diff options
Diffstat (limited to '')
217 files changed, 22677 insertions, 0 deletions
diff --git a/branches/sca-java-1.5.1/modules/core-databinding/LICENSE b/branches/sca-java-1.5.1/modules/core-databinding/LICENSE new file mode 100644 index 0000000000..8aa906c321 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-databinding/LICENSE @@ -0,0 +1,205 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + diff --git a/branches/sca-java-1.5.1/modules/core-databinding/NOTICE b/branches/sca-java-1.5.1/modules/core-databinding/NOTICE new file mode 100644 index 0000000000..fdfa0e9faa --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-databinding/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2008 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/branches/sca-java-1.5.1/modules/core-databinding/pom.xml b/branches/sca-java-1.5.1/modules/core-databinding/pom.xml new file mode 100644 index 0000000000..94779b5e4a --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-databinding/pom.xml @@ -0,0 +1,139 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. +--> +<project> + <parent> + <groupId>org.apache.tuscany.sca</groupId> + <artifactId>tuscany-modules</artifactId> + <version>1.6-SNAPSHOT</version> + <relativePath>../pom.xml</relativePath> + </parent> + <modelVersion>4.0.0</modelVersion> + <groupId>org.apache.tuscany.sca</groupId> + <artifactId>tuscany-core-databinding</artifactId> + <packaging>jar</packaging> + <name>Apache Tuscany SCA Core/DataBinding Integration</name> + + <dependencies> + <dependency> + <groupId>org.apache.tuscany.sca</groupId> + <artifactId>tuscany-databinding</artifactId> + <version>${project.version}</version> + <scope>compile</scope> + </dependency> + + <dependency> + <groupId>org.apache.tuscany.sca</groupId> + <artifactId>tuscany-databinding-jaxb</artifactId> + <version>${project.version}</version> + <scope>compile</scope> + </dependency> + + <dependency> + <groupId>org.apache.tuscany.sca</groupId> + <artifactId>tuscany-core</artifactId> + <version>${project.version}</version> + <scope>compile</scope> + </dependency> + + <dependency> + <groupId>org.apache.tuscany.sca</groupId> + <artifactId>tuscany-core-spi</artifactId> + <version>${project.version}</version> + <scope>compile</scope> + </dependency> + + <dependency> + <groupId>org.apache.tuscany.sca</groupId> + <artifactId>tuscany-interface-java-xml</artifactId> + <version>${project.version}</version> + <scope>compile</scope> + </dependency> + + <dependency> + <groupId>org.apache.tuscany.sca</groupId> + <artifactId>tuscany-interface-java-jaxws</artifactId> + <version>${project.version}</version> + <scope>compile</scope> + </dependency> + + <dependency> + <groupId>org.codehaus.woodstox</groupId> + <artifactId>wstx-asl</artifactId> + <scope>runtime</scope> + <version>3.2.4</version> + <exclusions> + <exclusion> + <groupId>stax</groupId> + <artifactId>stax-api</artifactId> + </exclusion> + </exclusions> + </dependency> + + <dependency> + <groupId>org.apache.ws.commons.axiom</groupId> + <artifactId>axiom-api</artifactId> + <version>1.2.7</version> + <exclusions> + <exclusion> + <groupId>xerces</groupId> + <artifactId>xercesImpl</artifactId> + </exclusion> + <exclusion> + <groupId>javax.mail</groupId> + <artifactId>mail</artifactId> + </exclusion> + <exclusion> + <groupId>commons-logging</groupId> + <artifactId>commons-logging</artifactId> + </exclusion> + <exclusion> + <groupId>xml-apis</groupId> + <artifactId>xml-apis</artifactId> + </exclusion> + </exclusions> + </dependency> + + <dependency> + <groupId>org.apache.ws.commons.axiom</groupId> + <artifactId>axiom-impl</artifactId> + <version>1.2.7</version> + <scope>runtime</scope> + </dependency> + </dependencies> + + <build> + <plugins> + <plugin> + <groupId>org.apache.felix</groupId> + <artifactId>maven-bundle-plugin</artifactId> + + <configuration> + <instructions> + <Bundle-Version>${tuscany.version}</Bundle-Version> + <Bundle-SymbolicName>org.apache.tuscany.sca.core.databinding</Bundle-SymbolicName> + <Bundle-Description>${pom.name}</Bundle-Description> + <Export-Package>org.apache.tuscany.sca.core.databinding*</Export-Package> + </instructions> + </configuration> + </plugin> + </plugins> + </build> + +</project> diff --git a/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/module/DataBindingModuleActivator.java b/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/module/DataBindingModuleActivator.java new file mode 100644 index 0000000000..4e0e58e6a1 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/module/DataBindingModuleActivator.java @@ -0,0 +1,111 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core.databinding.module; + +import org.apache.axiom.om.OMElement; +import org.apache.tuscany.sca.contribution.ModelFactoryExtensionPoint; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.core.ModuleActivator; +import org.apache.tuscany.sca.core.UtilityExtensionPoint; +import org.apache.tuscany.sca.core.databinding.processor.DataBindingJavaInterfaceProcessor; +import org.apache.tuscany.sca.core.databinding.processor.WrapperJavaInterfaceProcessor; +import org.apache.tuscany.sca.core.databinding.transformers.Array2ArrayTransformer; +import org.apache.tuscany.sca.core.databinding.transformers.CallableReference2XMLStreamReader; +import org.apache.tuscany.sca.core.databinding.transformers.CallableReferenceDataBinding; +import org.apache.tuscany.sca.core.databinding.transformers.CallableReferenceXMLAdapter; +import org.apache.tuscany.sca.core.databinding.transformers.Exception2ExceptionTransformer; +import org.apache.tuscany.sca.core.databinding.transformers.Input2InputTransformer; +import org.apache.tuscany.sca.core.databinding.transformers.OMElementXMLAdapter; +import org.apache.tuscany.sca.core.databinding.transformers.Output2OutputTransformer; +import org.apache.tuscany.sca.core.databinding.transformers.XMLStreamReader2CallableReference; +import org.apache.tuscany.sca.core.databinding.wire.DataBindingRuntimeWireProcessor; +import org.apache.tuscany.sca.databinding.DataBindingExtensionPoint; +import org.apache.tuscany.sca.databinding.Mediator; +import org.apache.tuscany.sca.databinding.TransformerExtensionPoint; +import org.apache.tuscany.sca.databinding.impl.Group2GroupTransformer; +import org.apache.tuscany.sca.databinding.jaxb.XMLAdapterExtensionPoint; +import org.apache.tuscany.sca.interfacedef.FaultExceptionMapper; +import org.apache.tuscany.sca.interfacedef.java.JavaInterfaceFactory; +import org.apache.tuscany.sca.interfacedef.java.jaxws.JAXWSFaultExceptionMapper; +import org.apache.tuscany.sca.interfacedef.java.jaxws.JAXWSJavaInterfaceProcessor; +import org.apache.tuscany.sca.interfacedef.java.jaxws.WebServiceInterfaceProcessor; +import org.apache.tuscany.sca.runtime.RuntimeWireProcessorExtensionPoint; +import org.osoa.sca.CallableReference; + +/** + * @version $Rev$ $Date$ + */ +public class DataBindingModuleActivator implements ModuleActivator { + + public void start(ExtensionPointRegistry registry) { + DataBindingExtensionPoint dataBindings = registry.getExtensionPoint(DataBindingExtensionPoint.class); + TransformerExtensionPoint transformers = registry.getExtensionPoint(TransformerExtensionPoint.class); + + XMLAdapterExtensionPoint xmlAdapterExtensionPoint = registry.getExtensionPoint(XMLAdapterExtensionPoint.class); + xmlAdapterExtensionPoint.addAdapter(CallableReference.class, CallableReferenceXMLAdapter.class); + xmlAdapterExtensionPoint.addAdapter(OMElement.class, OMElementXMLAdapter.class); + FaultExceptionMapper faultExceptionMapper = new JAXWSFaultExceptionMapper(dataBindings, xmlAdapterExtensionPoint); + registry.getExtensionPoint(UtilityExtensionPoint.class).addUtility(faultExceptionMapper); + + Mediator mediator = registry.getExtensionPoint(UtilityExtensionPoint.class).getUtility(Mediator.class); + + Input2InputTransformer input2InputTransformer = new Input2InputTransformer(); + input2InputTransformer.setMediator(mediator); + transformers.addTransformer(input2InputTransformer, true); + + Output2OutputTransformer output2OutputTransformer = new Output2OutputTransformer(); + output2OutputTransformer.setMediator(mediator); + transformers.addTransformer(output2OutputTransformer, true); + + Exception2ExceptionTransformer exception2ExceptionTransformer = new Exception2ExceptionTransformer(mediator, faultExceptionMapper); + transformers.addTransformer(exception2ExceptionTransformer, false); + + Array2ArrayTransformer array2ArrayTransformer = new Array2ArrayTransformer(); + array2ArrayTransformer.setMediator(mediator); + transformers.addTransformer(array2ArrayTransformer, true); + + Group2GroupTransformer group2GroupTransformer = new Group2GroupTransformer(); + group2GroupTransformer.setMediator(mediator); + transformers.addTransformer(group2GroupTransformer, true); + + dataBindings.addDataBinding(new CallableReferenceDataBinding()); + transformers.addTransformer(new CallableReference2XMLStreamReader(), true); + transformers.addTransformer(new XMLStreamReader2CallableReference(), false); + + ModelFactoryExtensionPoint modelFactories = registry.getExtensionPoint(ModelFactoryExtensionPoint.class); + JavaInterfaceFactory javaFactory = modelFactories.getFactory(JavaInterfaceFactory.class); + // Add the WebServiceInterfaceProcessor to mark the interface remotable + javaFactory.addInterfaceVisitor(new WebServiceInterfaceProcessor()); + // Introspect the data types + javaFactory.addInterfaceVisitor(new DataBindingJavaInterfaceProcessor(dataBindings)); + javaFactory.addInterfaceVisitor(new JAXWSJavaInterfaceProcessor(dataBindings, faultExceptionMapper, xmlAdapterExtensionPoint)); + javaFactory.addInterfaceVisitor(new WrapperJavaInterfaceProcessor(dataBindings)); + + + RuntimeWireProcessorExtensionPoint wireProcessorExtensionPoint = registry.getExtensionPoint(RuntimeWireProcessorExtensionPoint.class); + if (wireProcessorExtensionPoint != null) { + wireProcessorExtensionPoint.addWireProcessor(new DataBindingRuntimeWireProcessor(mediator, dataBindings, faultExceptionMapper)); + } + + } + + public void stop(ExtensionPointRegistry registry) { + } +} diff --git a/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/processor/DataBindingJavaInterfaceProcessor.java b/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/processor/DataBindingJavaInterfaceProcessor.java new file mode 100644 index 0000000000..8f35b2b00f --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/processor/DataBindingJavaInterfaceProcessor.java @@ -0,0 +1,141 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core.databinding.processor; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.tuscany.sca.databinding.DataBindingExtensionPoint; +import org.apache.tuscany.sca.databinding.annotation.DataBinding; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.InvalidInterfaceException; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.interfacedef.java.JavaInterface; +import org.apache.tuscany.sca.interfacedef.java.JavaOperation; +import org.apache.tuscany.sca.interfacedef.java.introspect.JavaInterfaceVisitor; + +/** + * The databinding annotation processor for java interfaces + * + * @version $Rev$ $Date$ + */ +public class DataBindingJavaInterfaceProcessor implements JavaInterfaceVisitor { + private DataBindingExtensionPoint dataBindingRegistry; + + public DataBindingJavaInterfaceProcessor(DataBindingExtensionPoint dataBindingRegistry) { + super(); + this.dataBindingRegistry = dataBindingRegistry; + } + + public void visitInterface(JavaInterface javaInterface) throws InvalidInterfaceException { + if (!javaInterface.isRemotable()) { + return; + } + List<Operation> operations = javaInterface.getOperations(); + processInterface(javaInterface, operations); + } + + private void processInterface(JavaInterface javaInterface, List<Operation> operations) { + Class<?> clazz = javaInterface.getJavaClass(); + DataBinding dataBinding = clazz.getAnnotation(DataBinding.class); + String dataBindingId = null; + boolean wrapperStyle = false; + if (dataBinding != null) { + dataBindingId = dataBinding.value(); + wrapperStyle = dataBinding.wrapped(); + } + + Map<String, Operation> opMap = new HashMap<String, Operation>(); + for (Operation op : javaInterface.getOperations()) { + opMap.put(op.getName(), op); + // In the case of @WebMethod, the method name can be different from the operation name + if (op instanceof JavaOperation) { + opMap.put(((JavaOperation)op).getJavaMethod().getName(), op); + } + if (dataBindingId != null) { + op.setDataBinding(dataBindingId); + op.setInputWrapperStyle(wrapperStyle); + op.setOutputWrapperStyle(wrapperStyle); + } + } + for (Method method : clazz.getMethods()) { + if (method.getDeclaringClass() == Object.class) { + continue; + } + Operation operation = opMap.get(method.getName()); + if (operation == null) { // @WebMethod exclude=true + continue; + } + DataBinding methodDataBinding = clazz.getAnnotation(DataBinding.class); + if (methodDataBinding == null) { + methodDataBinding = dataBinding; + } + dataBindingId = null; + wrapperStyle = false; + if (dataBinding != null) { + dataBindingId = dataBinding.value(); + wrapperStyle = dataBinding.wrapped(); + operation.setDataBinding(dataBindingId); + operation.setInputWrapperStyle(wrapperStyle); + operation.setOutputWrapperStyle(wrapperStyle); + } + + // FIXME: We need a better way to identify simple java types + int i = 0; + for (org.apache.tuscany.sca.interfacedef.DataType<?> d : operation.getInputType().getLogical()) { + if (d.getDataBinding() == null) { + d.setDataBinding(dataBindingId); + } + for (Annotation a : method.getParameterAnnotations()[i]) { + if (a.annotationType() == org.apache.tuscany.sca.databinding.annotation.DataType.class) { + String value = ((org.apache.tuscany.sca.databinding.annotation.DataType)a).value(); + d.setDataBinding(value); + } + } + dataBindingRegistry.introspectType(d, operation); + i++; + } + if (operation.getOutputType() != null) { + DataType<?> d = operation.getOutputType(); + if (d.getDataBinding() == null) { + d.setDataBinding(dataBindingId); + } + org.apache.tuscany.sca.databinding.annotation.DataType dt = + method.getAnnotation(org.apache.tuscany.sca.databinding.annotation.DataType.class); + if (dt != null) { + d.setDataBinding(dt.value()); + } + dataBindingRegistry.introspectType(d, operation); + } + /* It's now done in the JAXWS java interface processor + for (org.apache.tuscany.sca.interfacedef.DataType<?> d : operation.getFaultTypes()) { + if (d.getDataBinding() == null) { + d.setDataBinding(dataBindingId); + // TODO: Handle exceptions + dataBindingRegistry.introspectType(d, operation); + } + } + */ + } + } +} diff --git a/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/processor/WrapperJavaInterfaceProcessor.java b/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/processor/WrapperJavaInterfaceProcessor.java new file mode 100644 index 0000000000..702da720a0 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/processor/WrapperJavaInterfaceProcessor.java @@ -0,0 +1,128 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core.databinding.processor; + +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; + +import org.apache.tuscany.sca.databinding.DataBindingExtensionPoint; +import org.apache.tuscany.sca.databinding.WrapperHandler; +import org.apache.tuscany.sca.databinding.javabeans.JavaBeansDataBinding; +import org.apache.tuscany.sca.databinding.javabeans.SimpleJavaDataBinding; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.InvalidInterfaceException; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.interfacedef.java.JavaInterface; +import org.apache.tuscany.sca.interfacedef.java.introspect.JavaInterfaceVisitor; +import org.apache.tuscany.sca.interfacedef.util.WrapperInfo; + +/** + * The databinding annotation processor for java interfaces + * + * @version $Rev$ $Date$ + */ +public class WrapperJavaInterfaceProcessor implements JavaInterfaceVisitor { + private static final String JAXB_DATABINDING = "javax.xml.bind.JAXBElement"; + private DataBindingExtensionPoint dataBindingRegistry; + + public WrapperJavaInterfaceProcessor(DataBindingExtensionPoint dataBindingRegistry) { + super(); + this.dataBindingRegistry = dataBindingRegistry; + } + + public void visitInterface(JavaInterface javaInterface) throws InvalidInterfaceException { + if (!javaInterface.isRemotable()) { + return; + } + for (Operation operation : javaInterface.getOperations()) { + WrapperInfo inputWrapperInfo = operation.getInputWrapper(); + WrapperInfo outputWrapperInfo = operation.getOutputWrapper(); + if (inputWrapperInfo == null || outputWrapperInfo == null) { + continue; + } + // JIRA: TUSCANY-842 + String db = inputWrapperInfo.getDataBinding(); + if (db == null || JAXB_DATABINDING.equals(db)) { + db = assignOperationDataBinding(operation); + } + + // Introspect the wrapper data type + org.apache.tuscany.sca.databinding.DataBinding dbObj = dataBindingRegistry.getDataBinding(db); + WrapperHandler handler = dbObj == null ? null : dbObj.getWrapperHandler(); + if (handler != null) { + inputWrapperInfo.setWrapperType(handler.getWrapperType(operation, true)); + outputWrapperInfo.setWrapperType(handler.getWrapperType(operation, false)); + } + if (dbObj != null && handler == null) { + // To avoid JAXB wrapper bean generation + inputWrapperInfo.setWrapperType(null); + outputWrapperInfo.setWrapperType(null); + } + } + } + + /* + * Assigns an operation DB if one of the input types, output type, fault types has a non-default DB. + * However, if two of the input types, output type, fault types have two different non-default DBs + * ( e.g. SDO and JAXB), then we do nothing to the operation DB. + * + * The method logic assumes the JavaBeans DataBinding is the default + */ + private String assignOperationDataBinding(Operation operation) { + + Set<String> dbs = new HashSet<String>(); + + // Can't use DataType<?> since operation.getInputType() returns: DataType<List<DataType>> + List<DataType> opDataTypes = new LinkedList<DataType>(); + + opDataTypes.addAll(operation.getInputType().getLogical()); + opDataTypes.add(operation.getOutputType()); +/* + for (DataType<DataType> ft : operation.getFaultTypes()) { + opDataTypes.add(ft.getLogical()); + } +*/ + + for (DataType<?> d : opDataTypes) { + if (d != null) { + String dataBinding = d.getDataBinding(); + if ("java:array".equals(dataBinding)) { + dataBinding = ((DataType)d.getLogical()).getDataBinding(); + } + if (dataBinding != null) { + dbs.add(dataBinding); + } + } + } + + dbs.remove(JavaBeansDataBinding.NAME); + dbs.remove(SimpleJavaDataBinding.NAME); + + if (dbs.size() == 1) { + String db = dbs.iterator().next(); + operation.getInputWrapper().setDataBinding(db); + return db; + } else { + return operation.getInputWrapper().getDataBinding(); + } + } +} diff --git a/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/transformers/Array2ArrayTransformer.java b/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/transformers/Array2ArrayTransformer.java new file mode 100644 index 0000000000..38ca2cd10c --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/transformers/Array2ArrayTransformer.java @@ -0,0 +1,110 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.databinding.transformers; + +import java.lang.reflect.Array; + +import org.apache.tuscany.sca.databinding.Mediator; +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.osoa.sca.annotations.Reference; + +/** + * This is a special transformer to transform the output from one IDL to the + * other one + * + * @version $Rev$ $Date$ + */ +public class Array2ArrayTransformer extends BaseTransformer<Object, Object> implements PullTransformer<Object, Object> { + + protected Mediator mediator; + + public Array2ArrayTransformer() { + super(); + } + + /** + * @param mediator the mediator to set + */ + @Reference + public void setMediator(Mediator mediator) { + this.mediator = mediator; + } + + @Override + public String getSourceDataBinding() { + return "java:array"; + } + + @Override + public String getTargetDataBinding() { + return "java:array"; + } + + /** + * @see org.apache.tuscany.sca.databinding.impl.BaseTransformer#getSourceType() + */ + @Override + protected Class<Object> getSourceType() { + return Object.class; + } + + /** + * @see org.apache.tuscany.sca.databinding.impl.BaseTransformer#getTargetType() + */ + @Override + protected Class<Object> getTargetType() { + return Object.class; + } + + /** + * @see org.apache.tuscany.sca.databinding.Transformer#getWeight() + */ + @Override + public int getWeight() { + return 10; + } + + @SuppressWarnings("unchecked") + public Object transform(Object array, TransformationContext context) { + try { + if (array == null) { + return null; + } + DataType<DataType> sourceType = context.getSourceDataType(); + DataType<DataType> targetType = context.getTargetDataType(); + int length = Array.getLength(array); + Object targetArray = Array.newInstance(targetType.getPhysical().getComponentType(), length); + for (int i = 0; i < length; i++) { + Object sourceItem = Array.get(array, i); + Object targetItem = + mediator.mediate(sourceItem, sourceType.getLogical(), targetType.getLogical(), context + .getMetadata()); + Array.set(targetArray, i, targetItem); + } + return targetArray; + } catch (Exception e) { + throw new TransformationException(e); + } + } + +} diff --git a/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/transformers/CallableReference2XMLStreamReader.java b/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/transformers/CallableReference2XMLStreamReader.java new file mode 100644 index 0000000000..124928db24 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/transformers/CallableReference2XMLStreamReader.java @@ -0,0 +1,75 @@ +/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tuscany.sca.core.databinding.transformers;
+
+import javax.xml.stream.XMLStreamReader;
+
+import org.apache.tuscany.sca.core.context.CallableReferenceImpl;
+import org.apache.tuscany.sca.databinding.PullTransformer;
+import org.apache.tuscany.sca.databinding.TransformationContext;
+import org.apache.tuscany.sca.databinding.TransformationException;
+import org.apache.tuscany.sca.databinding.impl.BaseTransformer;
+import org.apache.tuscany.sca.databinding.xml.StAXHelper;
+import org.osoa.sca.CallableReference;
+
+public class CallableReference2XMLStreamReader extends BaseTransformer<CallableReference, XMLStreamReader> implements
+ PullTransformer<CallableReference, XMLStreamReader> {
+
+ @Override
+ protected Class<CallableReference> getSourceType() {
+ return CallableReference.class;
+ }
+
+ @Override
+ protected Class<XMLStreamReader> getTargetType() {
+ return XMLStreamReader.class;
+ }
+
+ public XMLStreamReader transform(CallableReference source, TransformationContext context) {
+ try {
+ if (source != null) {
+ if (source instanceof CallableReferenceImpl) {
+ XMLStreamReader xmlReader = ((CallableReferenceImpl)source).getXMLReader();
+ if (xmlReader != null) {
+ return xmlReader;
+ } else {
+ String xmlString = ((CallableReferenceImpl)source).toXMLString();
+
+ // remove "<?xml...?>" processing instruction and wrap with a top-level element
+ return StAXHelper.createXMLStreamReader("<reference xmlns=\"http://callable\">"
+ + xmlString.substring(xmlString.indexOf("?>") + 2)
+ + "</reference>");
+ }
+ } else {
+ throw new TransformationException("Unrecognized transformation source object");
+ }
+ } else {
+ return null;
+ }
+ } catch (Exception e) {
+ throw new TransformationException(e);
+ }
+ }
+
+ @Override
+ public int getWeight() {
+ return 10;
+ }
+
+}
diff --git a/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/transformers/CallableReferenceDataBinding.java b/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/transformers/CallableReferenceDataBinding.java new file mode 100644 index 0000000000..8733b91cd4 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/transformers/CallableReferenceDataBinding.java @@ -0,0 +1,42 @@ +/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.tuscany.sca.core.databinding.transformers;
+
+import org.apache.tuscany.sca.databinding.XMLTypeHelper;
+import org.apache.tuscany.sca.databinding.impl.BaseDataBinding;
+import org.osoa.sca.CallableReference;
+
+public class CallableReferenceDataBinding extends BaseDataBinding {
+
+ public static final String NAME = CallableReference.class.getName();
+
+ private CallableReferenceTypeHelper xmlTypeHelper;
+
+ public CallableReferenceDataBinding() {
+ super(NAME, CallableReference.class);
+ this.xmlTypeHelper = new CallableReferenceTypeHelper();
+ }
+
+ @Override
+ public XMLTypeHelper getXMLTypeHelper() {
+ return xmlTypeHelper;
+ }
+
+}
diff --git a/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/transformers/CallableReferenceTypeHelper.java b/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/transformers/CallableReferenceTypeHelper.java new file mode 100644 index 0000000000..97629ea7b5 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/transformers/CallableReferenceTypeHelper.java @@ -0,0 +1,75 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core.databinding.transformers; + +import java.beans.Introspector; +import java.util.ArrayList; +import java.util.List; +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.databinding.XMLTypeHelper; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.Interface; +import org.apache.tuscany.sca.interfacedef.util.JavaXMLMapper; +import org.apache.tuscany.sca.interfacedef.util.TypeInfo; +import org.apache.tuscany.sca.interfacedef.util.XMLType; +import org.apache.tuscany.sca.xsd.XSDFactory; +import org.apache.tuscany.sca.xsd.XSDefinition; + +/** + * + * @version $Rev$ $Date$ + */ +public class CallableReferenceTypeHelper implements XMLTypeHelper { + private static final String SCHEMA_NS = "http://www.w3.org/2001/XMLSchema"; + private static final String ANYTYPE_NAME = "anyType"; + private static final QName ANYTYPE_QNAME = new QName(SCHEMA_NS, ANYTYPE_NAME); + + public CallableReferenceTypeHelper() { + super(); + } + + public TypeInfo getTypeInfo(Class javaType, Object logical) { + QName xmlType = JavaXMLMapper.getXMLType(javaType); + if (xmlType != null) { + return new TypeInfo(xmlType, true, null); + } else if (javaType.isInterface()) { + return new TypeInfo(ANYTYPE_QNAME, true, null); + } else { + if (logical instanceof XMLType) { + xmlType = ((XMLType)logical).getTypeName(); + } + if (xmlType == null) { + xmlType = new QName(Introspector.decapitalize(javaType.getSimpleName())); + } + return new TypeInfo(xmlType, false, null); + } + } + + public List<XSDefinition> getSchemaDefinitions(XSDFactory factory, ModelResolver resolver, Interface intf) { + return new ArrayList<XSDefinition>(); + } + + public List<XSDefinition> getSchemaDefinitions(XSDFactory factory, ModelResolver resolver, List<DataType> dataTypes) { + return new ArrayList<XSDefinition>(); + } + +} diff --git a/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/transformers/CallableReferenceXMLAdapter.java b/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/transformers/CallableReferenceXMLAdapter.java new file mode 100644 index 0000000000..ff6e444dcd --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/transformers/CallableReferenceXMLAdapter.java @@ -0,0 +1,61 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core.databinding.transformers; + +import java.io.StringReader; +import java.io.StringWriter; + +import javax.xml.bind.annotation.adapters.XmlAdapter; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamReader; +import javax.xml.transform.Source; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.stream.StreamResult; +import javax.xml.transform.stream.StreamSource; + +import org.apache.tuscany.sca.databinding.xml.XMLStreamReader2String; +import org.osoa.sca.CallableReference; + +/** + * @version $Rev$ $Date$ + */ +public class CallableReferenceXMLAdapter extends XmlAdapter<Source, CallableReference> { + private TransformerFactory transformerFactory = TransformerFactory.newInstance(); + private XMLInputFactory inputFactory = XMLInputFactory.newInstance(); + + @Override + public CallableReference unmarshal(Source v) throws Exception { + StringWriter sw = new StringWriter(); + StreamResult result = new StreamResult(sw); + transformerFactory.newTransformer().transform(v, result); + XMLStreamReader reader = inputFactory.createXMLStreamReader(new StringReader(sw.toString())); + XMLStreamReader2CallableReference t2 = new XMLStreamReader2CallableReference(); + return t2.transform(reader, null); + } + + @Override + public Source marshal(CallableReference v) throws Exception { + CallableReference2XMLStreamReader t = new CallableReference2XMLStreamReader(); + XMLStreamReader reader = t.transform(v, null); + XMLStreamReader2String t2 = new XMLStreamReader2String(); + String xml = t2.transform(reader, null); + return new StreamSource(new StringReader(xml)); + } +} diff --git a/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/transformers/Exception2ExceptionTransformer.java b/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/transformers/Exception2ExceptionTransformer.java new file mode 100644 index 0000000000..6e2e714bdb --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/transformers/Exception2ExceptionTransformer.java @@ -0,0 +1,114 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core.databinding.transformers; + +import org.apache.tuscany.sca.databinding.DataBinding; +import org.apache.tuscany.sca.databinding.Mediator; +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.FaultExceptionMapper; + +/** + * This is a special transformer to transform the exception from one IDL to the + * other one + * + * @version $Rev$ $Date$ + */ +public class Exception2ExceptionTransformer extends BaseTransformer<Throwable, Throwable> implements + PullTransformer<Throwable, Throwable> { + + protected Mediator mediator; + protected FaultExceptionMapper faultExceptionMapper; + + public Exception2ExceptionTransformer(Mediator mediator, FaultExceptionMapper faultExceptionMapper) { + super(); + this.mediator = mediator; + this.faultExceptionMapper = faultExceptionMapper; + } + + public Exception2ExceptionTransformer() { + super(); + } + + @Override + public String getSourceDataBinding() { + return DataBinding.IDL_FAULT; + } + + @Override + public String getTargetDataBinding() { + return DataBinding.IDL_FAULT; + } + + /** + * @param mediator the mediator to set + */ + public void setMediator(Mediator mediator) { + this.mediator = mediator; + } + + /** + * @see org.apache.tuscany.sca.databinding.impl.BaseTransformer#getSourceType() + */ + @Override + protected Class<Throwable> getSourceType() { + return Throwable.class; + } + + /** + * @see org.apache.tuscany.sca.databinding.impl.BaseTransformer#getTargetType() + */ + @Override + protected Class<Throwable> getTargetType() { + return Throwable.class; + } + + /** + * @see org.apache.tuscany.sca.databinding.Transformer#getWeight() + */ + @Override + public int getWeight() { + return 10000; + } + + @SuppressWarnings("unchecked") + public Throwable transform(Throwable source, TransformationContext context) { + DataType<DataType> sourceType = context.getSourceDataType(); + + DataType<DataType> targetType = context.getTargetDataType(); + + Object sourceFaultInfo = faultExceptionMapper.getFaultInfo(source, sourceType.getLogical().getPhysical(), context.getSourceOperation()); + Object targetFaultInfo = + mediator.mediate(sourceFaultInfo, sourceType.getLogical(), targetType.getLogical(), context.getMetadata()); + + Throwable targetException = + faultExceptionMapper.wrapFaultInfo(targetType, source.getMessage(), targetFaultInfo, source.getCause(), context.getTargetOperation()); + + // FIXME + return targetException == null ? source : targetException; + + } + + public void setFaultExceptionMapper(FaultExceptionMapper faultExceptionMapper) { + this.faultExceptionMapper = faultExceptionMapper; + } +} diff --git a/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/transformers/Input2InputTransformer.java b/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/transformers/Input2InputTransformer.java new file mode 100644 index 0000000000..f537dc4524 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/transformers/Input2InputTransformer.java @@ -0,0 +1,279 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core.databinding.transformers; + +import java.util.List; +import java.util.logging.Logger; + +import org.apache.tuscany.sca.databinding.DataBinding; +import org.apache.tuscany.sca.databinding.Mediator; +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.WrapperHandler; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.interfacedef.util.ElementInfo; +import org.apache.tuscany.sca.interfacedef.util.WrapperInfo; +import org.apache.tuscany.sca.interfacedef.util.XMLType; +import org.osoa.sca.annotations.Reference; + +/** + * This is a special transformer to transform the input from one IDL to the + * other one + * + * @version $Rev$ $Date$ + */ +public class Input2InputTransformer extends BaseTransformer<Object[], Object[]> implements + PullTransformer<Object[], Object[]> { + private static final Logger logger = Logger.getLogger(Input2InputTransformer.class.getName()); + + protected Mediator mediator; + + public Input2InputTransformer() { + super(); + } + + @Override + public String getSourceDataBinding() { + return DataBinding.IDL_INPUT; + } + + @Override + public String getTargetDataBinding() { + return DataBinding.IDL_INPUT; + } + + /** + * @param mediator the mediator to set + */ + @Reference + public void setMediator(Mediator mediator) { + this.mediator = mediator; + } + + /** + * @see org.apache.tuscany.sca.databinding.impl.BaseTransformer#getSourceType() + */ + @Override + protected Class<Object[]> getSourceType() { + return Object[].class; + } + + /** + * @see org.apache.tuscany.sca.databinding.impl.BaseTransformer#getTargetType() + */ + @Override + protected Class<Object[]> getTargetType() { + return Object[].class; + } + + /** + * @see org.apache.tuscany.sca.databinding.Transformer#getWeight() + */ + @Override + public int getWeight() { + return 10000; + } + + /** + * Match the structure of the wrapper element. If it matches, then we can do + * wrapper to wrapper transformation. Otherwise, we do child to child. + * @param w1 + * @param w2 + * @return + */ + private boolean matches(WrapperInfo w1, WrapperInfo w2) { + if (w1 == null || w2 == null) { + return false; + } + if (!w1.getWrapperElement().equals(w2.getWrapperElement())) { + return false; + } + + // Compare the child elements + List<ElementInfo> list1 = w1.getChildElements(); + List<ElementInfo> list2 = w2.getChildElements(); + if (list1.size() != list2.size()) { + return false; + } + // FXIME: [rfeng] At this point, the J2W generates local elments under the namespace + // of the interface instead of "". We only compare the local parts only to work around + // the namespace mismatch + for (int i = 0; i < list1.size(); i++) { + String n1 = list1.get(i).getQName().getLocalPart(); + String n2 = list2.get(i).getQName().getLocalPart(); + if (!n1.equals(n2)) { + return false; + } + } + return true; + } + + @SuppressWarnings("unchecked") + public Object[] transform(Object[] source, TransformationContext context) { + // Check if the source operation is wrapped + DataType<List<DataType>> sourceType = context.getSourceDataType(); + Operation sourceOp = context.getSourceOperation(); + boolean sourceWrapped = sourceOp != null && sourceOp.isInputWrapperStyle() && sourceOp.getInputWrapper() != null; + boolean sourceBare = sourceOp != null && !sourceOp.isInputWrapperStyle() && sourceOp.getInputWrapper() == null; + + // Find the wrapper handler for source data + WrapperHandler sourceWrapperHandler = null; + String sourceDataBinding = getDataBinding(sourceOp); + sourceWrapperHandler = getWrapperHandler(sourceDataBinding, sourceWrapped); + + // Check if the target operation is wrapped + DataType<List<DataType>> targetType = context.getTargetDataType(); + Operation targetOp = (Operation)context.getTargetOperation(); + boolean targetWrapped = targetOp != null && targetOp.isInputWrapperStyle() && targetOp.getInputWrapper() != null; + boolean targetBare = targetOp != null && !targetOp.isInputWrapperStyle() && targetOp.getInputWrapper() == null; + + // Find the wrapper handler for target data + WrapperHandler targetWrapperHandler = null; + String targetDataBinding = getDataBinding(targetOp); + targetWrapperHandler = getWrapperHandler(targetDataBinding, targetWrapped); + + if ((!sourceWrapped && !sourceBare) && targetWrapped) { + // Unwrapped --> Wrapped + WrapperInfo wrapper = targetOp.getInputWrapper(); + // ElementInfo wrapperElement = wrapper.getInputWrapperElement(); + + // Class<?> targetWrapperClass = wrapper != null ? wrapper.getInputWrapperClass() : null; + + if (source == null) { + // Empty child elements + Object targetWrapper = targetWrapperHandler.create(targetOp, true); + return new Object[] {targetWrapper}; + } + + // If the source can be wrapped, wrapped it first + if (sourceWrapperHandler != null) { + WrapperInfo sourceWrapperInfo = sourceOp.getInputWrapper(); + DataType sourceWrapperType = sourceWrapperInfo != null ? sourceWrapperInfo.getWrapperType() : null; + + // We only do wrapper to wrapper transformation if the source has a wrapper and both sides + // match by XML structure + if (sourceWrapperType != null && matches(sourceOp.getInputWrapper(), targetOp.getInputWrapper())) { + Class<?> sourceWrapperClass = sourceWrapperType.getPhysical(); + + // Create the source wrapper + Object sourceWrapper = sourceWrapperHandler.create(sourceOp, true); + + // Populate the source wrapper + if (sourceWrapper != null) { + sourceWrapperHandler.setChildren(sourceWrapper, + source, + sourceOp, + true); + + // Transform the data from source wrapper to target wrapper + Object targetWrapper = + mediator.mediate(sourceWrapper, sourceWrapperType, targetType.getLogical().get(0), context + .getMetadata()); + return new Object[] {targetWrapper}; + } + } + } + // Fall back to child by child transformation + Object targetWrapper = targetWrapperHandler.create(targetOp, true); + List<DataType> argTypes = wrapper.getUnwrappedInputType().getLogical(); + Object[] targetChildren = new Object[source.length]; + for (int i = 0; i < source.length; i++) { + // ElementInfo argElement = wrapper.getInputChildElements().get(i); + DataType<XMLType> argType = argTypes.get(i); + targetChildren[i] = + mediator.mediate(source[i], sourceType.getLogical().get(i), argType, context.getMetadata()); + } + targetWrapperHandler.setChildren(targetWrapper, + targetChildren, + targetOp, + true); + return new Object[] {targetWrapper}; + + } else if (sourceWrapped && (!targetWrapped && !targetBare)) { + // Wrapped to Unwrapped + Object sourceWrapper = source[0]; + Object[] target = null; + + // List<ElementInfo> childElements = sourceOp.getWrapper().getInputChildElements(); + if (targetWrapperHandler != null) { + // ElementInfo wrapperElement = sourceOp.getWrapper().getInputWrapperElement(); + // FIXME: This is a workaround for the wsdless support as it passes in child elements + // under the wrapper that only matches by position + if (sourceWrapperHandler.isInstance(sourceWrapper, sourceOp, true)) { + + WrapperInfo targetWrapperInfo = targetOp.getInputWrapper(); + DataType targetWrapperType = + targetWrapperInfo != null ? targetWrapperInfo.getWrapperType() : null; + if (targetWrapperType != null && matches(sourceOp.getInputWrapper(), targetOp.getInputWrapper())) { + Object targetWrapper = + mediator.mediate(sourceWrapper, sourceType.getLogical().get(0), targetWrapperType, context + .getMetadata()); + target = targetWrapperHandler.getChildren(targetWrapper, targetOp, true).toArray(); + return target; + } + } + } + Object[] sourceChildren = sourceWrapperHandler.getChildren(sourceWrapper, sourceOp, true).toArray(); + target = new Object[sourceChildren.length]; + for (int i = 0; i < sourceChildren.length; i++) { + DataType<XMLType> childType = sourceOp.getInputWrapper().getUnwrappedInputType().getLogical().get(i); + target[i] = + mediator.mediate(sourceChildren[i], childType, targetType.getLogical().get(i), context + .getMetadata()); + } + return target; + } else { + // Assuming wrapper to wrapper conversion can be handled here as well + Object[] newArgs = new Object[source.length]; + for (int i = 0; i < source.length; i++) { + Object child = + mediator.mediate(source[i], sourceType.getLogical().get(i), targetType.getLogical().get(i), context + .getMetadata()); + newArgs[i] = child; + } + return newArgs; + } + } + + private WrapperHandler getWrapperHandler(String dataBindingId, boolean required) { + WrapperHandler wrapperHandler = null; + if (dataBindingId != null) { + DataBinding dataBinding = mediator.getDataBindings().getDataBinding(dataBindingId); + wrapperHandler = dataBinding == null ? null : dataBinding.getWrapperHandler(); + } + if (wrapperHandler == null && required) { + throw new TransformationException("No wrapper handler is provided for databinding: " + dataBindingId); + } + return wrapperHandler; + } + + private String getDataBinding(Operation operation) { + WrapperInfo wrapper = operation.getInputWrapper(); + if (wrapper != null) { + return wrapper.getDataBinding(); + } else { + return null; + } + } + +} diff --git a/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/transformers/OMElementXMLAdapter.java b/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/transformers/OMElementXMLAdapter.java new file mode 100644 index 0000000000..ec67dabc15 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/transformers/OMElementXMLAdapter.java @@ -0,0 +1,62 @@ +/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tuscany.sca.core.databinding.transformers;
+
+import java.io.StringReader;
+import java.io.StringWriter;
+
+import javax.xml.transform.Source;
+import javax.xml.stream.XMLInputFactory;
+import javax.xml.stream.XMLStreamReader;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.stream.StreamResult;
+import javax.xml.transform.stream.StreamSource;
+import javax.xml.bind.annotation.adapters.XmlAdapter;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.impl.builder.StAXOMBuilder;
+import org.apache.tuscany.sca.databinding.xml.XMLStreamReader2String;
+
+/**
+ * This special XmlAdapter can be used by JAXB classes to convert from OMElement to Source
+ */
+public class OMElementXMLAdapter extends XmlAdapter<Source, OMElement> {
+
+ private TransformerFactory transformerFactory = TransformerFactory.newInstance();
+ private XMLInputFactory inputFactory = XMLInputFactory.newInstance();
+
+ @Override
+ public Source marshal(OMElement v) throws Exception {
+ XMLStreamReader reader = v.getXMLStreamReaderWithoutCaching();
+ XMLStreamReader2String t2 = new XMLStreamReader2String();
+ String xml = t2.transform(reader, null);
+ return new StreamSource(new StringReader(xml));
+ }
+
+ @Override
+ public OMElement unmarshal(Source v) throws Exception {
+ StringWriter sw = new StringWriter();
+ StreamResult result = new StreamResult(sw);
+ transformerFactory.newTransformer().transform(v, result);
+ XMLStreamReader reader = inputFactory.createXMLStreamReader(new StringReader(sw.toString()));
+ // Build OMElement from XMLStreamReader
+ StAXOMBuilder builder = new StAXOMBuilder(reader);
+ return builder.getDocumentElement();
+ }
+}
diff --git a/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/transformers/Output2OutputTransformer.java b/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/transformers/Output2OutputTransformer.java new file mode 100644 index 0000000000..348d8345b2 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/transformers/Output2OutputTransformer.java @@ -0,0 +1,257 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.databinding.transformers; + +import java.util.List; + +import org.apache.tuscany.sca.databinding.DataBinding; +import org.apache.tuscany.sca.databinding.Mediator; +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.WrapperHandler; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.interfacedef.util.ElementInfo; +import org.apache.tuscany.sca.interfacedef.util.WrapperInfo; +import org.apache.tuscany.sca.interfacedef.util.XMLType; +import org.osoa.sca.annotations.Reference; + +/** + * This is a special transformer to transform the output from one IDL to the + * other one + * + * @version $Rev$ $Date$ + */ +public class Output2OutputTransformer extends BaseTransformer<Object, Object> implements + PullTransformer<Object, Object> { + + protected Mediator mediator; + + /** + * @param wrapperHandler + */ + public Output2OutputTransformer() { + super(); + } + + /** + * @param mediator the mediator to set + */ + @Reference + public void setMediator(Mediator mediator) { + this.mediator = mediator; + } + + @Override + public String getSourceDataBinding() { + return DataBinding.IDL_OUTPUT; + } + + @Override + public String getTargetDataBinding() { + return DataBinding.IDL_OUTPUT; + } + + /** + * @see org.apache.tuscany.sca.databinding.impl.BaseTransformer#getSourceType() + */ + @Override + protected Class<Object> getSourceType() { + return Object.class; + } + + /** + * @see org.apache.tuscany.sca.databinding.impl.BaseTransformer#getTargetType() + */ + @Override + protected Class<Object> getTargetType() { + return Object.class; + } + + /** + * @see org.apache.tuscany.sca.databinding.Transformer#getWeight() + */ + @Override + public int getWeight() { + return 10; + } + + private String getDataBinding(Operation operation) { + WrapperInfo wrapper = operation.getOutputWrapper(); + if (wrapper != null) { + return wrapper.getDataBinding(); + } else { + return null; + } + } + + private WrapperHandler getWrapperHandler(String dataBindingId, boolean required) { + WrapperHandler wrapperHandler = null; + if (dataBindingId != null) { + DataBinding dataBinding = mediator.getDataBindings().getDataBinding(dataBindingId); + wrapperHandler = dataBinding == null ? null : dataBinding.getWrapperHandler(); + } + if (wrapperHandler == null && required) { + throw new TransformationException("No wrapper handler is provided for databinding: " + dataBindingId); + } + return wrapperHandler; + } + + /** + * Match the structure of the wrapper element. If it matches, then we can do + * wrapper to wrapper transformation. Otherwise, we do child to child. + * @param w1 + * @param w2 + * @return + */ + private boolean matches(WrapperInfo w1, WrapperInfo w2) { + if (w1 == null || w2 == null) { + return false; + } + if (!w1.getWrapperElement().equals(w2.getWrapperElement())) { + return false; + } + + // Compare the child elements + List<ElementInfo> list1 = w1.getChildElements(); + List<ElementInfo> list2 = w2.getChildElements(); + if (list1.size() != list2.size()) { + return false; + } + // FXIME: [rfeng] At this point, the J2W generates local elments under the namespace + // of the interface instead of "". We only compare the local parts only to work around + // the namespace mismatch + for (int i = 0; i < list1.size(); i++) { + String n1 = list1.get(i).getQName().getLocalPart(); + String n2 = list2.get(i).getQName().getLocalPart(); + if (!n1.equals(n2)) { + return false; + } + } + return true; + } + + @SuppressWarnings("unchecked") + public Object transform(Object response, TransformationContext context) { + try { + DataType<DataType> sourceType = context.getSourceDataType(); + Operation sourceOp = context.getSourceOperation(); + boolean sourceWrapped = sourceOp != null && sourceOp.isOutputWrapperStyle() && sourceOp.getOutputWrapper() != null; + boolean sourceBare = sourceOp != null && !sourceOp.isOutputWrapperStyle() && sourceOp.getOutputWrapper() == null; + + WrapperHandler sourceWrapperHandler = null; + String sourceDataBinding = getDataBinding(sourceOp); + sourceWrapperHandler = getWrapperHandler(sourceDataBinding, sourceWrapped); + + DataType<DataType> targetType = context.getTargetDataType(); + Operation targetOp = (Operation)context.getTargetOperation(); + boolean targetWrapped = targetOp != null && targetOp.isOutputWrapperStyle() && targetOp.getOutputWrapper() != null; + boolean targetBare = targetOp != null && !targetOp.isOutputWrapperStyle() && targetOp.getOutputWrapper() == null; + + WrapperHandler targetWrapperHandler = null; + String targetDataBinding = getDataBinding(targetOp); + targetWrapperHandler = getWrapperHandler(targetDataBinding, targetWrapped); + + if ((!sourceWrapped &&!sourceBare) && targetWrapped) { + // Unwrapped --> Wrapped + WrapperInfo wrapper = targetOp.getOutputWrapper(); + ElementInfo wrapperElement = wrapper.getWrapperElement(); + List<ElementInfo> childElements = wrapper.getChildElements(); + Class<?> targetWrapperClass = wrapper != null ? wrapper.getWrapperClass() : null; + + // If the source can be wrapped, wrapped it first + if (sourceWrapperHandler != null) { + WrapperInfo sourceWrapperInfo = sourceOp.getOutputWrapper(); + DataType sourceWrapperType = + sourceWrapperInfo != null ? sourceWrapperInfo.getWrapperType() : null; + + if (sourceWrapperType != null && matches(sourceOp.getOutputWrapper(), targetOp.getOutputWrapper())) { + Class<?> sourceWrapperClass = sourceWrapperType.getPhysical(); + + Object sourceWrapper = sourceWrapperHandler.create(sourceOp, false); + if (sourceWrapper != null) { + if (!childElements.isEmpty()) { + // Set the return value + sourceWrapperHandler.setChildren(sourceWrapper, + new Object[] {response}, + sourceOp, + false); + } + Object targetWrapper = + mediator.mediate(sourceWrapper, sourceWrapperType, targetType.getLogical(), context + .getMetadata()); + return targetWrapper; + } + } + } + Object targetWrapper = targetWrapperHandler.create(targetOp, false); + + if (childElements.isEmpty()) { + // void output + return targetWrapper; + } + + DataType<XMLType> argType = wrapper.getUnwrappedOutputType(); + Object child = response; + child = mediator.mediate(response, sourceType.getLogical(), argType, context.getMetadata()); + targetWrapperHandler.setChildren(targetWrapper, new Object[] {child}, targetOp, false); + return targetWrapper; + } else if (sourceWrapped && (!targetWrapped && !targetBare)) { + // Wrapped to Unwrapped + Object sourceWrapper = response; + List<ElementInfo> childElements = sourceOp.getOutputWrapper().getChildElements(); + if (childElements.isEmpty()) { + // The void output + return null; + } + if (targetWrapperHandler != null) { + ElementInfo wrapperElement = sourceOp.getOutputWrapper().getWrapperElement(); + + // FIXME: This is a workaround for the wsdless support as it passes in child elements + // under the wrapper that only matches by position + if (sourceWrapperHandler.isInstance(sourceWrapper, sourceOp, false)) { + + WrapperInfo targetWrapperInfo = targetOp.getOutputWrapper(); + DataType targetWrapperType = + targetWrapperInfo != null ? targetWrapperInfo.getWrapperType() : null; + + if (targetWrapperType != null && matches(sourceOp.getOutputWrapper(), targetOp.getOutputWrapper())) { + Object targetWrapper = + mediator.mediate(sourceWrapper, sourceType.getLogical(), targetWrapperType, context + .getMetadata()); + return targetWrapperHandler.getChildren(targetWrapper, targetOp, false).get(0); + } + } + } + Object child = sourceWrapperHandler.getChildren(sourceWrapper, sourceOp, false).get(0); + DataType<?> childType = sourceOp.getOutputWrapper().getUnwrappedOutputType(); + return mediator.mediate(child, childType, targetType.getLogical(), context.getMetadata()); + } else { + // FIXME: Do we want to handle wrapped to wrapped? + return mediator.mediate(response, sourceType.getLogical(), targetType.getLogical(), context + .getMetadata()); + } + } catch (Exception e) { + throw new TransformationException(e); + } + } + +} diff --git a/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/transformers/XMLStreamReader2CallableReference.java b/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/transformers/XMLStreamReader2CallableReference.java new file mode 100644 index 0000000000..841efa9398 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/transformers/XMLStreamReader2CallableReference.java @@ -0,0 +1,100 @@ +/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tuscany.sca.core.databinding.transformers;
+
+import static javax.xml.stream.XMLStreamConstants.START_ELEMENT;
+
+import java.lang.reflect.Constructor;
+
+import javax.xml.namespace.QName;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamReader;
+
+import org.apache.tuscany.sca.core.context.CallableReferenceImpl;
+import org.apache.tuscany.sca.core.context.ServiceReferenceImpl;
+import org.apache.tuscany.sca.databinding.PullTransformer;
+import org.apache.tuscany.sca.databinding.TransformationContext;
+import org.apache.tuscany.sca.databinding.TransformationException;
+import org.apache.tuscany.sca.databinding.impl.BaseTransformer;
+import org.osoa.sca.CallableReference;
+
+@SuppressWarnings("unchecked")
+public class XMLStreamReader2CallableReference extends BaseTransformer<XMLStreamReader, CallableReference>
+ implements PullTransformer<XMLStreamReader, CallableReference> {
+
+ private static final String SCA10_NS = "http://www.osoa.org/xmlns/sca/1.0";
+ private static final String COMPOSITE = "composite";
+ public static final QName COMPOSITE_QNAME = new QName(SCA10_NS, COMPOSITE);
+
+ public CallableReference transform(XMLStreamReader source, TransformationContext context) {
+ try {
+ if (source != null) {
+ skipTopLevelElement(source);
+ Class refType = context.getTargetDataType().getPhysical();
+ Class implType;
+ if (refType.isAssignableFrom(CallableReferenceImpl.class)) {
+ implType = CallableReferenceImpl.class;
+ } else if (refType.isAssignableFrom(ServiceReferenceImpl.class)) {
+ implType = ServiceReferenceImpl.class;
+ } else {
+ throw new TransformationException("Unrecognized transformation target type");
+ }
+ Constructor constructor = implType.getConstructor(new Class[] {XMLStreamReader.class});
+ return (CallableReference)constructor.newInstance(new Object[] {source});
+ } else {
+ return null;
+ }
+ } catch (Exception e) {
+ throw new TransformationException(e);
+ }
+ }
+
+ /*
+ * Step over top-level element added by CallableReference2XMLStreamReader
+ */
+ private void skipTopLevelElement(XMLStreamReader source) throws XMLStreamException {
+ while (source.hasNext()) {
+ int event = source.getEventType();
+ if (event == START_ELEMENT) {
+ QName name = source.getName();
+ if (COMPOSITE_QNAME.equals(name)) {
+ return;
+ }
+ }
+ source.next();
+ }
+ throw new TransformationException("<composite> element not found");
+ }
+
+ @Override
+ protected Class<XMLStreamReader> getSourceType() {
+ return XMLStreamReader.class;
+ }
+
+ @Override
+ protected Class<CallableReference> getTargetType() {
+ return CallableReference.class;
+ }
+
+ @Override
+ public int getWeight() {
+ return 10;
+ }
+
+}
diff --git a/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/wire/DataBindingRuntimeWireProcessor.java b/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/wire/DataBindingRuntimeWireProcessor.java new file mode 100644 index 0000000000..bad2be6679 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/wire/DataBindingRuntimeWireProcessor.java @@ -0,0 +1,198 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core.databinding.wire; + +import java.util.List; + +import org.apache.tuscany.sca.assembly.ComponentReference; +import org.apache.tuscany.sca.databinding.DataBindingExtensionPoint; +import org.apache.tuscany.sca.databinding.Mediator; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.FaultExceptionMapper; +import org.apache.tuscany.sca.interfacedef.InterfaceContract; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.Interceptor; +import org.apache.tuscany.sca.invocation.InvocationChain; +import org.apache.tuscany.sca.invocation.Phase; +import org.apache.tuscany.sca.runtime.RuntimeWire; +import org.apache.tuscany.sca.runtime.RuntimeWireProcessor; + +/** + * This processor is responsible to add an interceptor to invocation chain if + * the source and target operations have different databinding requirements + * + * @version $Rev$ $Date$ + */ +public class DataBindingRuntimeWireProcessor implements RuntimeWireProcessor { + private Mediator mediator; + private DataBindingExtensionPoint dataBindings; + private FaultExceptionMapper faultExceptionMapper; + + public DataBindingRuntimeWireProcessor(Mediator mediator, + DataBindingExtensionPoint dataBindings, + FaultExceptionMapper faultExceptionMapper) { + super(); + this.mediator = mediator; + this.dataBindings = dataBindings; + this.faultExceptionMapper = faultExceptionMapper; + } + + public boolean isTransformationRequired(DataType source, DataType target) { + if (source == null || target == null) { // void return type + return false; + } + if (source == target) { + return false; + } + + // Output type can be null + if (source == null && target == null) { + return false; + } else if (source == null || target == null) { + return true; + } + String sourceDataBinding = source.getDataBinding(); + String targetDataBinding = target.getDataBinding(); + if (sourceDataBinding == targetDataBinding) { + return false; + } + if (sourceDataBinding == null || targetDataBinding == null) { + // TODO: If any of the databinding is null, then no transformation + return false; + } + return !sourceDataBinding.equals(targetDataBinding); + } + + public boolean isTransformationRequired(Operation source, Operation target) { + if (source == target) { + return false; + } + + if (source.isInputWrapperStyle() != target.isInputWrapperStyle()) { + return true; + } + + if (source.isOutputWrapperStyle() != target.isOutputWrapperStyle()) { + return true; + } + + // Check output type + DataType sourceOutputType = source.getOutputType(); + DataType targetOutputType = target.getOutputType(); + + // Note the target output type is now the source for checking + // compatibility + if (isTransformationRequired(targetOutputType, sourceOutputType)) { + return true; + } + + List<DataType> sourceInputType = source.getInputType().getLogical(); + List<DataType> targetInputType = target.getInputType().getLogical(); + + int size = sourceInputType.size(); + if (size != targetInputType.size()) { + // TUSCANY-1682: The wrapper style may have different arguments + return true; + } + for (int i = 0; i < size; i++) { + if (isTransformationRequired(sourceInputType.get(i), targetInputType.get(i))) { + return true; + } + } + + return false; + } + + private boolean isTransformationRequired(InterfaceContract sourceContract, + Operation sourceOperation, + InterfaceContract targetContract, + Operation targetOperation) { + if (targetContract == null) { + targetContract = sourceContract; + } + if (sourceContract == targetContract) { + return false; + } + return isTransformationRequired(sourceOperation, targetOperation); + } + + public void process(RuntimeWire wire) { + InterfaceContract sourceContract = wire.getSource().getInterfaceContract(); + InterfaceContract targetContract = wire.getTarget().getInterfaceContract(); + if (targetContract == null) { + targetContract = sourceContract; + } + + if (!sourceContract.getInterface().isRemotable()) { + return; + } + List<InvocationChain> chains = wire.getInvocationChains(); + for (InvocationChain chain : chains) { + Operation sourceOperation = chain.getSourceOperation(); + Operation targetOperation = chain.getTargetOperation(); + + Interceptor interceptor = null; + if (isTransformationRequired(sourceContract, sourceOperation, targetContract, targetOperation)) { + // Add the interceptor to the source side because multiple + // references can be wired to the same service + interceptor = + new DataTransformationInterceptor(wire, sourceOperation, targetOperation, mediator); + } else { + // assume pass-by-values copies are required if interfaces are remotable and there is no data binding + // transformation, i.e. a transformation will result in a copy so another pass-by-value copy is unnecessary + if (!isOnMessage(targetOperation) && isRemotable(chain, sourceOperation, targetOperation)) { + interceptor = + new PassByValueInterceptor(mediator, chain, targetOperation); + } + } + if (interceptor != null) { + String phase = + (wire.getSource().getContract() instanceof ComponentReference) ? Phase.REFERENCE_INTERFACE + : Phase.SERVICE_INTERFACE; + chain.addInterceptor(phase, interceptor); + } + } + + } + + /** + * FIXME: TUSCANY-2586, temporary work around till the JIRA is fixed to prevent + * the PassByValueInterceptor being used for services when the binding protocol + * doesn't need the copies done. + */ + protected boolean isOnMessage(Operation op) { + return "onMessage".equals(op.getName()); + } + + /** + * Pass-by-value copies are required if the interfaces are remotable unless the + * implementation uses the @AllowsPassByReference annotation. + */ + protected boolean isRemotable(InvocationChain chain, Operation sourceOperation, Operation targetOperation) { + if (!sourceOperation.getInterface().isRemotable()) { + return false; + } + if (!targetOperation.getInterface().isRemotable()) { + return false; + } + return true; + } + +} diff --git a/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/wire/DataTransformationInterceptor.java b/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/wire/DataTransformationInterceptor.java new file mode 100644 index 0000000000..79c442450b --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/wire/DataTransformationInterceptor.java @@ -0,0 +1,104 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core.databinding.wire; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.tuscany.sca.databinding.Mediator; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.DataExchangeSemantics; +import org.apache.tuscany.sca.invocation.Interceptor; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.Message; +import org.apache.tuscany.sca.runtime.RuntimeWire; + +/** + * An interceptor to transform data across databindings on the wire + * + * @version $Rev$ $Date$ + */ +public class DataTransformationInterceptor implements Interceptor, DataExchangeSemantics { + private Invoker next; + + private Operation sourceOperation; + + private Operation targetOperation; + private RuntimeWire wire; + private Mediator mediator; + + public DataTransformationInterceptor(RuntimeWire wire, + Operation sourceOperation, + Operation targetOperation, + Mediator mediator) { + super(); + this.sourceOperation = sourceOperation; + this.targetOperation = targetOperation; + this.mediator = mediator; + this.wire = wire; + } + + public Invoker getNext() { + return next; + } + + public Message invoke(Message msg) { + Map<String, Object> metadata = new HashMap<String, Object>(); + metadata.put("wire", wire); + Object input = mediator.mediateInput(msg.getBody(), sourceOperation, targetOperation, metadata); + msg.setBody(input); + Message resultMsg = next.invoke(msg); + if (sourceOperation.isNonBlocking()) { + // Not to reset the message body + return resultMsg; + } + + Object result = resultMsg.getBody(); + + if (resultMsg.isFault()) { + Object transformedFault = null; + if ((result instanceof Exception) && !(result instanceof RuntimeException)) { + transformedFault = mediator.mediateFault(result, sourceOperation, targetOperation, metadata); + if (transformedFault != result) { + resultMsg.setFaultBody(transformedFault); + } + } + // + // Leave it to another layer to actually throw the Exception which constitutes + // the message body. We don't throw it here. + // + } else { + assert !(result instanceof Throwable) : "Expected messages that are not throwable " + result; + Object newResult = mediator.mediateOutput(result, sourceOperation, targetOperation, metadata); + resultMsg.setBody(newResult); + } + + return resultMsg; + } + + public void setNext(Invoker next) { + this.next = next; + } + + public boolean allowsPassByReference() { + return true; + } + +} diff --git a/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/wire/PassByValueInterceptor.java b/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/wire/PassByValueInterceptor.java new file mode 100644 index 0000000000..44e5072e61 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-databinding/src/main/java/org/apache/tuscany/sca/core/databinding/wire/PassByValueInterceptor.java @@ -0,0 +1,80 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core.databinding.wire; + +import org.apache.tuscany.sca.databinding.Mediator; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.Interceptor; +import org.apache.tuscany.sca.invocation.InvocationChain; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.Message; + +/** + * Implementation of an interceptor that enforces pass-by-value semantics + * on operation invocations by copying the operation input and output data. + * + * @version $Rev$ $Date$ + */ +public class PassByValueInterceptor implements Interceptor { + + private Mediator mediator; + private Operation operation; + private Invoker nextInvoker; + private InvocationChain chain; + + /** + * Constructs a new PassByValueInterceptor. + * @param dataBindings databinding extension point + * @param operation the intercepted operation + */ + public PassByValueInterceptor(Mediator mediator, InvocationChain chain, Operation operation) { + this.mediator = mediator; + this.chain = chain; + this.operation = operation; + } + + public Message invoke(Message msg) { + if (chain.allowsPassByReference()) { + return nextInvoker.invoke(msg); + } + + msg.setBody(mediator.copyInput(msg.getBody(), operation)); + + Message resultMsg = nextInvoker.invoke(msg); + + if (!resultMsg.isFault() && operation.getOutputType() != null) { + resultMsg.setBody(mediator.copyOutput(resultMsg.getBody(), operation)); + } + + if (resultMsg.isFault()) { + resultMsg.setFaultBody(mediator.copyFault(resultMsg.getBody(), operation)); + } + return resultMsg; + } + + public Invoker getNext() { + return nextInvoker; + } + + public void setNext(Invoker next) { + this.nextInvoker = next; + } + +} diff --git a/branches/sca-java-1.5.1/modules/core-databinding/src/main/resources/META-INF/services/org.apache.tuscany.sca.core.ModuleActivator b/branches/sca-java-1.5.1/modules/core-databinding/src/main/resources/META-INF/services/org.apache.tuscany.sca.core.ModuleActivator new file mode 100644 index 0000000000..baba638c9b --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-databinding/src/main/resources/META-INF/services/org.apache.tuscany.sca.core.ModuleActivator @@ -0,0 +1,18 @@ +# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+# Implementation class for the ExtensionActivator
+org.apache.tuscany.sca.core.databinding.module.DataBindingModuleActivator
diff --git a/branches/sca-java-1.5.1/modules/core-databinding/src/test/java/org/apache/tuscany/sca/core/databinding/processor/DataBindingJavaInterfaceProcessorTestCase.java b/branches/sca-java-1.5.1/modules/core-databinding/src/test/java/org/apache/tuscany/sca/core/databinding/processor/DataBindingJavaInterfaceProcessorTestCase.java new file mode 100644 index 0000000000..b0c39e18ef --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-databinding/src/test/java/org/apache/tuscany/sca/core/databinding/processor/DataBindingJavaInterfaceProcessorTestCase.java @@ -0,0 +1,89 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core.databinding.processor; + +import junit.framework.TestCase; + +import org.apache.tuscany.sca.databinding.DataBindingExtensionPoint; +import org.apache.tuscany.sca.databinding.DefaultDataBindingExtensionPoint; +import org.apache.tuscany.sca.databinding.annotation.DataBinding; +import org.apache.tuscany.sca.interfacedef.InvalidInterfaceException; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.interfacedef.impl.OperationImpl; +import org.apache.tuscany.sca.interfacedef.java.DefaultJavaInterfaceFactory; +import org.apache.tuscany.sca.interfacedef.java.JavaInterface; +import org.apache.tuscany.sca.interfacedef.java.JavaInterfaceContract; +import org.apache.tuscany.sca.interfacedef.java.JavaInterfaceFactory; +import org.osoa.sca.annotations.Remotable; +import org.w3c.dom.Node; + +/** + * + * @version $Rev$ $Date$ + */ +public class DataBindingJavaInterfaceProcessorTestCase extends TestCase { + + /** + * @see junit.framework.TestCase#setUp() + */ + @Override + protected void setUp() throws Exception { + } + + /** + * @throws InvalidServiceContractException + */ + public final void testVisitInterface() throws InvalidInterfaceException { + DataBindingExtensionPoint registry = new DefaultDataBindingExtensionPoint(); + DataBindingJavaInterfaceProcessor processor = new DataBindingJavaInterfaceProcessor(registry); + JavaInterfaceFactory javaFactory = new DefaultJavaInterfaceFactory(); + + JavaInterface contract = javaFactory.createJavaInterface(); + contract.setJavaClass(MockInterface.class); + JavaInterfaceContract interfaceContract = javaFactory.createJavaInterfaceContract(); + interfaceContract.setInterface(contract); + Operation operation = newOperation("call"); + Operation operation1 = newOperation("call1"); + contract.getOperations().add(operation); + contract.getOperations().add(operation1); + contract.setRemotable(true); + processor.visitInterface(contract); + // Assert.assertEquals("org.w3c.dom.Node", contract.getDataBinding()); + // Assert.assertEquals("org.w3c.dom.Node", + // contract.getOperations().get("call").getDataBinding()); + // Assert.assertEquals("xml:string", + // contract.getOperations().get("call1").getDataBinding()); + } + + @DataBinding("org.w3c.dom.Node") + @Remotable + public static interface MockInterface { + Node call(Node msg); + + @DataBinding("xml:string") + String call1(String msg); + } + + private static Operation newOperation(String name) { + Operation operation = new OperationImpl(); + operation.setName(name); + return operation; + } +} diff --git a/branches/sca-java-1.5.1/modules/core-databinding/src/test/java/org/apache/tuscany/sca/core/databinding/transformers/IDLTransformerTestCaseFIXME.java b/branches/sca-java-1.5.1/modules/core-databinding/src/test/java/org/apache/tuscany/sca/core/databinding/transformers/IDLTransformerTestCaseFIXME.java new file mode 100644 index 0000000000..7d49fb7112 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-databinding/src/test/java/org/apache/tuscany/sca/core/databinding/transformers/IDLTransformerTestCaseFIXME.java @@ -0,0 +1,229 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.databinding.transformers; + +//import static org.apache.tuscany.spi.databinding.DataBinding.IDL_INPUT; +//import static org.apache.tuscany.spi.databinding.DataBinding.IDL_OUTPUT; +// +//import java.util.ArrayList; +//import java.util.List; +// +//import javax.xml.namespace.QName; + +import junit.framework.TestCase; + +//import org.apache.tuscany.databinding.impl.DataBindingRegistryImpl; +//import org.apache.tuscany.databinding.impl.MediatorImpl; +//import org.apache.tuscany.databinding.impl.TransformationContextImpl; +//import org.apache.tuscany.databinding.impl.TransformerRegistryImpl; +//import org.apache.tuscany.databinding.javabeans.DOMNode2JavaBeanTransformer; +//import org.apache.tuscany.databinding.javabeans.JavaBean2DOMNodeTransformer; +//import org.apache.tuscany.databinding.xml.DOMDataBinding; +//import org.apache.tuscany.databinding.xml.Node2String; +//import org.apache.tuscany.databinding.xml.String2Node; +//import org.apache.tuscany.interfacedef.DataType; +//import org.apache.tuscany.interfacedef.Operation; +//import org.apache.tuscany.interfacedef.impl.DataTypeImpl; +//import org.apache.tuscany.interfacedef.impl.OperationImpl; +//import org.apache.tuscany.interfacedef.util.ElementInfo; +//import org.apache.tuscany.interfacedef.util.TypeInfo; +//import org.apache.tuscany.interfacedef.util.WrapperInfo; +//import org.apache.tuscany.interfacedef.util.XMLType; +//import org.apache.tuscany.spi.databinding.DataBindingRegistry; +//import org.apache.tuscany.spi.databinding.TransformationContext; +//import org.apache.tuscany.spi.databinding.extension.DOMHelper; +//import org.apache.tuscany.spi.databinding.extension.SimpleTypeMapperExtension; +//import org.w3c.dom.Document; +//import org.w3c.dom.Element; + +public class IDLTransformerTestCaseFIXME extends TestCase { +// private static final String IPO_XML = "<?xml version=\"1.0\"?>" + "<order1" +// + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" +// + " xmlns:ipo=\"http://www.example.com/IPO\"" +// + " xsi:schemaLocation=\"http://www.example.com/IPO ipo.xsd\"" +// + " orderDate=\"1999-12-01\">" +// + " <shipTo exportCode=\"1\" xsi:type=\"ipo:UKAddress\">" +// + " <name>Helen Zoe</name>" +// + " <street>47 Eden Street</street>" +// + " <city>Cambridge</city>" +// + " <postcode>CB1 1JR</postcode>" +// + " </shipTo>" +// + " <billTo xsi:type=\"ipo:USAddress\">" +// + " <name>Robert Smith</name>" +// + " <street>8 Oak Avenue</street>" +// + " <city>Old Town</city>" +// + " <state>PA</state>" +// + " <zip>95819</zip>" +// + " </billTo>" +// + " <items>" +// + " <item partNum=\"833-AA\">" +// + " <productName>Lapis necklace</productName>" +// + " <quantity>1</quantity>" +// + " <USPrice>99.95</USPrice>" +// + " <ipo:comment>Want this for the holidays</ipo:comment>" +// + " <shipDate>1999-12-05</shipDate>" +// + " </item>" +// + " </items>" +// + "</order1>"; +// +// private static final String URI_ORDER_XSD = "http://example.com/order.xsd"; +// +// /** +// * @see junit.framework.TestCase#setUp() +// */ +// protected void setUp() throws Exception { +// super.setUp(); +// } +// +// public void testTransform() throws Exception { +// List<DataType> types0 = new ArrayList<DataType>(); +// DataType<XMLType> wrapperType = new DataTypeImpl<XMLType>(null, Object.class, +// new XMLType(new QName(URI_ORDER_XSD, +// "checkOrderStatus"), null)); +// types0.add(wrapperType); +// DataType<List<DataType>> inputType0 = new DataTypeImpl<List<DataType>>(IDL_INPUT, +// Object[].class, types0); +// +// List<DataType> types1 = new ArrayList<DataType>(); +// DataType<XMLType> customerIdType = new DataTypeImpl<XMLType>( +// null, +// Object.class, +// new XMLType( +// new QName(URI_ORDER_XSD, "customerId"), +// null)); +// DataType<XMLType> orderType = new DataTypeImpl<XMLType>(null, Object.class, +// new XMLType(new QName(URI_ORDER_XSD, "order"), null)); +// DataType<XMLType> flagType = new DataTypeImpl<XMLType>(null, Object.class, new XMLType(new QName(URI_ORDER_XSD, +// "flag"), null)); +// types1.add(customerIdType); +// types1.add(orderType); +// types1.add(flagType); +// +// DataType<XMLType> statusType = new DataTypeImpl<XMLType>(null, Object.class, +// new XMLType(new QName(URI_ORDER_XSD, "status"), null)); +// DataType<XMLType> responseType = new DataTypeImpl<XMLType>(null, Object.class, +// new XMLType(new QName(URI_ORDER_XSD, +// "checkOrderStatusResponse"), +// null)); +// +// Operation op = new OperationImpl("checkOrderStatus"); +// op.setInputType(inputType0); +// op.setOutputType(responseType); +//// op.setDataBinding(DOMDataBinding.NAME); +//// +//// inputType0.setOperation(op); +// op.setWrapperStyle(true); +// ElementInfo inputElement = new ElementInfo(new QName(URI_ORDER_XSD, "checkOrderStatus"), new TypeInfo(null, +// false, +// null)); +//// wrapperType.setMetadata(ElementInfo.class.getName(), inputElement); +// +// ElementInfo customerId = new ElementInfo(new QName("", "customerId"), +// SimpleTypeMapperExtension.XSD_SIMPLE_TYPES.get("string")); +// ElementInfo order = new ElementInfo(new QName("", "order"), new TypeInfo(new QName(URI_ORDER_XSD), false, null)); +// ElementInfo flag = new ElementInfo(new QName("", "flag"), SimpleTypeMapperExtension.XSD_SIMPLE_TYPES.get("int")); +// +//// customerIdType.setMetadata(ElementInfo.class.getName(), customerId); +//// orderType.setMetadata(ElementInfo.class.getName(), order); +//// flagType.setMetadata(ElementInfo.class.getName(), flag); +//// +//// customerIdType.setOperation(op); +//// orderType.setOperation(op); +//// flagType.setOperation(op); +// +// List<ElementInfo> inputElements = new ArrayList<ElementInfo>(); +// inputElements.add(customerId); +// inputElements.add(order); +// inputElements.add(flag); +// +// ElementInfo statusElement = new ElementInfo(new QName("", "status"), SimpleTypeMapperExtension.XSD_SIMPLE_TYPES +// .get("string")); +// +//// statusType.setMetadata(ElementInfo.class.getName(), statusElement); +//// statusType.setOperation(op); +// +// List<ElementInfo> outputElements = new ArrayList<ElementInfo>(); +// outputElements.add(statusElement); +// +// ElementInfo outputElement = new ElementInfo(new QName(URI_ORDER_XSD, "checkOrderStatusResponse"), +// new TypeInfo(null, false, null)); +// +//// responseType.setMetadata(ElementInfo.class.getName(), inputElement); +//// responseType.setOperation(op); +// +// WrapperInfo wrapperInfo = new WrapperInfo(DOMDataBinding.NAME, inputElement, outputElement, inputElements, +// outputElements); +// op.setWrapper(wrapperInfo); +//// op.setDataBinding(DOMDataBinding.NAME); +// +// MediatorImpl m = new MediatorImpl(); +// TransformerRegistryImpl tr = new TransformerRegistryImpl(); +// tr.registerTransformer(new String2Node()); +// tr.registerTransformer(new Node2String()); +// tr.registerTransformer(new DOMNode2JavaBeanTransformer()); +// tr.registerTransformer(new JavaBean2DOMNodeTransformer()); +// m.setTransformerRegistry(tr); +// DataBindingRegistry dataBindingRegistry = new DataBindingRegistryImpl(); +// dataBindingRegistry.register(new DOMDataBinding()); +// m.setDataBindingRegistry(dataBindingRegistry); +// +// Object[] source = new Object[] {"cust001", IPO_XML, Integer.valueOf(1)}; +// Input2InputTransformer t = new Input2InputTransformer(); +// t.setMediator(m); +// +// TransformationContext context = new TransformationContextImpl(); +// context.setSourceOperation(op); +// List<DataType<Class>> types = new ArrayList<DataType<Class>>(); +// types.add(new DataTypeImpl<Class>(Object.class.getName(), String.class, String.class)); +// types.add(new DataTypeImpl<Class>("java.lang.String", String.class, String.class)); +// types.add(new DataTypeImpl<Class>(Object.class.getName(), int.class, int.class)); +// DataType<List<DataType<Class>>> inputType1 = new DataTypeImpl<List<DataType<Class>>>(IDL_INPUT, Object[].class, +// types); +// context.setSourceDataType(inputType1); +// context.setTargetDataType(op.getInputType()); +// Object[] results = t.transform(source, context); +// assertEquals(1, results.length); +// assertTrue(results[0] instanceof Element); +// Element element = (Element)results[0]; +// assertEquals("http://example.com/order.xsd", element.getNamespaceURI()); +// assertEquals("checkOrderStatus", element.getLocalName()); +// +// TransformationContext context1 = new TransformationContextImpl(); +// DataType<DataType> sourceType = new DataTypeImpl<DataType>(IDL_OUTPUT, Object.class, op.getOutputType()); +// +// context1.setSourceDataType(sourceType); +// DataType<DataType> targetType = new DataTypeImpl<DataType>(IDL_OUTPUT, Object.class, +// new DataTypeImpl<Class>("java.lang.Object", +// String.class, String.class)); +// context1.setTargetDataType(targetType); +// +// Document factory = DOMHelper.newDocument(); +// Element responseElement = factory +// .createElementNS("http://example.com/order.wsdl", "p:checkOrderStatusResponse"); +// Element status = factory.createElement("status"); +// responseElement.appendChild(status); +// status.appendChild(factory.createTextNode("shipped")); +// Output2OutputTransformer t2 = new Output2OutputTransformer(); +// t2.setMediator(m); +// Object st = t2.transform(responseElement, context1); +// assertEquals("shipped", st); +// +// } +// +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/LICENSE b/branches/sca-java-1.5.1/modules/core-spi/LICENSE new file mode 100644 index 0000000000..8aa906c321 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/LICENSE @@ -0,0 +1,205 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + diff --git a/branches/sca-java-1.5.1/modules/core-spi/NOTICE b/branches/sca-java-1.5.1/modules/core-spi/NOTICE new file mode 100644 index 0000000000..fdfa0e9faa --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2008 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/branches/sca-java-1.5.1/modules/core-spi/pom.xml b/branches/sca-java-1.5.1/modules/core-spi/pom.xml new file mode 100644 index 0000000000..f2a15cd1c2 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/pom.xml @@ -0,0 +1,122 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. +--> +<project> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>org.apache.tuscany.sca</groupId> + <artifactId>tuscany-modules</artifactId> + <version>1.6-SNAPSHOT</version> + <relativePath>../pom.xml</relativePath> + </parent> + <artifactId>tuscany-core-spi</artifactId> + <name>Apache Tuscany SCA Core SPI</name> + + <dependencies> + <dependency> + <groupId>org.apache.tuscany.sca</groupId> + <artifactId>tuscany-extensibility</artifactId> + <version>1.6-SNAPSHOT</version> + </dependency> + + <dependency> + <groupId>org.apache.tuscany.sca</groupId> + <artifactId>tuscany-sca-api</artifactId> + <version>1.6-SNAPSHOT</version> + </dependency> + + <dependency> + <groupId>org.apache.tuscany.sca</groupId> + <artifactId>tuscany-sca-api-extension</artifactId> + <version>1.6-SNAPSHOT</version> + </dependency> + + <dependency> + <groupId>org.apache.tuscany.sca</groupId> + <artifactId>tuscany-assembly</artifactId> + <version>1.6-SNAPSHOT</version> + </dependency> + + <dependency> + <groupId>org.apache.tuscany.sca</groupId> + <artifactId>tuscany-definitions</artifactId> + <version>1.6-SNAPSHOT</version> + </dependency> + + <dependency> + <groupId>org.apache.tuscany.sca</groupId> + <artifactId>tuscany-policy</artifactId> + <version>1.6-SNAPSHOT</version> + </dependency> + + <dependency> + <groupId>org.apache.tuscany.sca</groupId> + <artifactId>tuscany-interface</artifactId> + <version>1.6-SNAPSHOT</version> + <scope>compile</scope> + </dependency> + + <dependency> + <groupId>org.apache.tuscany.sca</groupId> + <artifactId>tuscany-contribution</artifactId> + <version>1.6-SNAPSHOT</version> + </dependency> + + <dependency> + <groupId>javax.servlet</groupId> + <artifactId>servlet-api</artifactId> + <version>2.5</version> + <scope>provided</scope> + </dependency> + + <dependency> + <groupId>org.codehaus.woodstox</groupId> + <artifactId>wstx-asl</artifactId> + <version>3.2.4</version> + <scope>runtime</scope> + <exclusions> + <exclusion> + <groupId>stax</groupId> + <artifactId>stax-api</artifactId> + </exclusion> + </exclusions> + </dependency> + + </dependencies> + + + <build> + <plugins> + <plugin> + <groupId>org.apache.felix</groupId> + <artifactId>maven-bundle-plugin</artifactId> + + <configuration> + <instructions> + <Bundle-Version>${tuscany.version}</Bundle-Version> + <Bundle-SymbolicName>org.apache.tuscany.sca.core.spi</Bundle-SymbolicName> + <Bundle-Description>${pom.name}</Bundle-Description> + <Export-Package>org.apache.tuscany.sca*</Export-Package> + </instructions> + </configuration> + </plugin> + </plugins> + </build> + +</project> diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/doc/Context Model.emx b/branches/sca-java-1.5.1/modules/core-spi/src/doc/Context Model.emx new file mode 100644 index 0000000000..0445ea5a6b --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/doc/Context Model.emx @@ -0,0 +1,673 @@ +<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+-->
+<!--xtools2_universal_type_manager-->
+<uml:Model xmi:version="2.0" xmlns:xmi="http://www.omg.org/XMI" xmlns:notation="http://www.ibm.com/xtools/1.5.0/Notation" xmlns:uml="http://www.eclipse.org/uml2/1.0.0/UML" xmlns:umlnotation="http://www.ibm.com/xtools/1.5.0/Umlnotation" xmi:id="_al1S8NovEdqRBPR5WyT36A" name="Context Model" appliedProfile="_al1S9NovEdqRBPR5WyT36A _al1S99ovEdqRBPR5WyT36A _al1S-tovEdqRBPR5WyT36A _al1S_dovEdqRBPR5WyT36A _al1TANovEdqRBPR5WyT36A">
+ <eAnnotations xmi:id="_al1S8dovEdqRBPR5WyT36A" source="uml2.diagrams" references="_al1S8tovEdqRBPR5WyT36A">
+ <contents xmi:type="notation:Diagram" xmi:id="_al1S8tovEdqRBPR5WyT36A" type="Class" name="Main">
+ <children xmi:id="_ePDcYdovEdqRBPR5WyT36A" sourceEdges="_Fd3lQdowEdqRBPR5WyT36A _R5Rjwdo1EdqRBPR5WyT36A _pdfmkNo2EdqRBPR5WyT36A" targetEdges="_hmIF4dovEdqRBPR5WyT36A _mu9A4dovEdqRBPR5WyT36A _pe3jwNovEdqRBPR5WyT36A" element="_ePDcYNovEdqRBPR5WyT36A">
+ <children xmi:id="_ePJjANovEdqRBPR5WyT36A" type="ImageCompartment" element="_ePDcYNovEdqRBPR5WyT36A">
+ <layoutConstraint xmi:type="notation:Size" xmi:id="_ePJjAdovEdqRBPR5WyT36A" width="530" height="530"/>
+ </children>
+ <children xmi:id="_ePJjAtovEdqRBPR5WyT36A" type="Stereotype" element="_ePDcYNovEdqRBPR5WyT36A"/>
+ <children xmi:id="_ePJjA9ovEdqRBPR5WyT36A" type="Kind" element="_ePDcYNovEdqRBPR5WyT36A"/>
+ <children xmi:id="_ePJjBNovEdqRBPR5WyT36A" type="Name" element="_ePDcYNovEdqRBPR5WyT36A"/>
+ <children xmi:id="_ePJjBdovEdqRBPR5WyT36A" type="AttributeCompartment" element="_ePDcYNovEdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLListCompartmentStyle" xmi:id="_ePJjBtovEdqRBPR5WyT36A"/>
+ </children>
+ <children xmi:id="_ePJjB9ovEdqRBPR5WyT36A" type="OperationCompartment" element="_ePDcYNovEdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLListCompartmentStyle" xmi:id="_ePJjCNovEdqRBPR5WyT36A"/>
+ </children>
+ <children xmi:id="_ePJjCdovEdqRBPR5WyT36A" visible="false" type="SignalCompartment" element="_ePDcYNovEdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLListCompartmentStyle" xmi:id="_ePJjCtovEdqRBPR5WyT36A"/>
+ </children>
+ <styles xmi:type="umlnotation:UMLClassifierStyle" xmi:id="_ePDcYtovEdqRBPR5WyT36A" showStereotype="Label" useClassifierShape="true"/>
+ <layoutConstraint xmi:type="notation:Bounds" xmi:id="_ePDcY9ovEdqRBPR5WyT36A" x="6693" y="3545"/>
+ </children>
+ <children xmi:id="_fs1pANovEdqRBPR5WyT36A" sourceEdges="_hmIF4dovEdqRBPR5WyT36A _pe3jwNovEdqRBPR5WyT36A" targetEdges="_xInjYdovEdqRBPR5WyT36A" element="_fsviYNovEdqRBPR5WyT36A">
+ <children xmi:id="_fs1pA9ovEdqRBPR5WyT36A" type="ImageCompartment" element="_fsviYNovEdqRBPR5WyT36A">
+ <layoutConstraint xmi:type="notation:Size" xmi:id="_fs1pBNovEdqRBPR5WyT36A" width="530" height="530"/>
+ </children>
+ <children xmi:id="_fs1pBdovEdqRBPR5WyT36A" type="Stereotype" element="_fsviYNovEdqRBPR5WyT36A"/>
+ <children xmi:id="_fs1pBtovEdqRBPR5WyT36A" type="Kind" element="_fsviYNovEdqRBPR5WyT36A"/>
+ <children xmi:id="_fs1pB9ovEdqRBPR5WyT36A" type="Name" element="_fsviYNovEdqRBPR5WyT36A"/>
+ <children xmi:id="_fs1pCNovEdqRBPR5WyT36A" type="AttributeCompartment" element="_fsviYNovEdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLListCompartmentStyle" xmi:id="_fs1pCdovEdqRBPR5WyT36A"/>
+ </children>
+ <children xmi:id="_fs1pCtovEdqRBPR5WyT36A" type="OperationCompartment" element="_fsviYNovEdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLListCompartmentStyle" xmi:id="_fs1pC9ovEdqRBPR5WyT36A"/>
+ </children>
+ <children xmi:id="_fs1pDNovEdqRBPR5WyT36A" visible="false" type="SignalCompartment" element="_fsviYNovEdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLListCompartmentStyle" xmi:id="_fs1pDdovEdqRBPR5WyT36A"/>
+ </children>
+ <styles xmi:type="umlnotation:UMLClassifierStyle" xmi:id="_fs1pAdovEdqRBPR5WyT36A" showStereotype="Label" useClassifierShape="true"/>
+ <layoutConstraint xmi:type="notation:Bounds" xmi:id="_fs1pAtovEdqRBPR5WyT36A" x="2226" y="8268"/>
+ </children>
+ <children xmi:id="_ikr_4NovEdqRBPR5WyT36A" sourceEdges="_mu9A4dovEdqRBPR5WyT36A" element="_ikl5QNovEdqRBPR5WyT36A">
+ <children xmi:id="_ikr_49ovEdqRBPR5WyT36A" type="ImageCompartment" element="_ikl5QNovEdqRBPR5WyT36A">
+ <layoutConstraint xmi:type="notation:Size" xmi:id="_ikr_5NovEdqRBPR5WyT36A" width="530" height="530"/>
+ </children>
+ <children xmi:id="_ikr_5dovEdqRBPR5WyT36A" type="Stereotype" element="_ikl5QNovEdqRBPR5WyT36A"/>
+ <children xmi:id="_ikr_5tovEdqRBPR5WyT36A" type="Kind" element="_ikl5QNovEdqRBPR5WyT36A"/>
+ <children xmi:id="_ikr_59ovEdqRBPR5WyT36A" type="Name" element="_ikl5QNovEdqRBPR5WyT36A"/>
+ <children xmi:id="_ikr_6NovEdqRBPR5WyT36A" type="AttributeCompartment" element="_ikl5QNovEdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLListCompartmentStyle" xmi:id="_ikr_6dovEdqRBPR5WyT36A"/>
+ </children>
+ <children xmi:id="_ikr_6tovEdqRBPR5WyT36A" type="OperationCompartment" element="_ikl5QNovEdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLListCompartmentStyle" xmi:id="_ikr_69ovEdqRBPR5WyT36A"/>
+ </children>
+ <children xmi:id="_ikr_7NovEdqRBPR5WyT36A" visible="false" type="SignalCompartment" element="_ikl5QNovEdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLListCompartmentStyle" xmi:id="_ikr_7dovEdqRBPR5WyT36A"/>
+ </children>
+ <styles xmi:type="umlnotation:UMLClassifierStyle" xmi:id="_ikr_4dovEdqRBPR5WyT36A" showStereotype="Label" useClassifierShape="true"/>
+ <layoutConstraint xmi:type="notation:Bounds" xmi:id="_ikr_4tovEdqRBPR5WyT36A" x="9222" y="8268"/>
+ </children>
+ <children xmi:id="_tZF9odovEdqRBPR5WyT36A" sourceEdges="_xInjYdovEdqRBPR5WyT36A _BkUg0dowEdqRBPR5WyT36A" element="_tZF9oNovEdqRBPR5WyT36A">
+ <children xmi:id="_tZF9pNovEdqRBPR5WyT36A" type="ImageCompartment" element="_tZF9oNovEdqRBPR5WyT36A">
+ <layoutConstraint xmi:type="notation:Size" xmi:id="_tZF9pdovEdqRBPR5WyT36A" width="530" height="530"/>
+ </children>
+ <children xmi:id="_tZF9ptovEdqRBPR5WyT36A" type="Stereotype" element="_tZF9oNovEdqRBPR5WyT36A"/>
+ <children xmi:id="_tZF9p9ovEdqRBPR5WyT36A" type="Kind" element="_tZF9oNovEdqRBPR5WyT36A"/>
+ <children xmi:id="_tZF9qNovEdqRBPR5WyT36A" type="Name" element="_tZF9oNovEdqRBPR5WyT36A"/>
+ <children xmi:id="_tZF9qdovEdqRBPR5WyT36A" type="AttributeCompartment" element="_tZF9oNovEdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLListCompartmentStyle" xmi:id="_tZF9qtovEdqRBPR5WyT36A"/>
+ </children>
+ <children xmi:id="_tZF9q9ovEdqRBPR5WyT36A" type="OperationCompartment" element="_tZF9oNovEdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLListCompartmentStyle" xmi:id="_tZF9rNovEdqRBPR5WyT36A"/>
+ </children>
+ <children xmi:id="_tZF9rdovEdqRBPR5WyT36A" visible="false" type="SignalCompartment" element="_tZF9oNovEdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLListCompartmentStyle" xmi:id="_tZF9rtovEdqRBPR5WyT36A"/>
+ </children>
+ <styles xmi:type="umlnotation:UMLClassifierStyle" xmi:id="_tZF9otovEdqRBPR5WyT36A" showStereotype="Label" useClassifierShape="true"/>
+ <layoutConstraint xmi:type="notation:Bounds" xmi:id="_tZF9o9ovEdqRBPR5WyT36A" x="2226" y="12084"/>
+ </children>
+ <children xmi:id="_z_m-oNovEdqRBPR5WyT36A" sourceEdges="_cN4xsdo2EdqRBPR5WyT36A" targetEdges="_3Ic-4NovEdqRBPR5WyT36A _9XeF4tovEdqRBPR5WyT36A _Fd3lQdowEdqRBPR5WyT36A" element="_z_g4ANovEdqRBPR5WyT36A">
+ <children xmi:id="_z_m-o9ovEdqRBPR5WyT36A" type="ImageCompartment" element="_z_g4ANovEdqRBPR5WyT36A">
+ <layoutConstraint xmi:type="notation:Size" xmi:id="_z_m-pNovEdqRBPR5WyT36A" width="530" height="530"/>
+ </children>
+ <children xmi:id="_z_m-pdovEdqRBPR5WyT36A" type="Stereotype" element="_z_g4ANovEdqRBPR5WyT36A"/>
+ <children xmi:id="_z_m-ptovEdqRBPR5WyT36A" type="Kind" element="_z_g4ANovEdqRBPR5WyT36A"/>
+ <children xmi:id="_z_m-p9ovEdqRBPR5WyT36A" type="Name" element="_z_g4ANovEdqRBPR5WyT36A"/>
+ <children xmi:id="_z_m-qNovEdqRBPR5WyT36A" type="AttributeCompartment" element="_z_g4ANovEdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLListCompartmentStyle" xmi:id="_z_m-qdovEdqRBPR5WyT36A"/>
+ </children>
+ <children xmi:id="_z_m-qtovEdqRBPR5WyT36A" type="OperationCompartment" element="_z_g4ANovEdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLListCompartmentStyle" xmi:id="_z_m-q9ovEdqRBPR5WyT36A"/>
+ </children>
+ <children xmi:id="_z_m-rNovEdqRBPR5WyT36A" visible="false" type="SignalCompartment" element="_z_g4ANovEdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLListCompartmentStyle" xmi:id="_z_m-rdovEdqRBPR5WyT36A"/>
+ </children>
+ <styles xmi:type="umlnotation:UMLClassifierStyle" xmi:id="_z_m-odovEdqRBPR5WyT36A" showStereotype="Label" useClassifierShape="true"/>
+ <layoutConstraint xmi:type="notation:Bounds" xmi:id="_z_m-otovEdqRBPR5WyT36A" x="17172" y="6996"/>
+ </children>
+ <children xmi:id="_1y-ZsNovEdqRBPR5WyT36A" sourceEdges="_3Ic-4NovEdqRBPR5WyT36A _9-BEUNo2EdqRBPR5WyT36A" targetEdges="_BkUg0dowEdqRBPR5WyT36A" element="_1yyMcNovEdqRBPR5WyT36A">
+ <children xmi:id="_1y-Zs9ovEdqRBPR5WyT36A" type="ImageCompartment" element="_1yyMcNovEdqRBPR5WyT36A">
+ <layoutConstraint xmi:type="notation:Size" xmi:id="_1y-ZtNovEdqRBPR5WyT36A" width="1320" height="1320"/>
+ </children>
+ <children xmi:id="_1y-ZtdovEdqRBPR5WyT36A" type="Stereotype" element="_1yyMcNovEdqRBPR5WyT36A"/>
+ <children xmi:id="_1y-ZttovEdqRBPR5WyT36A" type="Name" element="_1yyMcNovEdqRBPR5WyT36A"/>
+ <children xmi:id="_1y-Zt9ovEdqRBPR5WyT36A" type="AttributeCompartment" element="_1yyMcNovEdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLListCompartmentStyle" xmi:id="_1y-ZuNovEdqRBPR5WyT36A"/>
+ </children>
+ <children xmi:id="_1y-ZudovEdqRBPR5WyT36A" type="OperationCompartment" element="_1yyMcNovEdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLListCompartmentStyle" xmi:id="_1y-ZutovEdqRBPR5WyT36A"/>
+ </children>
+ <children xmi:id="_1y-Zu9ovEdqRBPR5WyT36A" visible="false" type="SignalCompartment" element="_1yyMcNovEdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLListCompartmentStyle" xmi:id="_1y-ZvNovEdqRBPR5WyT36A"/>
+ </children>
+ <children xmi:id="_1y-ZvdovEdqRBPR5WyT36A" visible="false" type="StructureCompartment" element="_1yyMcNovEdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLShapeCompartmentStyle" xmi:id="_1y-ZvtovEdqRBPR5WyT36A"/>
+ </children>
+ <styles xmi:type="umlnotation:UMLShapeStyle" xmi:id="_1y-ZsdovEdqRBPR5WyT36A" showStereotype="Label"/>
+ <layoutConstraint xmi:type="notation:Bounds" xmi:id="_1y-ZstovEdqRBPR5WyT36A" x="13992" y="12084"/>
+ </children>
+ <children xmi:id="_4WSrANovEdqRBPR5WyT36A" sourceEdges="_9XeF4tovEdqRBPR5WyT36A _9PaR4No2EdqRBPR5WyT36A" element="_4WMkYNovEdqRBPR5WyT36A">
+ <children xmi:id="_4WSrA9ovEdqRBPR5WyT36A" type="ImageCompartment" element="_4WMkYNovEdqRBPR5WyT36A">
+ <layoutConstraint xmi:type="notation:Size" xmi:id="_4WSrBNovEdqRBPR5WyT36A" width="1320" height="1320"/>
+ </children>
+ <children xmi:id="_4WSrBdovEdqRBPR5WyT36A" type="Stereotype" element="_4WMkYNovEdqRBPR5WyT36A"/>
+ <children xmi:id="_4WSrBtovEdqRBPR5WyT36A" type="Name" element="_4WMkYNovEdqRBPR5WyT36A"/>
+ <children xmi:id="_4WSrB9ovEdqRBPR5WyT36A" type="AttributeCompartment" element="_4WMkYNovEdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLListCompartmentStyle" xmi:id="_4WSrCNovEdqRBPR5WyT36A"/>
+ </children>
+ <children xmi:id="_4WSrCdovEdqRBPR5WyT36A" type="OperationCompartment" element="_4WMkYNovEdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLListCompartmentStyle" xmi:id="_4WSrCtovEdqRBPR5WyT36A"/>
+ </children>
+ <children xmi:id="_4WSrC9ovEdqRBPR5WyT36A" visible="false" type="SignalCompartment" element="_4WMkYNovEdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLListCompartmentStyle" xmi:id="_4WSrDNovEdqRBPR5WyT36A"/>
+ </children>
+ <children xmi:id="_4WSrDdovEdqRBPR5WyT36A" visible="false" type="StructureCompartment" element="_4WMkYNovEdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLShapeCompartmentStyle" xmi:id="_4WSrDtovEdqRBPR5WyT36A"/>
+ </children>
+ <styles xmi:type="umlnotation:UMLShapeStyle" xmi:id="_4WSrAdovEdqRBPR5WyT36A" showStereotype="Label"/>
+ <layoutConstraint xmi:type="notation:Bounds" xmi:id="_4WSrAtovEdqRBPR5WyT36A" x="19716" y="12084"/>
+ </children>
+ <children xmi:id="_o2m3oNo0EdqRBPR5WyT36A" targetEdges="_9PaR4No2EdqRBPR5WyT36A _9-BEUNo2EdqRBPR5WyT36A" element="_o2gxANo0EdqRBPR5WyT36A">
+ <children xmi:id="_o2m3o9o0EdqRBPR5WyT36A" type="ImageCompartment" element="_o2gxANo0EdqRBPR5WyT36A">
+ <layoutConstraint xmi:type="notation:Size" xmi:id="_o2m3pNo0EdqRBPR5WyT36A" width="530" height="530"/>
+ </children>
+ <children xmi:id="_o2m3pdo0EdqRBPR5WyT36A" type="Stereotype" element="_o2gxANo0EdqRBPR5WyT36A"/>
+ <children xmi:id="_o2m3pto0EdqRBPR5WyT36A" type="Kind" element="_o2gxANo0EdqRBPR5WyT36A"/>
+ <children xmi:id="_o2m3p9o0EdqRBPR5WyT36A" type="Name" element="_o2gxANo0EdqRBPR5WyT36A"/>
+ <children xmi:id="_o2m3qNo0EdqRBPR5WyT36A" type="AttributeCompartment" element="_o2gxANo0EdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLListCompartmentStyle" xmi:id="_o2m3qdo0EdqRBPR5WyT36A"/>
+ </children>
+ <children xmi:id="_o2m3qto0EdqRBPR5WyT36A" type="OperationCompartment" element="_o2gxANo0EdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLListCompartmentStyle" xmi:id="_o2m3q9o0EdqRBPR5WyT36A"/>
+ </children>
+ <children xmi:id="_o2m3rNo0EdqRBPR5WyT36A" visible="false" type="SignalCompartment" element="_o2gxANo0EdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLListCompartmentStyle" xmi:id="_o2m3rdo0EdqRBPR5WyT36A"/>
+ </children>
+ <styles xmi:type="umlnotation:UMLClassifierStyle" xmi:id="_o2m3odo0EdqRBPR5WyT36A" showStereotype="Label" useClassifierShape="true"/>
+ <layoutConstraint xmi:type="notation:Bounds" xmi:id="_o2m3oto0EdqRBPR5WyT36A" x="23532" y="6996"/>
+ </children>
+ <children xmi:id="_M0FLkNo1EdqRBPR5WyT36A" targetEdges="_R5Rjwdo1EdqRBPR5WyT36A _V7zlEdo1EdqRBPR5WyT36A" element="_Mz_E8No1EdqRBPR5WyT36A">
+ <children xmi:id="_M0FLk9o1EdqRBPR5WyT36A" type="ImageCompartment" element="_Mz_E8No1EdqRBPR5WyT36A">
+ <layoutConstraint xmi:type="notation:Size" xmi:id="_M0FLlNo1EdqRBPR5WyT36A" width="530" height="530"/>
+ </children>
+ <children xmi:id="_M0FLldo1EdqRBPR5WyT36A" type="Stereotype" element="_Mz_E8No1EdqRBPR5WyT36A"/>
+ <children xmi:id="_M0FLlto1EdqRBPR5WyT36A" type="Kind" element="_Mz_E8No1EdqRBPR5WyT36A"/>
+ <children xmi:id="_M0FLl9o1EdqRBPR5WyT36A" type="Name" element="_Mz_E8No1EdqRBPR5WyT36A"/>
+ <children xmi:id="_M0FLmNo1EdqRBPR5WyT36A" type="AttributeCompartment" element="_Mz_E8No1EdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLListCompartmentStyle" xmi:id="_M0FLmdo1EdqRBPR5WyT36A"/>
+ </children>
+ <children xmi:id="_M0FLmto1EdqRBPR5WyT36A" type="OperationCompartment" element="_Mz_E8No1EdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLListCompartmentStyle" xmi:id="_M0FLm9o1EdqRBPR5WyT36A"/>
+ </children>
+ <children xmi:id="_M0FLnNo1EdqRBPR5WyT36A" visible="false" type="SignalCompartment" element="_Mz_E8No1EdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLListCompartmentStyle" xmi:id="_M0FLndo1EdqRBPR5WyT36A"/>
+ </children>
+ <styles xmi:type="umlnotation:UMLClassifierStyle" xmi:id="_M0FLkdo1EdqRBPR5WyT36A" showStereotype="Label" useClassifierShape="true"/>
+ <layoutConstraint xmi:type="notation:Bounds" xmi:id="_M0FLkto1EdqRBPR5WyT36A" x="6678" y="318"/>
+ </children>
+ <children xmi:id="_TJHbANo1EdqRBPR5WyT36A" sourceEdges="_V7zlEdo1EdqRBPR5WyT36A" targetEdges="_cN4xsdo2EdqRBPR5WyT36A" element="_TI7NwNo1EdqRBPR5WyT36A">
+ <children xmi:id="_TJHbA9o1EdqRBPR5WyT36A" type="ImageCompartment" element="_TI7NwNo1EdqRBPR5WyT36A">
+ <layoutConstraint xmi:type="notation:Size" xmi:id="_TJHbBNo1EdqRBPR5WyT36A" width="530" height="530"/>
+ </children>
+ <children xmi:id="_TJHbBdo1EdqRBPR5WyT36A" type="Stereotype" element="_TI7NwNo1EdqRBPR5WyT36A"/>
+ <children xmi:id="_TJHbBto1EdqRBPR5WyT36A" type="Kind" element="_TI7NwNo1EdqRBPR5WyT36A"/>
+ <children xmi:id="_TJHbB9o1EdqRBPR5WyT36A" type="Name" element="_TI7NwNo1EdqRBPR5WyT36A"/>
+ <children xmi:id="_TJHbCNo1EdqRBPR5WyT36A" type="AttributeCompartment" element="_TI7NwNo1EdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLListCompartmentStyle" xmi:id="_TJHbCdo1EdqRBPR5WyT36A"/>
+ </children>
+ <children xmi:id="_TJHbCto1EdqRBPR5WyT36A" type="OperationCompartment" element="_TI7NwNo1EdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLListCompartmentStyle" xmi:id="_TJHbC9o1EdqRBPR5WyT36A"/>
+ </children>
+ <children xmi:id="_TJHbDNo1EdqRBPR5WyT36A" visible="false" type="SignalCompartment" element="_TI7NwNo1EdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLListCompartmentStyle" xmi:id="_TJHbDdo1EdqRBPR5WyT36A"/>
+ </children>
+ <styles xmi:type="umlnotation:UMLClassifierStyle" xmi:id="_TJHbAdo1EdqRBPR5WyT36A" showStereotype="Label" useClassifierShape="true"/>
+ <layoutConstraint xmi:type="notation:Bounds" xmi:id="_TJHbAto1EdqRBPR5WyT36A" x="16854" y="318"/>
+ </children>
+ <styles xmi:type="umlnotation:UMLDiagramStyle" xmi:id="_al1S89ovEdqRBPR5WyT36A"/>
+ <edges xmi:id="_hmIF4dovEdqRBPR5WyT36A" element="_hmIF4NovEdqRBPR5WyT36A" source="_fs1pANovEdqRBPR5WyT36A" target="_ePDcYdovEdqRBPR5WyT36A">
+ <children xmi:id="_hmIF5NovEdqRBPR5WyT36A" type="NameLabel" element="_hmIF4NovEdqRBPR5WyT36A">
+ <children xmi:id="_hmIF5tovEdqRBPR5WyT36A" type="Stereotype" element="_hmIF4NovEdqRBPR5WyT36A"/>
+ <children xmi:id="_hmIF59ovEdqRBPR5WyT36A" type="Name" element="_hmIF4NovEdqRBPR5WyT36A"/>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_hmIF5dovEdqRBPR5WyT36A" y="-185"/>
+ </children>
+ <styles xmi:type="umlnotation:UMLConnectorStyle" xmi:id="_hmIF4tovEdqRBPR5WyT36A" routing="Tree" showStereotype="Text"/>
+ <bendpoints xmi:type="notation:RelativeBendpoints" xmi:id="_hmIF49ovEdqRBPR5WyT36A" points="[26, -31, -110, 148]$[140, -148, 4, 31]"/>
+ </edges>
+ <edges xmi:id="_mu9A4dovEdqRBPR5WyT36A" element="_mu9A4NovEdqRBPR5WyT36A" source="_ikr_4NovEdqRBPR5WyT36A" target="_ePDcYdovEdqRBPR5WyT36A">
+ <children xmi:id="_mu9A5NovEdqRBPR5WyT36A" type="NameLabel" element="_mu9A4NovEdqRBPR5WyT36A">
+ <children xmi:id="_mu9A5tovEdqRBPR5WyT36A" type="Stereotype" element="_mu9A4NovEdqRBPR5WyT36A"/>
+ <children xmi:id="_mu9A59ovEdqRBPR5WyT36A" type="Name" element="_mu9A4NovEdqRBPR5WyT36A"/>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_mu9A5dovEdqRBPR5WyT36A" y="-185"/>
+ </children>
+ <styles xmi:type="umlnotation:UMLConnectorStyle" xmi:id="_mu9A4tovEdqRBPR5WyT36A" routing="Tree" showStereotype="Text"/>
+ <bendpoints xmi:type="notation:RelativeBendpoints" xmi:id="_mu9A49ovEdqRBPR5WyT36A" points="[-185, -820, 2937, 3916]$[-185, -3042, 2937, 1694]$[-3255, -3042, -133, 1694]$[-3255, -3916, -133, 820]"/>
+ </edges>
+ <edges xmi:id="_pe3jwNovEdqRBPR5WyT36A" element="_peM1YNovEdqRBPR5WyT36A" source="_fs1pANovEdqRBPR5WyT36A" target="_ePDcYdovEdqRBPR5WyT36A">
+ <children xmi:id="_pe3jw9ovEdqRBPR5WyT36A" type="NameLabel" element="_peM1YNovEdqRBPR5WyT36A">
+ <children xmi:id="_pe3jxdovEdqRBPR5WyT36A" type="Stereotype" element="_peM1YNovEdqRBPR5WyT36A"/>
+ <children xmi:id="_pe3jxtovEdqRBPR5WyT36A" type="Name" element="_peM1YNovEdqRBPR5WyT36A"/>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_pe3jxNovEdqRBPR5WyT36A" y="-185"/>
+ </children>
+ <children xmi:id="_pe3jx9ovEdqRBPR5WyT36A" type="ToMultiplicityLabel" element="_peM1YtovEdqRBPR5WyT36A">
+ <children xmi:id="_pe3jydovEdqRBPR5WyT36A" type="ToMultiplicity" element="_peM1YtovEdqRBPR5WyT36A"/>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_pe3jyNovEdqRBPR5WyT36A" y="397"/>
+ </children>
+ <children xmi:id="_pe3jytovEdqRBPR5WyT36A" type="ToRoleLabel" element="_peM1YtovEdqRBPR5WyT36A">
+ <children xmi:id="_pe3jzNovEdqRBPR5WyT36A" type="ToRole" element="_peM1YtovEdqRBPR5WyT36A"/>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_pe3jy9ovEdqRBPR5WyT36A" y="-397"/>
+ </children>
+ <children xmi:id="_pe3jzdovEdqRBPR5WyT36A" type="FromMultiplicityLabel" element="_peM1YdovEdqRBPR5WyT36A">
+ <children xmi:id="_pe3jz9ovEdqRBPR5WyT36A" type="FromMultiplicity" element="_peM1YdovEdqRBPR5WyT36A"/>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_pe3jztovEdqRBPR5WyT36A" y="397"/>
+ </children>
+ <children xmi:id="_pe3j0NovEdqRBPR5WyT36A" type="FromRoleLabel" element="_peM1YdovEdqRBPR5WyT36A">
+ <children xmi:id="_pe3j0tovEdqRBPR5WyT36A" type="FromRole" element="_peM1YdovEdqRBPR5WyT36A"/>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_pe3j0dovEdqRBPR5WyT36A" y="-397"/>
+ </children>
+ <children xmi:id="_pe3j09ovEdqRBPR5WyT36A" type="ToQualifierLabel" element="_peM1YtovEdqRBPR5WyT36A">
+ <children xmi:id="_pe3j1dovEdqRBPR5WyT36A" type="QualifierCompartment" element="_peM1YtovEdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLListCompartmentStyle" xmi:id="_pe3j1tovEdqRBPR5WyT36A"/>
+ </children>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_pe3j1NovEdqRBPR5WyT36A" y="-185"/>
+ </children>
+ <children xmi:id="_pe3j19ovEdqRBPR5WyT36A" type="FromQualifierLabel" element="_peM1YdovEdqRBPR5WyT36A">
+ <children xmi:id="_pe3j2dovEdqRBPR5WyT36A" type="QualifierCompartment" element="_peM1YdovEdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLListCompartmentStyle" xmi:id="_pe3j2tovEdqRBPR5WyT36A"/>
+ </children>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_pe3j2NovEdqRBPR5WyT36A" y="-185"/>
+ </children>
+ <styles xmi:type="umlnotation:UMLConnectorStyle" xmi:id="_pe3jwdovEdqRBPR5WyT36A" showStereotype="Text"/>
+ <bendpoints xmi:type="notation:RelativeBendpoints" xmi:id="_pe3jwtovEdqRBPR5WyT36A" points="[-317, -820, -3916, 3916]$[-1931, -4762, -5530, -26]$[2382, -4762, -1217, -26]"/>
+ </edges>
+ <edges xmi:id="_xInjYdovEdqRBPR5WyT36A" element="_xInjYNovEdqRBPR5WyT36A" source="_tZF9odovEdqRBPR5WyT36A" target="_fs1pANovEdqRBPR5WyT36A">
+ <children xmi:id="_xInjZNovEdqRBPR5WyT36A" type="NameLabel" element="_xInjYNovEdqRBPR5WyT36A">
+ <children xmi:id="_xInjZtovEdqRBPR5WyT36A" type="Stereotype" element="_xInjYNovEdqRBPR5WyT36A"/>
+ <children xmi:id="_xInjZ9ovEdqRBPR5WyT36A" type="Name" element="_xInjYNovEdqRBPR5WyT36A"/>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_xInjZdovEdqRBPR5WyT36A" y="-185"/>
+ </children>
+ <styles xmi:type="umlnotation:UMLConnectorStyle" xmi:id="_xInjYtovEdqRBPR5WyT36A" showStereotype="Text"/>
+ <bendpoints xmi:type="notation:RelativeBendpoints" xmi:id="_xInjY9ovEdqRBPR5WyT36A" points="[-4, -31, 1, 113]$[-4, -115, 1, 29]"/>
+ </edges>
+ <edges xmi:id="_3Ic-4NovEdqRBPR5WyT36A" element="_3IW4QNovEdqRBPR5WyT36A" source="_1y-ZsNovEdqRBPR5WyT36A" target="_z_m-oNovEdqRBPR5WyT36A">
+ <children xmi:id="_3Ic-49ovEdqRBPR5WyT36A" type="NameLabel" element="_3IW4QNovEdqRBPR5WyT36A">
+ <children xmi:id="_3Ic-5dovEdqRBPR5WyT36A" type="Stereotype" element="_3IW4QNovEdqRBPR5WyT36A"/>
+ <children xmi:id="_3Ic-5tovEdqRBPR5WyT36A" type="Name" element="_3IW4QNovEdqRBPR5WyT36A"/>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_3Ic-5NovEdqRBPR5WyT36A" y="-185"/>
+ </children>
+ <styles xmi:type="umlnotation:UMLConnectorStyle" xmi:id="_3Ic-4dovEdqRBPR5WyT36A" showStereotype="Text"/>
+ <bendpoints xmi:type="notation:RelativeBendpoints" xmi:id="_3Ic-4tovEdqRBPR5WyT36A" points="[6, -24, -37, 154]$[-22, -170, -65, 8]"/>
+ </edges>
+ <edges xmi:id="_9XeF4tovEdqRBPR5WyT36A" element="_9XeF4NovEdqRBPR5WyT36A" source="_4WSrANovEdqRBPR5WyT36A" target="_z_m-oNovEdqRBPR5WyT36A">
+ <children xmi:id="_9XeF5dovEdqRBPR5WyT36A" type="NameLabel" element="_9XeF4NovEdqRBPR5WyT36A">
+ <children xmi:id="_9XeF59ovEdqRBPR5WyT36A" type="Stereotype" element="_9XeF4NovEdqRBPR5WyT36A"/>
+ <children xmi:id="_9XeF6NovEdqRBPR5WyT36A" type="Name" element="_9XeF4NovEdqRBPR5WyT36A"/>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_9XeF5tovEdqRBPR5WyT36A" y="-185"/>
+ </children>
+ <styles xmi:type="umlnotation:UMLConnectorStyle" xmi:id="_9XeF49ovEdqRBPR5WyT36A" showStereotype="Text"/>
+ <bendpoints xmi:type="notation:RelativeBendpoints" xmi:id="_9XeF5NovEdqRBPR5WyT36A" points="[-23, -23, 162, 151]$[-121, -170, 64, 4]"/>
+ </edges>
+ <edges xmi:id="_BkUg0dowEdqRBPR5WyT36A" element="_Bj8GUNowEdqRBPR5WyT36A" source="_tZF9odovEdqRBPR5WyT36A" target="_1y-ZsNovEdqRBPR5WyT36A">
+ <children xmi:id="_BkancNowEdqRBPR5WyT36A" type="NameLabel" element="_Bj8GUNowEdqRBPR5WyT36A">
+ <children xmi:id="_BkanctowEdqRBPR5WyT36A" type="Stereotype" element="_Bj8GUNowEdqRBPR5WyT36A"/>
+ <children xmi:id="_Bkanc9owEdqRBPR5WyT36A" type="Name" element="_Bj8GUNowEdqRBPR5WyT36A"/>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_BkancdowEdqRBPR5WyT36A" y="-185"/>
+ </children>
+ <children xmi:id="_BkandNowEdqRBPR5WyT36A" type="ToMultiplicityLabel" element="_Bj8GUtowEdqRBPR5WyT36A">
+ <children xmi:id="_BkandtowEdqRBPR5WyT36A" type="ToMultiplicity" element="_Bj8GUtowEdqRBPR5WyT36A"/>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_BkanddowEdqRBPR5WyT36A" y="397"/>
+ </children>
+ <children xmi:id="_Bkand9owEdqRBPR5WyT36A" type="ToRoleLabel" element="_Bj8GUtowEdqRBPR5WyT36A">
+ <children xmi:id="_BkanedowEdqRBPR5WyT36A" type="ToRole" element="_Bj8GUtowEdqRBPR5WyT36A"/>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_BkaneNowEdqRBPR5WyT36A" y="-397"/>
+ </children>
+ <children xmi:id="_BkanetowEdqRBPR5WyT36A" type="FromMultiplicityLabel" element="_Bj8GUdowEdqRBPR5WyT36A">
+ <children xmi:id="_BkanfNowEdqRBPR5WyT36A" type="FromMultiplicity" element="_Bj8GUdowEdqRBPR5WyT36A"/>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_Bkane9owEdqRBPR5WyT36A" y="397"/>
+ </children>
+ <children xmi:id="_BkanfdowEdqRBPR5WyT36A" type="FromRoleLabel" element="_Bj8GUdowEdqRBPR5WyT36A">
+ <children xmi:id="_Bkanf9owEdqRBPR5WyT36A" type="FromRole" element="_Bj8GUdowEdqRBPR5WyT36A"/>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_BkanftowEdqRBPR5WyT36A" y="-397"/>
+ </children>
+ <children xmi:id="_BkangNowEdqRBPR5WyT36A" type="ToQualifierLabel" element="_Bj8GUtowEdqRBPR5WyT36A">
+ <children xmi:id="_BkangtowEdqRBPR5WyT36A" type="QualifierCompartment" element="_Bj8GUtowEdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLListCompartmentStyle" xmi:id="_Bkang9owEdqRBPR5WyT36A"/>
+ </children>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_BkangdowEdqRBPR5WyT36A" y="-185"/>
+ </children>
+ <children xmi:id="_BkanhNowEdqRBPR5WyT36A" type="FromQualifierLabel" element="_Bj8GUdowEdqRBPR5WyT36A">
+ <children xmi:id="_BkanhtowEdqRBPR5WyT36A" type="QualifierCompartment" element="_Bj8GUdowEdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLListCompartmentStyle" xmi:id="_Bkanh9owEdqRBPR5WyT36A"/>
+ </children>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_BkanhdowEdqRBPR5WyT36A" y="-185"/>
+ </children>
+ <styles xmi:type="umlnotation:UMLConnectorStyle" xmi:id="_BkUg0towEdqRBPR5WyT36A" showStereotype="Text"/>
+ <bendpoints xmi:type="notation:RelativeBendpoints" xmi:id="_BkUg09owEdqRBPR5WyT36A" points="[83, -24, -490, 123]$[486, -151, -87, -4]"/>
+ </edges>
+ <edges xmi:id="_Fd3lQdowEdqRBPR5WyT36A" element="_FdlRYNowEdqRBPR5WyT36A" source="_ePDcYdovEdqRBPR5WyT36A" target="_z_m-oNovEdqRBPR5WyT36A">
+ <children xmi:id="_Fd3lRNowEdqRBPR5WyT36A" type="NameLabel" element="_FdlRYNowEdqRBPR5WyT36A">
+ <children xmi:id="_Fd3lRtowEdqRBPR5WyT36A" type="Stereotype" element="_FdlRYNowEdqRBPR5WyT36A"/>
+ <children xmi:id="_Fd3lR9owEdqRBPR5WyT36A" type="Name" element="_FdlRYNowEdqRBPR5WyT36A"/>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_Fd3lRdowEdqRBPR5WyT36A" y="-185"/>
+ </children>
+ <children xmi:id="_Fd3lSNowEdqRBPR5WyT36A" type="ToMultiplicityLabel" element="_FdlRYtowEdqRBPR5WyT36A">
+ <children xmi:id="_Fd3lStowEdqRBPR5WyT36A" type="ToMultiplicity" element="_FdlRYtowEdqRBPR5WyT36A"/>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_Fd3lSdowEdqRBPR5WyT36A" y="397"/>
+ </children>
+ <children xmi:id="_Fd3lS9owEdqRBPR5WyT36A" type="ToRoleLabel" element="_FdlRYtowEdqRBPR5WyT36A">
+ <children xmi:id="_Fd3lTdowEdqRBPR5WyT36A" type="ToRole" element="_FdlRYtowEdqRBPR5WyT36A"/>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_Fd3lTNowEdqRBPR5WyT36A" y="-397"/>
+ </children>
+ <children xmi:id="_Fd3lTtowEdqRBPR5WyT36A" type="FromMultiplicityLabel" element="_FdlRYdowEdqRBPR5WyT36A">
+ <children xmi:id="_Fd3lUNowEdqRBPR5WyT36A" type="FromMultiplicity" element="_FdlRYdowEdqRBPR5WyT36A"/>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_Fd3lT9owEdqRBPR5WyT36A" y="397"/>
+ </children>
+ <children xmi:id="_Fd3lUdowEdqRBPR5WyT36A" type="FromRoleLabel" element="_FdlRYdowEdqRBPR5WyT36A">
+ <children xmi:id="_Fd3lU9owEdqRBPR5WyT36A" type="FromRole" element="_FdlRYdowEdqRBPR5WyT36A"/>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_Fd3lUtowEdqRBPR5WyT36A" y="-397"/>
+ </children>
+ <children xmi:id="_Fd3lVNowEdqRBPR5WyT36A" type="ToQualifierLabel" element="_FdlRYtowEdqRBPR5WyT36A">
+ <children xmi:id="_Fd3lVtowEdqRBPR5WyT36A" type="QualifierCompartment" element="_FdlRYtowEdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLListCompartmentStyle" xmi:id="_Fd3lV9owEdqRBPR5WyT36A"/>
+ </children>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_Fd3lVdowEdqRBPR5WyT36A" y="-185"/>
+ </children>
+ <children xmi:id="_Fd3lWNowEdqRBPR5WyT36A" type="FromQualifierLabel" element="_FdlRYdowEdqRBPR5WyT36A">
+ <children xmi:id="_Fd3lWtowEdqRBPR5WyT36A" type="QualifierCompartment" element="_FdlRYdowEdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLListCompartmentStyle" xmi:id="_Fd3lW9owEdqRBPR5WyT36A"/>
+ </children>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_Fd3lWdowEdqRBPR5WyT36A" y="-185"/>
+ </children>
+ <styles xmi:type="umlnotation:UMLConnectorStyle" xmi:id="_Fd3lQtowEdqRBPR5WyT36A" showStereotype="Text"/>
+ <bendpoints xmi:type="notation:RelativeBendpoints" xmi:id="_Fd3lQ9owEdqRBPR5WyT36A" points="[46, -11, -369, -9]$[351, -11, -64, -9]"/>
+ </edges>
+ <edges xmi:id="_R5Rjwdo1EdqRBPR5WyT36A" element="_R5RjwNo1EdqRBPR5WyT36A" source="_ePDcYdovEdqRBPR5WyT36A" target="_M0FLkNo1EdqRBPR5WyT36A">
+ <children xmi:id="_R5RjxNo1EdqRBPR5WyT36A" type="NameLabel" element="_R5RjwNo1EdqRBPR5WyT36A">
+ <children xmi:id="_R5Rjxto1EdqRBPR5WyT36A" type="Stereotype" element="_R5RjwNo1EdqRBPR5WyT36A"/>
+ <children xmi:id="_R5Rjx9o1EdqRBPR5WyT36A" type="Name" element="_R5RjwNo1EdqRBPR5WyT36A"/>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_R5Rjxdo1EdqRBPR5WyT36A" y="-185"/>
+ </children>
+ <styles xmi:type="umlnotation:UMLConnectorStyle" xmi:id="_R5Rjwto1EdqRBPR5WyT36A" showStereotype="Text"/>
+ <bendpoints xmi:type="notation:RelativeBendpoints" xmi:id="_R5Rjw9o1EdqRBPR5WyT36A" points="[-2, -31, -2, 91]$[-2, -91, -2, 31]"/>
+ </edges>
+ <edges xmi:id="_V7zlEdo1EdqRBPR5WyT36A" element="_V7zlENo1EdqRBPR5WyT36A" source="_TJHbANo1EdqRBPR5WyT36A" target="_M0FLkNo1EdqRBPR5WyT36A">
+ <children xmi:id="_V7zlFNo1EdqRBPR5WyT36A" type="NameLabel" element="_V7zlENo1EdqRBPR5WyT36A">
+ <children xmi:id="_V7zlFto1EdqRBPR5WyT36A" type="Stereotype" element="_V7zlENo1EdqRBPR5WyT36A"/>
+ <children xmi:id="_V7zlF9o1EdqRBPR5WyT36A" type="Name" element="_V7zlENo1EdqRBPR5WyT36A"/>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_V7zlFdo1EdqRBPR5WyT36A" y="-185"/>
+ </children>
+ <styles xmi:type="umlnotation:UMLConnectorStyle" xmi:id="_V7zlEto1EdqRBPR5WyT36A" showStereotype="Text"/>
+ <bendpoints xmi:type="notation:RelativeBendpoints" xmi:id="_V7zlE9o1EdqRBPR5WyT36A" points="[-73, 0, 339, 0]$[-457, 0, -45, 0]"/>
+ </edges>
+ <edges xmi:id="_cN4xsdo2EdqRBPR5WyT36A" targetEdges="_pdfmkNo2EdqRBPR5WyT36A" element="_cNskcNo2EdqRBPR5WyT36A" source="_z_m-oNovEdqRBPR5WyT36A" target="_TJHbANo1EdqRBPR5WyT36A">
+ <children xmi:id="_cN4xtNo2EdqRBPR5WyT36A" type="NameLabel" element="_cNskcNo2EdqRBPR5WyT36A">
+ <children xmi:id="_cN4xtto2EdqRBPR5WyT36A" type="Stereotype" element="_cNskcNo2EdqRBPR5WyT36A"/>
+ <children xmi:id="_cN4xt9o2EdqRBPR5WyT36A" type="Name" element="_cNskcNo2EdqRBPR5WyT36A"/>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_cN4xtdo2EdqRBPR5WyT36A" y="-185"/>
+ </children>
+ <children xmi:id="_cN4xuNo2EdqRBPR5WyT36A" type="ToMultiplicityLabel" element="_cNskcto2EdqRBPR5WyT36A">
+ <children xmi:id="_cN4xuto2EdqRBPR5WyT36A" type="ToMultiplicity" element="_cNskcto2EdqRBPR5WyT36A"/>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_cN4xudo2EdqRBPR5WyT36A" y="397"/>
+ </children>
+ <children xmi:id="_cN4xu9o2EdqRBPR5WyT36A" type="ToRoleLabel" element="_cNskcto2EdqRBPR5WyT36A">
+ <children xmi:id="_cN4xvdo2EdqRBPR5WyT36A" type="ToRole" element="_cNskcto2EdqRBPR5WyT36A"/>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_cN4xvNo2EdqRBPR5WyT36A" y="-397"/>
+ </children>
+ <children xmi:id="_cN_fYNo2EdqRBPR5WyT36A" type="FromMultiplicityLabel" element="_cNskcdo2EdqRBPR5WyT36A">
+ <children xmi:id="_cN_fYto2EdqRBPR5WyT36A" type="FromMultiplicity" element="_cNskcdo2EdqRBPR5WyT36A"/>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_cN_fYdo2EdqRBPR5WyT36A" y="397"/>
+ </children>
+ <children xmi:id="_cN_fY9o2EdqRBPR5WyT36A" type="FromRoleLabel" element="_cNskcdo2EdqRBPR5WyT36A">
+ <children xmi:id="_cN_fZdo2EdqRBPR5WyT36A" type="FromRole" element="_cNskcdo2EdqRBPR5WyT36A"/>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_cN_fZNo2EdqRBPR5WyT36A" y="-397"/>
+ </children>
+ <children xmi:id="_cN_fZto2EdqRBPR5WyT36A" type="ToQualifierLabel" element="_cNskcto2EdqRBPR5WyT36A">
+ <children xmi:id="_cN_faNo2EdqRBPR5WyT36A" type="QualifierCompartment" element="_cNskcto2EdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLListCompartmentStyle" xmi:id="_cN_fado2EdqRBPR5WyT36A"/>
+ </children>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_cN_fZ9o2EdqRBPR5WyT36A" y="-185"/>
+ </children>
+ <children xmi:id="_cN_fato2EdqRBPR5WyT36A" type="FromQualifierLabel" element="_cNskcdo2EdqRBPR5WyT36A">
+ <children xmi:id="_cN_fbNo2EdqRBPR5WyT36A" type="QualifierCompartment" element="_cNskcdo2EdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLListCompartmentStyle" xmi:id="_cN_fbdo2EdqRBPR5WyT36A"/>
+ </children>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_cN_fa9o2EdqRBPR5WyT36A" y="-185"/>
+ </children>
+ <styles xmi:type="umlnotation:UMLConnectorStyle" xmi:id="_cN4xsto2EdqRBPR5WyT36A" showStereotype="Text"/>
+ <bendpoints xmi:type="notation:RelativeBendpoints" xmi:id="_cN4xs9o2EdqRBPR5WyT36A" points="[-2, -29, 1, 91]$[26, -89, 29, 31]"/>
+ </edges>
+ <edges xmi:id="_pdfmkNo2EdqRBPR5WyT36A" element="_pdHMENo2EdqRBPR5WyT36A" source="_ePDcYdovEdqRBPR5WyT36A" target="_cN4xsdo2EdqRBPR5WyT36A">
+ <children xmi:id="_pdfml9o2EdqRBPR5WyT36A" type="ToMultiplicityLabel" element="_pdTZUdo2EdqRBPR5WyT36A">
+ <children xmi:id="_pdfmmdo2EdqRBPR5WyT36A" type="ToMultiplicity" element="_pdTZUdo2EdqRBPR5WyT36A"/>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_pdfmmNo2EdqRBPR5WyT36A" y="397"/>
+ </children>
+ <children xmi:id="_pdfmmto2EdqRBPR5WyT36A" type="ToRoleLabel" element="_pdTZUdo2EdqRBPR5WyT36A">
+ <children xmi:id="_pdfmnNo2EdqRBPR5WyT36A" type="ToRole" element="_pdTZUdo2EdqRBPR5WyT36A"/>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_pdfmm9o2EdqRBPR5WyT36A" y="-397"/>
+ </children>
+ <children xmi:id="_pdfmndo2EdqRBPR5WyT36A" type="FromMultiplicityLabel" element="_pdTZUNo2EdqRBPR5WyT36A">
+ <children xmi:id="_pdfmn9o2EdqRBPR5WyT36A" type="FromMultiplicity" element="_pdTZUNo2EdqRBPR5WyT36A"/>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_pdfmnto2EdqRBPR5WyT36A" y="397"/>
+ </children>
+ <children xmi:id="_pdfmoNo2EdqRBPR5WyT36A" type="FromRoleLabel" element="_pdTZUNo2EdqRBPR5WyT36A">
+ <children xmi:id="_pdfmoto2EdqRBPR5WyT36A" type="FromRole" element="_pdTZUNo2EdqRBPR5WyT36A"/>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_pdfmodo2EdqRBPR5WyT36A" y="-397"/>
+ </children>
+ <children xmi:id="_pdfmo9o2EdqRBPR5WyT36A" type="ToQualifierLabel" element="_pdTZUdo2EdqRBPR5WyT36A">
+ <children xmi:id="_pdfmpdo2EdqRBPR5WyT36A" type="QualifierCompartment" element="_pdTZUdo2EdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLListCompartmentStyle" xmi:id="_pdfmpto2EdqRBPR5WyT36A"/>
+ </children>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_pdfmpNo2EdqRBPR5WyT36A" y="-185"/>
+ </children>
+ <children xmi:id="_pdfmp9o2EdqRBPR5WyT36A" type="FromQualifierLabel" element="_pdTZUNo2EdqRBPR5WyT36A">
+ <children xmi:id="_pdfmqdo2EdqRBPR5WyT36A" type="QualifierCompartment" element="_pdTZUNo2EdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLListCompartmentStyle" xmi:id="_pdfmqto2EdqRBPR5WyT36A"/>
+ </children>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_pdfmqNo2EdqRBPR5WyT36A" y="-185"/>
+ </children>
+ <children xmi:id="_pdfmq9o2EdqRBPR5WyT36A" element="_pdHMENo2EdqRBPR5WyT36A">
+ <children xmi:id="_pdfmrto2EdqRBPR5WyT36A" type="ImageCompartment" element="_pdHMENo2EdqRBPR5WyT36A">
+ <layoutConstraint xmi:type="notation:Size" xmi:id="_pdfmr9o2EdqRBPR5WyT36A" width="1320" height="1320"/>
+ </children>
+ <children xmi:id="_pdfmsNo2EdqRBPR5WyT36A" type="Stereotype" element="_pdHMENo2EdqRBPR5WyT36A"/>
+ <children xmi:id="_pdfmsdo2EdqRBPR5WyT36A" type="Name" element="_pdHMENo2EdqRBPR5WyT36A"/>
+ <children xmi:id="_pdfmsto2EdqRBPR5WyT36A" type="AttributeCompartment" element="_pdHMENo2EdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLListCompartmentStyle" xmi:id="_pdfms9o2EdqRBPR5WyT36A"/>
+ </children>
+ <children xmi:id="_pdfmtNo2EdqRBPR5WyT36A" type="OperationCompartment" element="_pdHMENo2EdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLListCompartmentStyle" xmi:id="_pdfmtdo2EdqRBPR5WyT36A"/>
+ </children>
+ <children xmi:id="_pdfmtto2EdqRBPR5WyT36A" visible="false" type="SignalCompartment" element="_pdHMENo2EdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLListCompartmentStyle" xmi:id="_pdfmt9o2EdqRBPR5WyT36A"/>
+ </children>
+ <children xmi:id="_pdfmuNo2EdqRBPR5WyT36A" visible="false" type="StructureCompartment" element="_pdHMENo2EdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLShapeCompartmentStyle" xmi:id="_pdfmudo2EdqRBPR5WyT36A"/>
+ </children>
+ <styles xmi:type="umlnotation:UMLShapeStyle" xmi:id="_pdfmrNo2EdqRBPR5WyT36A" showStereotype="Label"/>
+ <layoutConstraint xmi:type="notation:Bounds" xmi:id="_pdfmrdo2EdqRBPR5WyT36A" y="1323"/>
+ </children>
+ <styles xmi:type="umlnotation:UMLConnectorStyle" xmi:id="_pdfmkdo2EdqRBPR5WyT36A" showStereotype="Text"/>
+ <bendpoints xmi:type="notation:RelativeBendpoints" xmi:id="_pdfmkto2EdqRBPR5WyT36A" points="[46, 3, -366, 94]$[412, -91, 0, 0]"/>
+ <targetAnchor xmi:type="notation:IdentityAnchor" xmi:id="_pdrz0No2EdqRBPR5WyT36A" id="100"/>
+ </edges>
+ <edges xmi:id="_9PaR4No2EdqRBPR5WyT36A" element="_9PH-ANo2EdqRBPR5WyT36A" source="_4WSrANovEdqRBPR5WyT36A" target="_o2m3oNo0EdqRBPR5WyT36A">
+ <children xmi:id="_9PaR49o2EdqRBPR5WyT36A" type="NameLabel" element="_9PH-ANo2EdqRBPR5WyT36A">
+ <children xmi:id="_9PaR5do2EdqRBPR5WyT36A" type="Stereotype" element="_9PH-ANo2EdqRBPR5WyT36A"/>
+ <children xmi:id="_9PaR5to2EdqRBPR5WyT36A" type="Name" element="_9PH-ANo2EdqRBPR5WyT36A"/>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_9PaR5No2EdqRBPR5WyT36A" y="-185"/>
+ </children>
+ <children xmi:id="_9PaR59o2EdqRBPR5WyT36A" type="ToMultiplicityLabel" element="_9PH-Ato2EdqRBPR5WyT36A">
+ <children xmi:id="_9PaR6do2EdqRBPR5WyT36A" type="ToMultiplicity" element="_9PH-Ato2EdqRBPR5WyT36A"/>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_9PaR6No2EdqRBPR5WyT36A" y="397"/>
+ </children>
+ <children xmi:id="_9PaR6to2EdqRBPR5WyT36A" type="ToRoleLabel" element="_9PH-Ato2EdqRBPR5WyT36A">
+ <children xmi:id="_9PaR7No2EdqRBPR5WyT36A" type="ToRole" element="_9PH-Ato2EdqRBPR5WyT36A"/>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_9PaR69o2EdqRBPR5WyT36A" y="-397"/>
+ </children>
+ <children xmi:id="_9PaR7do2EdqRBPR5WyT36A" type="FromMultiplicityLabel" element="_9PH-Ado2EdqRBPR5WyT36A">
+ <children xmi:id="_9PaR79o2EdqRBPR5WyT36A" type="FromMultiplicity" element="_9PH-Ado2EdqRBPR5WyT36A"/>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_9PaR7to2EdqRBPR5WyT36A" y="397"/>
+ </children>
+ <children xmi:id="_9PaR8No2EdqRBPR5WyT36A" type="FromRoleLabel" element="_9PH-Ado2EdqRBPR5WyT36A">
+ <children xmi:id="_9PaR8to2EdqRBPR5WyT36A" type="FromRole" element="_9PH-Ado2EdqRBPR5WyT36A"/>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_9PaR8do2EdqRBPR5WyT36A" y="-397"/>
+ </children>
+ <children xmi:id="_9PgYgNo2EdqRBPR5WyT36A" type="ToQualifierLabel" element="_9PH-Ato2EdqRBPR5WyT36A">
+ <children xmi:id="_9PgYgto2EdqRBPR5WyT36A" type="QualifierCompartment" element="_9PH-Ato2EdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLListCompartmentStyle" xmi:id="_9PgYg9o2EdqRBPR5WyT36A"/>
+ </children>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_9PgYgdo2EdqRBPR5WyT36A" y="-185"/>
+ </children>
+ <children xmi:id="_9PgYhNo2EdqRBPR5WyT36A" type="FromQualifierLabel" element="_9PH-Ado2EdqRBPR5WyT36A">
+ <children xmi:id="_9PgYhto2EdqRBPR5WyT36A" type="QualifierCompartment" element="_9PH-Ado2EdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLListCompartmentStyle" xmi:id="_9PgYh9o2EdqRBPR5WyT36A"/>
+ </children>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_9PgYhdo2EdqRBPR5WyT36A" y="-185"/>
+ </children>
+ <styles xmi:type="umlnotation:UMLConnectorStyle" xmi:id="_9PaR4do2EdqRBPR5WyT36A" showStereotype="Text"/>
+ <bendpoints xmi:type="notation:RelativeBendpoints" xmi:id="_9PaR4to2EdqRBPR5WyT36A" points="[12, -24, -94, 162]$[80, -155, -26, 31]"/>
+ </edges>
+ <edges xmi:id="_9-BEUNo2EdqRBPR5WyT36A" element="_99uwcNo2EdqRBPR5WyT36A" source="_1y-ZsNovEdqRBPR5WyT36A" target="_o2m3oNo0EdqRBPR5WyT36A">
+ <children xmi:id="_9-BEU9o2EdqRBPR5WyT36A" type="NameLabel" element="_99uwcNo2EdqRBPR5WyT36A">
+ <children xmi:id="_9-HK8No2EdqRBPR5WyT36A" type="Stereotype" element="_99uwcNo2EdqRBPR5WyT36A"/>
+ <children xmi:id="_9-HK8do2EdqRBPR5WyT36A" type="Name" element="_99uwcNo2EdqRBPR5WyT36A"/>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_9-BEVNo2EdqRBPR5WyT36A" y="-185"/>
+ </children>
+ <children xmi:id="_9-HK8to2EdqRBPR5WyT36A" type="ToMultiplicityLabel" element="_99uwcto2EdqRBPR5WyT36A">
+ <children xmi:id="_9-HK9No2EdqRBPR5WyT36A" type="ToMultiplicity" element="_99uwcto2EdqRBPR5WyT36A"/>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_9-HK89o2EdqRBPR5WyT36A" y="397"/>
+ </children>
+ <children xmi:id="_9-HK9do2EdqRBPR5WyT36A" type="ToRoleLabel" element="_99uwcto2EdqRBPR5WyT36A">
+ <children xmi:id="_9-HK99o2EdqRBPR5WyT36A" type="ToRole" element="_99uwcto2EdqRBPR5WyT36A"/>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_9-HK9to2EdqRBPR5WyT36A" y="-397"/>
+ </children>
+ <children xmi:id="_9-HK-No2EdqRBPR5WyT36A" type="FromMultiplicityLabel" element="_99uwcdo2EdqRBPR5WyT36A">
+ <children xmi:id="_9-HK-to2EdqRBPR5WyT36A" type="FromMultiplicity" element="_99uwcdo2EdqRBPR5WyT36A"/>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_9-HK-do2EdqRBPR5WyT36A" y="397"/>
+ </children>
+ <children xmi:id="_9-HK-9o2EdqRBPR5WyT36A" type="FromRoleLabel" element="_99uwcdo2EdqRBPR5WyT36A">
+ <children xmi:id="_9-HK_do2EdqRBPR5WyT36A" type="FromRole" element="_99uwcdo2EdqRBPR5WyT36A"/>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_9-HK_No2EdqRBPR5WyT36A" y="-397"/>
+ </children>
+ <children xmi:id="_9-HK_to2EdqRBPR5WyT36A" type="ToQualifierLabel" element="_99uwcto2EdqRBPR5WyT36A">
+ <children xmi:id="_9-HLANo2EdqRBPR5WyT36A" type="QualifierCompartment" element="_99uwcto2EdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLListCompartmentStyle" xmi:id="_9-HLAdo2EdqRBPR5WyT36A"/>
+ </children>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_9-HK_9o2EdqRBPR5WyT36A" y="-185"/>
+ </children>
+ <children xmi:id="_9-HLAto2EdqRBPR5WyT36A" type="FromQualifierLabel" element="_99uwcdo2EdqRBPR5WyT36A">
+ <children xmi:id="_9-HLBNo2EdqRBPR5WyT36A" type="QualifierCompartment" element="_99uwcdo2EdqRBPR5WyT36A">
+ <styles xmi:type="umlnotation:UMLListCompartmentStyle" xmi:id="_9-HLBdo2EdqRBPR5WyT36A"/>
+ </children>
+ <layoutConstraint xmi:type="notation:Location" xmi:id="_9-HLA9o2EdqRBPR5WyT36A" y="-185"/>
+ </children>
+ <styles xmi:type="umlnotation:UMLConnectorStyle" xmi:id="_9-BEUdo2EdqRBPR5WyT36A" showStereotype="Text"/>
+ <bendpoints xmi:type="notation:RelativeBendpoints" xmi:id="_9-BEUto2EdqRBPR5WyT36A" points="[49, -24, -290, 162]$[404, -163, 65, 23]"/>
+ </edges>
+ </contents>
+ </eAnnotations>
+ <packageImport xmi:type="uml:ProfileApplication" xmi:id="_al1S9NovEdqRBPR5WyT36A">
+ <eAnnotations xmi:id="_al1S9dovEdqRBPR5WyT36A" source="attributes">
+ <details xmi:id="_al1S9tovEdqRBPR5WyT36A" key="version" value="0"/>
+ </eAnnotations>
+ <importedPackage xmi:type="uml:Profile" href="pathmap://UML2_PROFILES/Basic.profile.uml2#_6mFRgK86Edih9-GG5afQ0g"/>
+ <importedProfile href="pathmap://UML2_PROFILES/Basic.profile.uml2#_6mFRgK86Edih9-GG5afQ0g"/>
+ </packageImport>
+ <packageImport xmi:type="uml:ProfileApplication" xmi:id="_al1S99ovEdqRBPR5WyT36A">
+ <eAnnotations xmi:id="_al1S-NovEdqRBPR5WyT36A" source="attributes">
+ <details xmi:id="_al1S-dovEdqRBPR5WyT36A" key="version" value="0"/>
+ </eAnnotations>
+ <importedPackage xmi:type="uml:Profile" href="pathmap://UML2_PROFILES/Intermediate.profile.uml2#_Cz7csK87Edih9-GG5afQ0g"/>
+ <importedProfile href="pathmap://UML2_PROFILES/Intermediate.profile.uml2#_Cz7csK87Edih9-GG5afQ0g"/>
+ </packageImport>
+ <packageImport xmi:type="uml:ProfileApplication" xmi:id="_al1S-tovEdqRBPR5WyT36A">
+ <eAnnotations xmi:id="_al1S-9ovEdqRBPR5WyT36A" source="attributes">
+ <details xmi:id="_al1S_NovEdqRBPR5WyT36A" key="version" value="0"/>
+ </eAnnotations>
+ <importedPackage xmi:type="uml:Profile" href="pathmap://UML2_PROFILES/Complete.profile.uml2#_M7pTkK87Edih9-GG5afQ0g"/>
+ <importedProfile href="pathmap://UML2_PROFILES/Complete.profile.uml2#_M7pTkK87Edih9-GG5afQ0g"/>
+ </packageImport>
+ <packageImport xmi:type="uml:ProfileApplication" xmi:id="_al1S_dovEdqRBPR5WyT36A">
+ <eAnnotations xmi:id="_al1S_tovEdqRBPR5WyT36A" source="attributes">
+ <details xmi:id="_al1S_9ovEdqRBPR5WyT36A" key="version" value="0"/>
+ </eAnnotations>
+ <importedPackage xmi:type="uml:Profile" href="pathmap://UML2_MSL_PROFILES/Default.epx#_a_S3wNWLEdiy4IqP8whjFA?Default"/>
+ <importedProfile href="pathmap://UML2_MSL_PROFILES/Default.epx#_a_S3wNWLEdiy4IqP8whjFA?Default"/>
+ </packageImport>
+ <packageImport xmi:type="uml:ProfileApplication" xmi:id="_al1TANovEdqRBPR5WyT36A">
+ <eAnnotations xmi:id="_al1TAdovEdqRBPR5WyT36A" source="attributes">
+ <details xmi:id="_al1TAtovEdqRBPR5WyT36A" key="version" value="0"/>
+ </eAnnotations>
+ <importedPackage xmi:type="uml:Profile" href="pathmap://UML2_MSL_PROFILES/Deployment.epx#_vjbuwOvHEdiDX5bji0iVSA?Deployment"/>
+ <importedProfile href="pathmap://UML2_MSL_PROFILES/Deployment.epx#_vjbuwOvHEdiDX5bji0iVSA?Deployment"/>
+ </packageImport>
+ <packageImport xmi:id="_al1TA9ovEdqRBPR5WyT36A">
+ <importedPackage xmi:type="uml:Model" href="pathmap://UML2_LIBRARIES/UML2PrimitiveTypes.library.uml2#_EfRZoK86EdieaYgxtVWN8Q"/>
+ </packageImport>
+ <ownedMember xmi:type="uml:Interface" xmi:id="_ePDcYNovEdqRBPR5WyT36A" name="Context">
+ <generalization xmi:id="_R5RjwNo1EdqRBPR5WyT36A" general="_Mz_E8No1EdqRBPR5WyT36A"/>
+ <ownedAttribute xmi:id="_FdlRYdowEdqRBPR5WyT36A" name="scopecontext" visibility="private" type="_z_g4ANovEdqRBPR5WyT36A" association="_FdlRYNowEdqRBPR5WyT36A">
+ <upperValue xmi:type="uml:LiteralUnlimitedNatural" xmi:id="_FdlRZNowEdqRBPR5WyT36A" value="1"/>
+ <lowerValue xmi:type="uml:LiteralInteger" xmi:id="_FdlRY9owEdqRBPR5WyT36A"/>
+ </ownedAttribute>
+ </ownedMember>
+ <ownedMember xmi:type="uml:Interface" xmi:id="_fsviYNovEdqRBPR5WyT36A" name="CompositeContext">
+ <generalization xmi:id="_hmIF4NovEdqRBPR5WyT36A" general="_ePDcYNovEdqRBPR5WyT36A"/>
+ <ownedAttribute xmi:id="_peM1YdovEdqRBPR5WyT36A" name="context" visibility="private" type="_ePDcYNovEdqRBPR5WyT36A" association="_peM1YNovEdqRBPR5WyT36A" aggregation="composite">
+ <upperValue xmi:type="uml:LiteralUnlimitedNatural" xmi:id="_peM1ZNovEdqRBPR5WyT36A" value="-1"/>
+ <lowerValue xmi:type="uml:LiteralInteger" xmi:id="_peM1Y9ovEdqRBPR5WyT36A"/>
+ </ownedAttribute>
+ </ownedMember>
+ <ownedMember xmi:type="uml:Interface" xmi:id="_ikl5QNovEdqRBPR5WyT36A" name="AtomicContext">
+ <generalization xmi:id="_mu9A4NovEdqRBPR5WyT36A" general="_ePDcYNovEdqRBPR5WyT36A"/>
+ </ownedMember>
+ <ownedMember xmi:type="uml:Association" xmi:id="_peM1YNovEdqRBPR5WyT36A" memberEnd="_peM1YdovEdqRBPR5WyT36A _peM1YtovEdqRBPR5WyT36A">
+ <ownedEnd xmi:id="_peM1YtovEdqRBPR5WyT36A" visibility="private" type="_fsviYNovEdqRBPR5WyT36A" association="_peM1YNovEdqRBPR5WyT36A"/>
+ </ownedMember>
+ <ownedMember xmi:type="uml:Interface" xmi:id="_tZF9oNovEdqRBPR5WyT36A" name="DeploymentContext">
+ <generalization xmi:id="_xInjYNovEdqRBPR5WyT36A" general="_fsviYNovEdqRBPR5WyT36A"/>
+ <ownedAttribute xmi:id="_Bj8GUdowEdqRBPR5WyT36A" name="modulescopecontext" visibility="private" type="_1yyMcNovEdqRBPR5WyT36A" association="_Bj8GUNowEdqRBPR5WyT36A">
+ <upperValue xmi:type="uml:LiteralUnlimitedNatural" xmi:id="_Bj8GVNowEdqRBPR5WyT36A" value="1"/>
+ <lowerValue xmi:type="uml:LiteralInteger" xmi:id="_Bj8GU9owEdqRBPR5WyT36A"/>
+ </ownedAttribute>
+ </ownedMember>
+ <ownedMember xmi:type="uml:Interface" xmi:id="_z_g4ANovEdqRBPR5WyT36A" name="ScopeContext">
+ <ownedAttribute xmi:id="_cNskcdo2EdqRBPR5WyT36A" name="instancewrapper" visibility="private" type="_TI7NwNo1EdqRBPR5WyT36A" association="_cNskcNo2EdqRBPR5WyT36A">
+ <upperValue xmi:type="uml:LiteralUnlimitedNatural" xmi:id="_cNskdNo2EdqRBPR5WyT36A" value="1"/>
+ <lowerValue xmi:type="uml:LiteralInteger" xmi:id="_cNskc9o2EdqRBPR5WyT36A"/>
+ </ownedAttribute>
+ </ownedMember>
+ <ownedMember xmi:type="uml:Class" xmi:id="_1yyMcNovEdqRBPR5WyT36A" name="ModuleScopeContext" clientDependency="_3IW4QNovEdqRBPR5WyT36A">
+ <implementation xmi:id="_3IW4QNovEdqRBPR5WyT36A" client="_1yyMcNovEdqRBPR5WyT36A" supplier="_z_g4ANovEdqRBPR5WyT36A" realizingClassifier="_z_g4ANovEdqRBPR5WyT36A" contract="_z_g4ANovEdqRBPR5WyT36A">
+ <mapping xmi:id="_3IW4QdovEdqRBPR5WyT36A"/>
+ </implementation>
+ <ownedAttribute xmi:id="_99uwcdo2EdqRBPR5WyT36A" name="scoperegistry" visibility="private" type="_o2gxANo0EdqRBPR5WyT36A" association="_99uwcNo2EdqRBPR5WyT36A">
+ <upperValue xmi:type="uml:LiteralUnlimitedNatural" xmi:id="_99uwdNo2EdqRBPR5WyT36A" value="1"/>
+ <lowerValue xmi:type="uml:LiteralInteger" xmi:id="_99uwc9o2EdqRBPR5WyT36A"/>
+ </ownedAttribute>
+ </ownedMember>
+ <ownedMember xmi:type="uml:Class" xmi:id="_4WMkYNovEdqRBPR5WyT36A" name="HTTPSessionScopeContext" clientDependency="_9XeF4NovEdqRBPR5WyT36A">
+ <implementation xmi:id="_9XeF4NovEdqRBPR5WyT36A" client="_4WMkYNovEdqRBPR5WyT36A" supplier="_z_g4ANovEdqRBPR5WyT36A" realizingClassifier="_z_g4ANovEdqRBPR5WyT36A" contract="_z_g4ANovEdqRBPR5WyT36A">
+ <mapping xmi:id="_9XeF4dovEdqRBPR5WyT36A"/>
+ </implementation>
+ <ownedAttribute xmi:id="_9PH-Ado2EdqRBPR5WyT36A" name="scoperegistry" visibility="private" type="_o2gxANo0EdqRBPR5WyT36A" association="_9PH-ANo2EdqRBPR5WyT36A">
+ <upperValue xmi:type="uml:LiteralUnlimitedNatural" xmi:id="_9PH-BNo2EdqRBPR5WyT36A" value="1"/>
+ <lowerValue xmi:type="uml:LiteralInteger" xmi:id="_9PH-A9o2EdqRBPR5WyT36A"/>
+ </ownedAttribute>
+ </ownedMember>
+ <ownedMember xmi:type="uml:Association" xmi:id="_Bj8GUNowEdqRBPR5WyT36A" memberEnd="_Bj8GUdowEdqRBPR5WyT36A _Bj8GUtowEdqRBPR5WyT36A">
+ <ownedEnd xmi:id="_Bj8GUtowEdqRBPR5WyT36A" visibility="private" type="_tZF9oNovEdqRBPR5WyT36A" association="_Bj8GUNowEdqRBPR5WyT36A"/>
+ </ownedMember>
+ <ownedMember xmi:type="uml:Association" xmi:id="_FdlRYNowEdqRBPR5WyT36A" memberEnd="_FdlRYdowEdqRBPR5WyT36A _FdlRYtowEdqRBPR5WyT36A">
+ <ownedEnd xmi:id="_FdlRYtowEdqRBPR5WyT36A" visibility="private" type="_ePDcYNovEdqRBPR5WyT36A" association="_FdlRYNowEdqRBPR5WyT36A"/>
+ </ownedMember>
+ <ownedMember xmi:type="uml:Interface" xmi:id="_o2gxANo0EdqRBPR5WyT36A" name="ScopeRegistry"/>
+ <ownedMember xmi:type="uml:Interface" xmi:id="_Mz_E8No1EdqRBPR5WyT36A" name="Lifecycle"/>
+ <ownedMember xmi:type="uml:Interface" xmi:id="_TI7NwNo1EdqRBPR5WyT36A" name="InstanceWrapper">
+ <generalization xmi:id="_V7zlENo1EdqRBPR5WyT36A" general="_Mz_E8No1EdqRBPR5WyT36A"/>
+ </ownedMember>
+ <ownedMember xmi:type="uml:Association" xmi:id="_cNskcNo2EdqRBPR5WyT36A" memberEnd="_cNskcdo2EdqRBPR5WyT36A _cNskcto2EdqRBPR5WyT36A">
+ <ownedEnd xmi:id="_cNskcto2EdqRBPR5WyT36A" visibility="private" type="_z_g4ANovEdqRBPR5WyT36A" association="_cNskcNo2EdqRBPR5WyT36A"/>
+ </ownedMember>
+ <ownedMember xmi:type="uml:AssociationClass" xmi:id="_pdHMENo2EdqRBPR5WyT36A" name="AssociationClass1" memberEnd="_pdTZUNo2EdqRBPR5WyT36A _pdTZUdo2EdqRBPR5WyT36A">
+ <ownedEnd xmi:id="_pdTZUNo2EdqRBPR5WyT36A" visibility="private" type="_cNskcNo2EdqRBPR5WyT36A" association="_pdHMENo2EdqRBPR5WyT36A"/>
+ <ownedEnd xmi:id="_pdTZUdo2EdqRBPR5WyT36A" visibility="private" type="_ePDcYNovEdqRBPR5WyT36A" association="_pdHMENo2EdqRBPR5WyT36A"/>
+ </ownedMember>
+ <ownedMember xmi:type="uml:Association" xmi:id="_9PH-ANo2EdqRBPR5WyT36A" memberEnd="_9PH-Ado2EdqRBPR5WyT36A _9PH-Ato2EdqRBPR5WyT36A">
+ <ownedEnd xmi:id="_9PH-Ato2EdqRBPR5WyT36A" visibility="private" type="_4WMkYNovEdqRBPR5WyT36A" association="_9PH-ANo2EdqRBPR5WyT36A"/>
+ </ownedMember>
+ <ownedMember xmi:type="uml:Association" xmi:id="_99uwcNo2EdqRBPR5WyT36A" memberEnd="_99uwcdo2EdqRBPR5WyT36A _99uwcto2EdqRBPR5WyT36A">
+ <ownedEnd xmi:id="_99uwcto2EdqRBPR5WyT36A" visibility="private" type="_1yyMcNovEdqRBPR5WyT36A" association="_99uwcNo2EdqRBPR5WyT36A"/>
+ </ownedMember>
+</uml:Model>
diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/context/ComponentContextFactory.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/context/ComponentContextFactory.java new file mode 100644 index 0000000000..ed4b57639c --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/context/ComponentContextFactory.java @@ -0,0 +1,38 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.context; + +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.osoa.sca.ComponentContext; + +/** + * Interface implemented by the provider of the ComponentContext. + * + * @version $Rev$ $Date$ + */ +public interface ComponentContextFactory { + /** + * Create an instance of ComponentContext + * + * @param component The runtime component + * @param requestContextFactory The factory to create RequestContext + * @return An instance of ComponentContext for the component + */ + ComponentContext createComponentContext(RuntimeComponent component, RequestContextFactory requestContextFactory); +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/context/ContextFactoryExtensionPoint.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/context/ContextFactoryExtensionPoint.java new file mode 100644 index 0000000000..e92a8f2844 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/context/ContextFactoryExtensionPoint.java @@ -0,0 +1,50 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.context; + +/** + * An extension point for context factories. + * + * @version $Rev$ $Date$ + */ +public interface ContextFactoryExtensionPoint { + + /** + * Add a context factory extension. + * + * @param factory The factory to add + */ + void addFactory(Object factory); + + /** + * Remove a context factory extension. + * + * @param factory The factory to remove + */ + void removeFactory(Object factory); + + /** + * Get a factory implementing the given interface. + * @param factoryInterface the lookup key (factory interface) + * @return The factory + */ + <T> T getFactory(Class<T> factoryInterface); + +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/context/DefaultContextFactoryExtensionPoint.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/context/DefaultContextFactoryExtensionPoint.java new file mode 100644 index 0000000000..5a0aefe55d --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/context/DefaultContextFactoryExtensionPoint.java @@ -0,0 +1,114 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.context; + +import java.lang.reflect.Constructor; +import java.util.HashMap; + +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.extensibility.ServiceDiscovery; + +/** + * Default implementation of a model factory extension point. + * + * @version $Rev$ $Date$ + */ +public class DefaultContextFactoryExtensionPoint implements ContextFactoryExtensionPoint { + + /** + * The Map of Factories that have been registered. + */ + private HashMap<Class<?>, Object> factories = new HashMap<Class<?>, Object>(); + + private ExtensionPointRegistry registry; + + public DefaultContextFactoryExtensionPoint(ExtensionPointRegistry registry) { + this.registry = registry; + } + + /** + * Add a model factory extension. + * + * @param factory The factory to add. + * @throws IllegalArgumentException if factory is null + */ + public void addFactory(Object factory) throws IllegalArgumentException { + if (factory == null) { + throw new IllegalArgumentException("Cannot add null as a factory"); + } + + Class<?>[] interfaces = factory.getClass().getInterfaces(); + for (int i = 0; i<interfaces.length; i++) { + factories.put(interfaces[i], factory); + } + } + + /** + * Remove a model factory extension. + * + * @param factory The factory to remove + * @throws IllegalArgumentException if factory is null + */ + public void removeFactory(Object factory) throws IllegalArgumentException { + if (factory == null) { + throw new IllegalArgumentException("Cannot remove null as a factory"); + } + + Class<?>[] interfaces = factory.getClass().getInterfaces(); + for (int i = 0; i<interfaces.length; i++) { + factories.remove(interfaces[i]); + } + } + + /** + * Get a factory implementing the given interface. + * + * @param factoryInterface The lookup key (factory interface) + * @return The factory + */ + public <T> T getFactory(Class<T> factoryInterface) throws IllegalArgumentException { + if (factoryInterface == null) { + throw new IllegalArgumentException("Cannot get null as a factory"); + } + + Object factory = factories.get(factoryInterface); + if (factory == null) { + + // Dynamically load a factory class declared under META-INF/services + try { + Class<?> factoryClass = ServiceDiscovery.getInstance().loadFirstServiceClass(factoryInterface); + if (factoryClass != null) { + + // Default empty constructor + Constructor<?> constructor = factoryClass.getConstructor(ExtensionPointRegistry.class); + factory = constructor.newInstance(registry); + + // Cache the loaded factory + addFactory(factory); + } + } catch (Exception e) { + throw new IllegalArgumentException(e); + } + + } + + return factoryInterface.cast(factory); + } +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/context/PropertyValueFactory.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/context/PropertyValueFactory.java new file mode 100644 index 0000000000..9766e164b8 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/context/PropertyValueFactory.java @@ -0,0 +1,40 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.context; + +import org.apache.tuscany.sca.assembly.ComponentProperty; + +/** + * Interface implemented by the provider of the property values + * + * @version $Rev$ $Date$ + */ +public interface PropertyValueFactory { + + /** + * This method will create an instance of the value for the specified Property. + * + * @param property The Property from which to retrieve the property value + * @param type The type of the property value being retrieved from the Property + * @param <B> Type type of the property value being looked up + * + * @return the value for the Property + */ + <B> B createPropertyValue(ComponentProperty property, Class<B> type); +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/context/RequestContextFactory.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/context/RequestContextFactory.java new file mode 100644 index 0000000000..546757c766 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/context/RequestContextFactory.java @@ -0,0 +1,33 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.context; + +import org.osoa.sca.RequestContext; + +/** + * Interface implemented by the provider of the RequestContext. + * + * @version $Rev$ $Date$ + */ +public interface RequestContextFactory { + /** + * @return An instance of RequestContext for the current invocation + */ + RequestContext createRequestContext(); +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/endpointresolver/DefaultEndpointResolverFactoryExtensionPoint.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/endpointresolver/DefaultEndpointResolverFactoryExtensionPoint.java new file mode 100644 index 0000000000..04ac4ee20c --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/endpointresolver/DefaultEndpointResolverFactoryExtensionPoint.java @@ -0,0 +1,180 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.endpointresolver; + +import java.lang.reflect.Constructor; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.assembly.Endpoint; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.extensibility.ServiceDeclaration; +import org.apache.tuscany.sca.extensibility.ServiceDiscovery; + +/** + * Default implementation of a provider factory extension point. + * + * @version $Rev$ $Date$ + */ +public class DefaultEndpointResolverFactoryExtensionPoint implements EndpointResolverFactoryExtensionPoint { + + private ExtensionPointRegistry registry; + private final Map<Class<?>, EndpointResolverFactory> endpointResolverFactories = new HashMap<Class<?>, EndpointResolverFactory>(); + private boolean loaded; + + /** + * The default constructor. Does nothing. + * + */ + public DefaultEndpointResolverFactoryExtensionPoint(ExtensionPointRegistry registry) { + this.registry = registry; + } + + /** + * Add an endpoint resolver factory. + * + * @param endpointResolverFactory The resolver factory + */ + public void addEndpointResolverFactory(EndpointResolverFactory endpointResolverFactory){ + endpointResolverFactories.put(endpointResolverFactory.getModelType(), endpointResolverFactory); + } + + /** + * Remove a endpoint resolver factory. + * + * @param endpointResolverFactory The endpoint resolver factory + */ + public void removeEndpointResolverFactory(EndpointResolverFactory endpointResolverFactory){ + endpointResolverFactories.remove(endpointResolverFactory.getModelType()); + } + + /** + * Returns the provider factory associated with the given model type. + * @param modelType A model type + * @return The provider factory associated with the given model type + */ + public EndpointResolverFactory getEndpointResolverFactory(Class<?> modelType) { + loadProviderFactories(); + + Class<?>[] classes = modelType.getInterfaces(); + for (Class<?> c : classes) { + EndpointResolverFactory factory = endpointResolverFactories.get(c); + if (factory != null) { + return factory; + } + } + return endpointResolverFactories.get(modelType); + } + + + /** + * Load provider factories declared under META-INF/services. + * @param registry + */ + private synchronized void loadProviderFactories() { + if (loaded) + return; + + // Get the provider factory service declarations + Set<ServiceDeclaration> factoryDeclarations; + ServiceDiscovery serviceDiscovery = ServiceDiscovery.getInstance(); + try { + factoryDeclarations = serviceDiscovery.getServiceDeclarations(EndpointResolverFactory.class); + } catch (Exception e) { + throw new IllegalStateException(e); + } + + // Get the extension point + EndpointResolverFactoryExtensionPoint factoryExtensionPoint = + registry.getExtensionPoint(EndpointResolverFactoryExtensionPoint.class); + List<EndpointResolverFactory> factories = new ArrayList<EndpointResolverFactory>(); + + for (ServiceDeclaration factoryDeclaration : factoryDeclarations) { + Map<String, String> attributes = factoryDeclaration.getAttributes(); + + // Find the model type that identifies this resolver + String modelTypeName = attributes.get("model"); + + // Create a provider factory wrapper and register it + EndpointResolverFactory factory = + new LazyEndpointResolverFactory(registry, modelTypeName, factoryDeclaration); + factoryExtensionPoint.addEndpointResolverFactory(factory); + factories.add(factory); + } + + loaded = true; + } + + /** + * A wrapper around an endpoint provider factory allowing lazy + * loading and initialization of endpoint providers. + */ + private class LazyEndpointResolverFactory implements EndpointResolverFactory { + private ExtensionPointRegistry registry; + private String modelTypeName; + private ServiceDeclaration providerClass; + private EndpointResolverFactory factory; + private Class modelType; + + private LazyEndpointResolverFactory(ExtensionPointRegistry registry, + String modelTypeName, + ServiceDeclaration providerClass) { + this.registry = registry; + this.modelTypeName = modelTypeName; + this.providerClass = providerClass; + } + + @SuppressWarnings("unchecked") + private EndpointResolverFactory getFactory() { + if (factory == null) { + try { + Class<EndpointResolverFactory> factoryClass = (Class<EndpointResolverFactory>)providerClass.loadClass(); + Constructor<EndpointResolverFactory> constructor = + factoryClass.getConstructor(ExtensionPointRegistry.class); + factory = constructor.newInstance(registry); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + return factory; + } + + public EndpointResolver createEndpointResolver(Endpoint endpoint, Binding binding) { + return getFactory().createEndpointResolver(endpoint, binding); + } + + public Class getModelType() { + if (modelType == null) { + try { + modelType = providerClass.loadClass(modelTypeName); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + return modelType; + } + + } + +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/endpointresolver/EndpointResolver.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/endpointresolver/EndpointResolver.java new file mode 100644 index 0000000000..79a10f6d84 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/endpointresolver/EndpointResolver.java @@ -0,0 +1,55 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.endpointresolver; + + +/** + * A reference binding implementation can options implement this + * interface to tie into the Tuscany SCA runtime + * + * @version $Rev$ $Date$ + */ +public interface EndpointResolver { + + /** + * This method will be invoked when the endpoint is + * activated. It gives the resolver the opportunity + * to do any set up ready for when it is asked to + * resolve the endpoint when a message arrives + */ + void start(); + + /** + * This method will be invoked when the endpoint is + * to be resolved. The resolver will attempt to resolve the + * endpoint against available services. The resolvers extending + * this interface will provide environment or binding specific + * resolution processing + */ + void resolve(); + + /** + * This method will be invoked when the endpont is + * deactivated. It gives the resolver the opportunity + * to take and required resolver shutdown actions + */ + void stop(); + +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/endpointresolver/EndpointResolverFactory.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/endpointresolver/EndpointResolverFactory.java new file mode 100644 index 0000000000..fdd304a9c7 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/endpointresolver/EndpointResolverFactory.java @@ -0,0 +1,44 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.endpointresolver; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.assembly.Endpoint; + +/** + * A factory for creating the runtime artifacts that resolve endpoints. + * + * @version $Rev$ $Date$ + */ +public interface EndpointResolverFactory <M>{ + + /** + * Creates a new endpoint resolver for the given component, + * reference and binding. + * + * @param component The runtime component + * @param reference The reference on the runtime component + * @param enpoint The endpoint assembly model object + * @return The endpoint provider + */ + EndpointResolver createEndpointResolver(Endpoint endpoint, Binding binding); + + Class<M> getModelType(); +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/endpointresolver/EndpointResolverFactoryExtensionPoint.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/endpointresolver/EndpointResolverFactoryExtensionPoint.java new file mode 100644 index 0000000000..be55981131 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/endpointresolver/EndpointResolverFactoryExtensionPoint.java @@ -0,0 +1,57 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.endpointresolver; + +import java.util.List; + + +/** + * An extension point for resolver factories. Holds all of the resolver + * factories from loaded extension points. Allows a resolver factory + * to be located based on a given model type. Hence the runtime can + * generate endpoint resolvers from the in memory assembly model. + * + * @version $Rev$ $Date$ + */ +public interface EndpointResolverFactoryExtensionPoint { + + + /** + * Add an endpoint resolver factory. + * + * @param endpointResolverFactory The resolver factory + */ + void addEndpointResolverFactory(EndpointResolverFactory endpointResolverFactory); + + /** + * Remove a endpoint resolver factory. + * + * @param endpointResolverFactory The endpoint resolver factory + */ + void removeEndpointResolverFactory(EndpointResolverFactory endpointResolverFactory); + + /** + * Returns the endpoint resolver factory associated with the given binding type. + * @param bindingType A binding type + * @return The endpoint resolver factory associated with the given binding type + */ + EndpointResolverFactory getEndpointResolverFactory(Class<?> bindingType); + +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/event/Event.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/event/Event.java new file mode 100644 index 0000000000..992c1188f7 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/event/Event.java @@ -0,0 +1,33 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.event; + +/** + * The base interface for events that are propagated in the runtime + * + * @version $Rev$ $Date$ + */ +public interface Event { + + /** + * Returns the source of the event + */ + Object getSource(); + +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/event/EventFilter.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/event/EventFilter.java new file mode 100644 index 0000000000..d17aebd7e8 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/event/EventFilter.java @@ -0,0 +1,35 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.event; + +/** + * Evaluates whether a {@link RuntimeEventListener} is applicable to a given runtime event + * + * @version $Rev$ $Date$ + */ +public interface EventFilter { + + /** + * Performs the actual evaluation on an event + * @param event Returns true if the event matches implemented criteria + * @return Match result + */ + boolean match(Event event); + +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/event/EventPublisher.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/event/EventPublisher.java new file mode 100644 index 0000000000..f209eb8936 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/event/EventPublisher.java @@ -0,0 +1,55 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.event; + +/** + * Publishes events in the runtime by accepting {@link Event} objects and + * forwarding them to all registered {@link RuntimeEventListener} objects. + * + * @version $Rev$ $Date$ + */ +public interface EventPublisher { + + /** + * Publish an event to all registered listeners + * @param object The event to publish + */ + void publish(Event object); + + /** + * Registers a listener to receive notifications for the context + * @param listener The listener to add + */ + void addListener(RuntimeEventListener listener); + + /** + * Registers a listener to receive notifications for the context + * @param filter The filter that will be applied before the lister is called + * @param listener The lister to add + */ + void addListener(EventFilter filter, RuntimeEventListener listener); + + + /** + * Removes a previously registered listener + * @param listener The listener to remove + */ + void removeListener(RuntimeEventListener listener); + +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/event/RuntimeEventListener.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/event/RuntimeEventListener.java new file mode 100644 index 0000000000..b34dceee62 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/event/RuntimeEventListener.java @@ -0,0 +1,35 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.event; + +import java.util.EventListener; + +/** + * Listeners observe events fired in the SCA runtime. + * + * @version $Rev$ $Date$ + */ +public interface RuntimeEventListener extends EventListener { + + /** + * Accepts and event and acts on it + * @param event The event to act on + */ + void onEvent(Event event); +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/event/TrueFilter.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/event/TrueFilter.java new file mode 100644 index 0000000000..f888908340 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/event/TrueFilter.java @@ -0,0 +1,37 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.event; + +/** + * An event filter that always returns a true condition + * + * @version $Rev$ $Date$ + */ +public class TrueFilter implements EventFilter { + + /** + * Performs the actual evaluation on an event. Always returns true + * in this case + * @param event The incoming event which is ignored + * @return true + */ + public boolean match(Event event) { + return true; + } +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/invocation/DataExchangeSemantics.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/invocation/DataExchangeSemantics.java new file mode 100644 index 0000000000..957a15ce8a --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/invocation/DataExchangeSemantics.java @@ -0,0 +1,34 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.invocation; + +/** + * An invoker or interceptor can optionally implement this interface to indicate if they can + * enforce the pass-by-value semantics for an operation on remotable interfaces. + * + * @version $Rev$ $Date$ + */ +public interface DataExchangeSemantics { + /** + * Indicate if the data can be passed in by reference as they won't be mutated. + * @return true if pass-by-reference is allowed + */ + boolean allowsPassByReference(); +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/invocation/Interceptor.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/invocation/Interceptor.java new file mode 100644 index 0000000000..a5f221fc11 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/invocation/Interceptor.java @@ -0,0 +1,40 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.invocation; + +/** + * Synchronous mediation associated with a client- or target- side wire. + * + * @version $Rev$ $Date$ + */ +public interface Interceptor extends Invoker { + + /** + * Sets the next invoker + * @param next The next invoker + */ + void setNext(Invoker next); + + /** + * Returns the next invoker or null + * @return The next Invoker + */ + Invoker getNext(); + +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/invocation/InvocationChain.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/invocation/InvocationChain.java new file mode 100644 index 0000000000..75719bb0cc --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/invocation/InvocationChain.java @@ -0,0 +1,112 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.invocation; + +import org.apache.tuscany.sca.interfacedef.Operation; + +/** + * A wire consists of 1..n invocation chains associated with the operations of its source service contract. + * <p/> + * Invocation chains may contain <code>Interceptors</code> that process invocations. + * <p/> + * A <code>Message</code> is used to pass data associated with an invocation through the chain. + * + * @version $Rev$ $Date$ + */ +public interface InvocationChain { + /** + * Returns the target operation for this invocation chain. + * + * @return The target operation for this invocation chain + */ + Operation getTargetOperation(); + + /** + * Updates the target operation for this invocation chain. + * + * @param operation The new target operation for this invocation chain + */ + void setTargetOperation(Operation operation); + + /** + * Returns the source operation for this invocation chain. + * + * @return The source operation for this invocation chain + */ + Operation getSourceOperation(); + + /** + * Adds an interceptor to the chain. For reference side, it will be added to + * Phase.REFERENCE. For service side, it will be added to Phase.SERVICE + * + * @param interceptor The interceptor to add + */ + void addInterceptor(Interceptor interceptor); + + /** + * Adds an invoker to the chain + * + * @param invoker The invoker to add + */ + void addInvoker(Invoker invoker); + + /** + * Returns the first invoker in the chain. + * + * @return The first invoker in the chain + */ + Invoker getHeadInvoker(); + + /** + * @deprecated This method is not used + * Returns the last invoker in the chain. + * + * @return The last invoker in the chain + */ + @Deprecated + Invoker getTailInvoker(); + + /** + * @deprecated Please use <code>void addInterceptor(String phase, Interceptor interceptor);</code> + * Adds an interceptor at the given position in the interceptor stack + * + * @param index The position in the interceptor stack to add the interceptor + * @param interceptor The interceptor to add + */ + @Deprecated + void addInterceptor(int index, Interceptor interceptor); + + /** + * Add an interceptor to the given phase + * @param phase + * @param interceptor + */ + void addInterceptor(String phase, Interceptor interceptor); + + /** + * Indicate if the data can be passed in by reference as they won't be mutated. + * @return true if pass-by-reference is allowed + */ + boolean allowsPassByReference(); + /** + * Force the invocation to allow pass-by-reference + * @param allowsPBR + */ + void setAllowsPassByReference(boolean allowsPBR); +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/invocation/Invoker.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/invocation/Invoker.java new file mode 100644 index 0000000000..2748bbed9a --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/invocation/Invoker.java @@ -0,0 +1,36 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.invocation; + +/** + * Synchronous mediation associated with a client- or target- side wire. + * + * @version $Rev$ $Date$ + */ +public interface Invoker { + + /** + * Process a synchronous wire + * + * @param msg The request Message for the wire + * @return The response Message from the wire + */ + Message invoke(Message msg); + +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/invocation/Message.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/invocation/Message.java new file mode 100644 index 0000000000..16cb4132e4 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/invocation/Message.java @@ -0,0 +1,127 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.invocation; + +import java.util.List; +import java.util.Map; + +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.runtime.EndpointReference; + +/** + * Represents a request, response, or exception flowing through a wire + * + * @version $Rev $Date$ + */ +public interface Message { + + /** + * Returns the body of the message, which will be the payload or parameters associated with the wire + * @return The body of the message + */ + <T> T getBody(); + + /** + * Sets the body of the message. + * @param body The body of the message + */ + <T> void setBody(T body); + + /** + * Get the end point reference of the source reference + * @return The end point reference of the reference originating the message + */ + EndpointReference getFrom(); + + /** + * Set the end point reference of the reference originating the message + * @param from The end point reference of the reference originating the message + */ + void setFrom(EndpointReference from); + + /** + * Get the end point reference of target service + * @return The end point reference of the service that the message targets + */ + EndpointReference getTo(); + + /** + * Set the end point reference of target service + * @param to The end point reference of the service that the message targets + */ + void setTo(EndpointReference to); + + /** + * Returns the id of the message + * @return The message Id + */ + Object getMessageID(); + + /** + * Sets the id of the message + * @param messageId The message ID + */ + void setMessageID(Object messageId); + + /** + * Determines if the message represents a fault/exception + * + * @return true If the message body is a fault object, false if the body is a normal payload + */ + boolean isFault(); + + /** + * Set the message body with a fault object. After this method is called, isFault() returns true. + * + * @param fault The fault object represents an exception + */ + <T> void setFaultBody(T fault); + + /** + * Returns the operation that created the message. + * + * @return The operation that created the message + */ + Operation getOperation(); + + /** + * Sets the operation that created the message. + * + * @param op The operation that created the message + */ + void setOperation(Operation op); + + /** + * Returns a list of objects that are contained in the message header + * + * @return + */ + List<Object> getHeaders(); + + /** + * Returns the binding context in force for this message + */ + <T> T getBindingContext(); + + /** + * Set the binding context that is in force for this message + * @param bindingContext + */ + <T> void setBindingContext(T bindingContext); +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/invocation/MessageFactory.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/invocation/MessageFactory.java new file mode 100644 index 0000000000..38c900e36a --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/invocation/MessageFactory.java @@ -0,0 +1,36 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.invocation; + + +/** + * A factory for messages + * + * @version $Rev $Date$ + */ +public interface MessageFactory { + + /** + * Creates a new message. + * + * @return The new message + */ + Message createMessage(); + +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/invocation/Phase.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/invocation/Phase.java new file mode 100644 index 0000000000..af8ad6e582 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/invocation/Phase.java @@ -0,0 +1,69 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.invocation; + +/** + * Tuscany built-in phases for the invocation chain + * + * @version $Rev$ $Date$ + */ +public interface Phase { + // The first phase for outgoing invocations via a reference + String REFERENCE = "component.reference"; + + // data transformation and validation + String REFERENCE_INTERFACE = "reference.interface"; + + // reference policy handling + String REFERENCE_POLICY = "reference.policy"; + + // reference binding invoker + String REFERENCE_BINDING = "reference.binding"; + + String REFERENCE_BINDING_WIREFORMAT = "reference.binding.wireformat"; + String REFERENCE_BINDING_POLICY = "reference.binding.policy"; + String REFERENCE_BINDING_TRANSPORT = "reference.binding.transport"; + + String SERVICE_BINDING_TRANSPORT = "service.binding.transport"; + String SERVICE_BINDING_OPERATION_SELECTOR = "service.binding.operationselector"; + String SERVICE_BINDING_WIREFORMAT = "service.binding.wireformat"; + String SERVICE_BINDING_POLICY = "service.binding.policy"; + + + // The first phase for incoming invocations via a service + String SERVICE_BINDING = "service.binding"; + + // service policy handling + String SERVICE_POLICY = "service.policy"; + + // data validation and transformation + String SERVICE_INTERFACE = "service.interface"; + + // TODO: not sure if we need to have this face + String SERVICE = "component.service"; + + // implementation policy handling + String IMPLEMENTATION_POLICY = "implementation.policy"; + + // implementation invoker + String IMPLEMENTATION = "component.implementation"; + + // String getName(); +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/management/ManagementService.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/management/ManagementService.java new file mode 100644 index 0000000000..3887db4873 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/management/ManagementService.java @@ -0,0 +1,39 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.management; + +import org.apache.tuscany.sca.runtime.RuntimeComponent; + +/** + * Interface for the management service abstraction. The implementation + * could be based on a variety of technologies including JMX, WSDM, + * SNMP etc. + * + * @version $Revision$ $Date$ + */ +public interface ManagementService { + + /** + * Registers a component for management. + * + * @param name Name of the component. + * @param component Component to be registered. + */ + void registerComponent(String name, RuntimeComponent component); +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/BindingProviderFactory.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/BindingProviderFactory.java new file mode 100644 index 0000000000..0f6a932c51 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/BindingProviderFactory.java @@ -0,0 +1,60 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.provider; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; + +/** + * A factory for creating the runtime artifacts that represent bindings. + * + * @version $Rev$ $Date$ + */ +public interface BindingProviderFactory<M extends Binding> extends ProviderFactory<M> { + + /** + * Creates a new reference binding provider for the given component and + * reference. + * + * @param component The runtime component + * @param reference The reference on the runtime component + * @param binding The binding assembly model object + * @return The binding provider + */ + ReferenceBindingProvider createReferenceBindingProvider(RuntimeComponent component, + RuntimeComponentReference reference, + M binding); + + /** + * Creates a new service binding provider for the given component and + * service. + * + * @param component The runtime component + * @param service The service on the runtime component + * @param binding The binding assembly model object + * @return The binding provider + */ + ServiceBindingProvider createServiceBindingProvider(RuntimeComponent component, + RuntimeComponentService service, + M binding); + +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/DefaultProviderFactoryExtensionPoint.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/DefaultProviderFactoryExtensionPoint.java new file mode 100644 index 0000000000..df46af121c --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/DefaultProviderFactoryExtensionPoint.java @@ -0,0 +1,509 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.provider; + +import java.lang.reflect.Constructor; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.assembly.Implementation; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.extensibility.ServiceDeclaration; +import org.apache.tuscany.sca.extensibility.ServiceDiscovery; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; + +/** + * Default implementation of a provider factory extension point. + * + * @version $Rev$ $Date$ + */ +public class DefaultProviderFactoryExtensionPoint implements ProviderFactoryExtensionPoint { + + private ExtensionPointRegistry registry; + private final Map<Class<?>, ProviderFactory> providerFactories = new HashMap<Class<?>, ProviderFactory>(); + private final List<PolicyProviderFactory> policyProviderFactories = new ArrayList<PolicyProviderFactory>(); + private boolean loaded; + + /** + * The default constructor. Does nothing. + * + */ + public DefaultProviderFactoryExtensionPoint(ExtensionPointRegistry registry) { + this.registry = registry; + } + + /** + * Add a provider factory. + * + * @param providerFactory The provider factory + */ + public void addProviderFactory(ProviderFactory providerFactory) { + if(providerFactory instanceof PolicyProviderFactory) { + policyProviderFactories.add((PolicyProviderFactory)providerFactory); + } + providerFactories.put(providerFactory.getModelType(), providerFactory); + } + + /** + * Remove a provider factory. + * + * @param providerFactory The provider factory + */ + public void removeProviderFactory(ProviderFactory providerFactory) { + if(providerFactory instanceof PolicyProviderFactory) { + policyProviderFactories.remove((PolicyProviderFactory)providerFactory); + } + providerFactories.remove(providerFactory.getModelType()); + } + + /** + * Returns the provider factory associated with the given model type. + * @param modelType A model type + * @return The provider factory associated with the given model type + */ + public ProviderFactory getProviderFactory(Class<?> modelType) { + loadProviderFactories(); + + Class<?>[] classes = modelType.getInterfaces(); + for (Class<?> c : classes) { + ProviderFactory factory = providerFactories.get(c); + if (factory != null) { + return factory; + } + } + return providerFactories.get(modelType); + } + + public List<PolicyProviderFactory> getPolicyProviderFactories() { + loadProviderFactories(); + return policyProviderFactories; + } + + /** + * Load provider factories declared under META-INF/services. + * @param registry + */ + private synchronized void loadProviderFactories() { + if (loaded) + return; + + loadProviderFactories(BindingProviderFactory.class); + loadProviderFactories(ImplementationProviderFactory.class); + loadProviderFactories(PolicyProviderFactory.class); + loadProviderFactories(WireFormatProviderFactory.class); + loadProviderFactories(OperationSelectorProviderFactory.class); + + loaded = true; + } + + /** + * Load provider factories declared under META-INF/services. + * @param registry + * @param factoryClass + * @return + */ + private List<ProviderFactory> loadProviderFactories(Class<?> factoryClass) { + + // Get the provider factory service declarations + Set<ServiceDeclaration> factoryDeclarations; + ServiceDiscovery serviceDiscovery = ServiceDiscovery.getInstance(); + try { + factoryDeclarations = serviceDiscovery.getServiceDeclarations(factoryClass); + } catch (Exception e) { + throw new IllegalStateException(e); + } + + // Get the target extension point + ProviderFactoryExtensionPoint factoryExtensionPoint = + registry.getExtensionPoint(ProviderFactoryExtensionPoint.class); + List<ProviderFactory> factories = new ArrayList<ProviderFactory>(); + + for (ServiceDeclaration factoryDeclaration : factoryDeclarations) { + Map<String, String> attributes = factoryDeclaration.getAttributes(); + + // Load an implementation provider factory + if (factoryClass == ImplementationProviderFactory.class) { + String modelTypeName = attributes.get("model"); + + // Create a provider factory wrapper and register it + ImplementationProviderFactory factory = + new LazyImplementationProviderFactory(registry, modelTypeName, factoryDeclaration); + factoryExtensionPoint.addProviderFactory(factory); + factories.add(factory); + + } else if (factoryClass == BindingProviderFactory.class) { + + // Load a binding provider factory + String modelTypeName = attributes.get("model"); + + // Create a provider factory wrapper and register it + BindingProviderFactory factory = + new LazyBindingProviderFactory(registry, modelTypeName, factoryDeclaration); + factoryExtensionPoint.addProviderFactory(factory); + factories.add(factory); + } else if (factoryClass == PolicyProviderFactory.class) { + // Load a policy provider factory + String modelTypeName = attributes.get("model"); + + // Create a provider factory wrapper and register it + PolicyProviderFactory factory = + new LazyPolicyProviderFactory(registry, modelTypeName, factoryDeclaration); + factoryExtensionPoint.addProviderFactory(factory); + factories.add(factory); + } else if (factoryClass == WireFormatProviderFactory.class) { + + // Load a wire format provider factory + String modelTypeName = attributes.get("model"); + + // Create a provider factory wrapper and register it + WireFormatProviderFactory factory = + new LazyWireFormatProviderFactory(registry, modelTypeName, factoryDeclaration); + factoryExtensionPoint.addProviderFactory(factory); + factories.add(factory); + } else if (factoryClass == OperationSelectorProviderFactory.class) { + + // Load a wire format provider factory + String modelTypeName = attributes.get("model"); + + // Create a provider factory wrapper and register it + OperationSelectorProviderFactory factory = + new LazyOperationSelectorProviderFactory(registry, modelTypeName, factoryDeclaration); + factoryExtensionPoint.addProviderFactory(factory); + factories.add(factory); + } + } + return factories; + } + + /** + * A wrapper around an implementation provider factory allowing lazy + * loading and initialization of implementation providers. + */ + private static class LazyBindingProviderFactory implements BindingProviderFactory { + + private ExtensionPointRegistry registry; + private String modelTypeName; + private ServiceDeclaration factoryDeclaration; + private BindingProviderFactory factory; + private Class modelType; + + private LazyBindingProviderFactory(ExtensionPointRegistry registry, + String modelTypeName, + ServiceDeclaration factoryDeclaration) { + this.registry = registry; + this.modelTypeName = modelTypeName; + this.factoryDeclaration = factoryDeclaration; + } + + @SuppressWarnings("unchecked") + private BindingProviderFactory getFactory() { + if (factory == null) { + try { + Class<BindingProviderFactory> factoryClass = + (Class<BindingProviderFactory>)factoryDeclaration.loadClass(); + Constructor<BindingProviderFactory> constructor = + factoryClass.getConstructor(ExtensionPointRegistry.class); + factory = constructor.newInstance(registry); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + return factory; + } + + @SuppressWarnings("unchecked") + public ReferenceBindingProvider createReferenceBindingProvider(RuntimeComponent component, + RuntimeComponentReference reference, + Binding binding) { + return getFactory().createReferenceBindingProvider(component, reference, binding); + } + + @SuppressWarnings("unchecked") + public ServiceBindingProvider createServiceBindingProvider(RuntimeComponent component, + RuntimeComponentService service, + Binding binding) { + return getFactory().createServiceBindingProvider(component, service, binding); + } + + public Class getModelType() { + if (modelType == null) { + try { + modelType = factoryDeclaration.loadClass(modelTypeName); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + return modelType; + } + + } + + /** + * A wrapper around an implementation provider factory allowing lazy + * loading and initialization of implementation providers. + */ + private class LazyImplementationProviderFactory implements ImplementationProviderFactory { + + private ExtensionPointRegistry registry; + private String modelTypeName; + private ServiceDeclaration providerClass; + private ImplementationProviderFactory factory; + private Class modelType; + + private LazyImplementationProviderFactory(ExtensionPointRegistry registry, + String modelTypeName, + ServiceDeclaration providerClass) { + this.registry = registry; + this.modelTypeName = modelTypeName; + this.providerClass = providerClass; + } + + @SuppressWarnings("unchecked") + private ImplementationProviderFactory getFactory() { + if (factory == null) { + try { + Class<ImplementationProviderFactory> factoryClass = + (Class<ImplementationProviderFactory>)providerClass.loadClass(); + Constructor<ImplementationProviderFactory> constructor = + factoryClass.getConstructor(ExtensionPointRegistry.class); + factory = constructor.newInstance(registry); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + return factory; + } + + @SuppressWarnings("unchecked") + public ImplementationProvider createImplementationProvider(RuntimeComponent component, + Implementation Implementation) { + return getFactory().createImplementationProvider(component, Implementation); + } + + public Class getModelType() { + if (modelType == null) { + try { + + modelType = providerClass.loadClass(modelTypeName); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + return modelType; + } + + } + + /** + * A wrapper around an policy provider factory allowing lazy + * loading and initialization of policy providers. + */ + private class LazyPolicyProviderFactory implements PolicyProviderFactory { + private ExtensionPointRegistry registry; + private String modelTypeName; + private ServiceDeclaration providerClass; + private PolicyProviderFactory factory; + private Class modelType; + + private LazyPolicyProviderFactory(ExtensionPointRegistry registry, + String modelTypeName, + ServiceDeclaration providerClass) { + this.registry = registry; + this.modelTypeName = modelTypeName; + this.providerClass = providerClass; + } + + @SuppressWarnings("unchecked") + private PolicyProviderFactory getFactory() { + if (factory == null) { + try { + Class<PolicyProviderFactory> factoryClass = (Class<PolicyProviderFactory>)providerClass.loadClass(); + Constructor<PolicyProviderFactory> constructor = + factoryClass.getConstructor(ExtensionPointRegistry.class); + factory = constructor.newInstance(registry); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + return factory; + } + + public PolicyProvider createImplementationPolicyProvider(RuntimeComponent component, + Implementation implementation) { + return getFactory().createImplementationPolicyProvider(component, implementation); + } + + public PolicyProvider createReferencePolicyProvider(RuntimeComponent component, + RuntimeComponentReference reference, + Binding binding) { + return getFactory().createReferencePolicyProvider(component, reference, binding); + } + + public PolicyProvider createServicePolicyProvider(RuntimeComponent component, + RuntimeComponentService service, + Binding binding) { + return getFactory().createServicePolicyProvider(component, service, binding); + } + + public Class getModelType() { + if (modelType == null) { + try { + modelType = providerClass.loadClass(modelTypeName); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + return modelType; + } + } + + /** + * A wrapper around a wire format provider factory allowing lazy + * loading and initialization of wire format providers. + */ + private class LazyWireFormatProviderFactory implements WireFormatProviderFactory { + + private ExtensionPointRegistry registry; + private String modelTypeName; + private ServiceDeclaration providerClass; + private WireFormatProviderFactory factory; + private Class modelType; + + private LazyWireFormatProviderFactory(ExtensionPointRegistry registry, + String modelTypeName, + ServiceDeclaration providerClass) { + this.registry = registry; + this.modelTypeName = modelTypeName; + this.providerClass = providerClass; + } + + @SuppressWarnings("unchecked") + private WireFormatProviderFactory getFactory() { + if (factory == null) { + try { + Class<WireFormatProviderFactory> factoryClass = + (Class<WireFormatProviderFactory>)providerClass.loadClass(); + Constructor<WireFormatProviderFactory> constructor = + factoryClass.getConstructor(ExtensionPointRegistry.class); + factory = constructor.newInstance(registry); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + return factory; + } + + @SuppressWarnings("unchecked") + public WireFormatProvider createReferenceWireFormatProvider(RuntimeComponent component, + RuntimeComponentReference reference, + Binding binding){ + return getFactory().createReferenceWireFormatProvider(component, reference, binding); + } + + @SuppressWarnings("unchecked") + public WireFormatProvider createServiceWireFormatProvider(RuntimeComponent component, + RuntimeComponentService service, + Binding binding){ + return getFactory().createServiceWireFormatProvider(component, service, binding); + } + + public Class getModelType() { + if (modelType == null) { + try { + + modelType = providerClass.loadClass(modelTypeName); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + return modelType; + } + } + + /** + * A wrapper around a operation selector provider factory allowing lazy + * loading and initialization of operation selector providers. + */ + private class LazyOperationSelectorProviderFactory implements OperationSelectorProviderFactory { + + private ExtensionPointRegistry registry; + private String modelTypeName; + private ServiceDeclaration providerClass; + private OperationSelectorProviderFactory factory; + private Class modelType; + + private LazyOperationSelectorProviderFactory(ExtensionPointRegistry registry, + String modelTypeName, + ServiceDeclaration providerClass) { + this.registry = registry; + this.modelTypeName = modelTypeName; + this.providerClass = providerClass; + } + + @SuppressWarnings("unchecked") + private OperationSelectorProviderFactory getFactory() { + if (factory == null) { + try { + Class<OperationSelectorProviderFactory> factoryClass = + (Class<OperationSelectorProviderFactory>)providerClass.loadClass(); + Constructor<OperationSelectorProviderFactory> constructor = + factoryClass.getConstructor(ExtensionPointRegistry.class); + factory = constructor.newInstance(registry); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + return factory; + } + + @SuppressWarnings("unchecked") + public OperationSelectorProvider createReferenceOperationSelectorProvider(RuntimeComponent component, + RuntimeComponentReference reference, + Binding binding){ + return getFactory().createReferenceOperationSelectorProvider(component, reference, binding); + } + + @SuppressWarnings("unchecked") + public OperationSelectorProvider createServiceOperationSelectorProvider(RuntimeComponent component, + RuntimeComponentService service, + Binding binding){ + return getFactory().createServiceOperationSelectorProvider(component, service, binding); + } + + public Class getModelType() { + if (modelType == null) { + try { + + modelType = providerClass.loadClass(modelTypeName); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + return modelType; + } + } + +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/DefaultSCADefinitionsProviderExtensionPoint.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/DefaultSCADefinitionsProviderExtensionPoint.java new file mode 100644 index 0000000000..76ca061bab --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/DefaultSCADefinitionsProviderExtensionPoint.java @@ -0,0 +1,91 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.provider; + +import java.lang.reflect.Constructor; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.extensibility.ServiceDeclaration; +import org.apache.tuscany.sca.extensibility.ServiceDiscovery; + +/** + * Concrete Implementation for the SCADefinitionsProviderExtensionPoint + * + * @version $Rev$ $Date$ + */ +public class DefaultSCADefinitionsProviderExtensionPoint implements + SCADefinitionsProviderExtensionPoint { + + private ExtensionPointRegistry extensionPointRegistry = null; + + private List<SCADefinitionsProvider> scaDefnsProviders = new ArrayList<SCADefinitionsProvider>(); + + public DefaultSCADefinitionsProviderExtensionPoint(ExtensionPointRegistry extnPtReg) { + this.extensionPointRegistry = extnPtReg; + } + + public void addSCADefinitionsProvider(SCADefinitionsProvider provider) { + scaDefnsProviders.add(provider); + } + + public void removeSCADefinitionsProvider(SCADefinitionsProvider provider) { + scaDefnsProviders.remove(provider); + } + + public List<SCADefinitionsProvider> getSCADefinitionsProviders() { + if (scaDefnsProviders.isEmpty()) { + loadProviders(); + } + return scaDefnsProviders; + } + + private synchronized void loadProviders() { + // Get the provider service declarations + Set<ServiceDeclaration> defnProviderDecls; + SCADefinitionsProvider aProvider = null; + Class providerClass = null; + Constructor constructor = null; + + try { + defnProviderDecls = + ServiceDiscovery.getInstance().getServiceDeclarations(SCADefinitionsProvider.class); + + for (ServiceDeclaration aDefnProviderDecl : defnProviderDecls) { + providerClass = aDefnProviderDecl.loadClass(); + + try { + constructor = providerClass.getConstructor(); + aProvider = (SCADefinitionsProvider)constructor.newInstance(); + } catch (NoSuchMethodException e1) { + constructor = providerClass.getConstructor(ExtensionPointRegistry.class); + aProvider = (SCADefinitionsProvider)constructor.newInstance(extensionPointRegistry); + } + + scaDefnsProviders.add(aProvider); + } + } catch (Exception e) { + throw new RuntimeException(e); + } + + } +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/ImplementationProvider.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/ImplementationProvider.java new file mode 100644 index 0000000000..015c673d66 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/ImplementationProvider.java @@ -0,0 +1,68 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.provider; + +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; + +/** + * A component implementation can implement this interface in order to tie + * into the Tuscany runtime + * + * @version $Rev$ $Date$ + */ +public interface ImplementationProvider { + + /** + * This method will be invoked when the component implementation + * is activated. + */ + void start(); + + /** + * This method will be invoked when the component implementation + * is deactivated. + */ + void stop(); + + /** + * Create an invoker for the component implementation in the invocation + * chain. The invoker will be responsible for calling the implementation + * logic for the given component. + * + * @param service The component service + * @param operation The operation that the interceptor will handle + * @return An invoker that handles the invocation logic, null should be + * returned if no invoker is required + */ + Invoker createInvoker(RuntimeComponentService service, Operation operation); + + /** + * For bindings that invoke one-way callback operations asynchronously, + * there is no need to perform a thread switch before calling the invoker. + * This method indicates whether the binding has this capability. + * + * @return true if the callback invoker is able to invoke one-way operations + * asynchronously, false if all invocations are synchronous + */ + boolean supportsOneWayInvocation(); + +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/ImplementationProviderFactory.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/ImplementationProviderFactory.java new file mode 100644 index 0000000000..6a37d1e951 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/ImplementationProviderFactory.java @@ -0,0 +1,42 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.provider; + +import org.apache.tuscany.sca.assembly.Implementation; +import org.apache.tuscany.sca.runtime.RuntimeComponent; + +/** + * An interface for factories that create implementation providers. + * + * @version $Rev$ $Date$ + */ +public interface ImplementationProviderFactory<M extends Implementation> extends ProviderFactory<M> { + + /** + * Creates a new implementation provider for the given + * component. + * + * @param component The runtime component + * @param Implementation The implementation type + * @return The implementation provider + */ + ImplementationProvider createImplementationProvider(RuntimeComponent component, M Implementation); + +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/OperationSelectorProvider.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/OperationSelectorProvider.java new file mode 100644 index 0000000000..f385c7dfba --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/OperationSelectorProvider.java @@ -0,0 +1,39 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.provider; + +import org.apache.tuscany.sca.invocation.Interceptor; + +/** + * @version $Rev$ $Date$ + */ +public interface OperationSelectorProvider { + /** + * Create an interceptor for the operation selector + * @return An interceptor that realize the policySet + */ + Interceptor createInterceptor(); + + /** + * Get the phase that the interceptor should be added + * @return The phase that this interceptor belongs to + */ + String getPhase(); +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/OperationSelectorProviderFactory.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/OperationSelectorProviderFactory.java new file mode 100644 index 0000000000..183b38cb33 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/OperationSelectorProviderFactory.java @@ -0,0 +1,53 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.provider; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.assembly.OperationSelector; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; + +/** + * @version $Rev$ $Date$ + */ +public interface OperationSelectorProviderFactory<M extends OperationSelector> extends ProviderFactory<M> { + /** + * Create wire format provider for a given reference binding + * @param component + * @param reference + * @param binding + * @return + */ + OperationSelectorProvider createReferenceOperationSelectorProvider(RuntimeComponent component, + RuntimeComponentReference reference, + Binding binding); + + /** + * Create policy provider for a given service binding + * @param component + * @param service + * @param binding + * @return + */ + OperationSelectorProvider createServiceOperationSelectorProvider(RuntimeComponent component, + RuntimeComponentService service, + Binding binding); +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/PolicyImplementor.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/PolicyImplementor.java new file mode 100644 index 0000000000..f2b59a7c54 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/PolicyImplementor.java @@ -0,0 +1,38 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.provider; + +import java.util.List; + +import javax.xml.namespace.QName; + +/** + * This interface can be optionally implemented by the Binding or Implementation providers to + * indicate if they implement the policies in the binding/implementation provider. + * + * @version $Rev$ $Date$ + */ +public interface PolicyImplementor { + /** + * Get a list of policy names that are implemented by this policy implementor + * @return A list of policy names + */ + List<QName> getImplementedPolicies(); +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/PolicyProvider.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/PolicyProvider.java new file mode 100644 index 0000000000..644283dea1 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/PolicyProvider.java @@ -0,0 +1,41 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.provider; + +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.Interceptor; + +/** + * @version $Rev$ $Date$ + */ +public interface PolicyProvider { + /** + * Create an interceptor for a given operation + * @param operation + * @return An interceptor that realize the policySet + */ + Interceptor createInterceptor(Operation operation); + + /** + * Get the phase that the interceptor should be added + * @return The phase that this interceptor belongs to + */ + String getPhase(); +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/PolicyProviderFactory.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/PolicyProviderFactory.java new file mode 100644 index 0000000000..b60a14d2da --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/PolicyProviderFactory.java @@ -0,0 +1,63 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.provider; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.assembly.Implementation; +import org.apache.tuscany.sca.policy.Policy; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; + +/** + * @version $Rev$ $Date$ + */ +public interface PolicyProviderFactory<M extends Policy> extends ProviderFactory<M> { + /** + * Create policy provider for a given reference binding + * @param component + * @param reference + * @param binding + * @return + */ + PolicyProvider createReferencePolicyProvider(RuntimeComponent component, + RuntimeComponentReference reference, + Binding binding); + + /** + * Create policy provider for a given service binding + * @param component + * @param service + * @param binding + * @return + */ + PolicyProvider createServicePolicyProvider(RuntimeComponent component, + RuntimeComponentService service, + Binding binding); + + /** + * Create policy provider for a given component implementation + * @param component + * @param implementation + * @return + */ + PolicyProvider createImplementationPolicyProvider(RuntimeComponent component, Implementation implementation); + +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/ProviderFactory.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/ProviderFactory.java new file mode 100644 index 0000000000..2102806881 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/ProviderFactory.java @@ -0,0 +1,36 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.provider; + +/** + * A factory for runtime providers. + * + * @version $Rev$ $Date$ + */ +public interface ProviderFactory<M> { + + /** + * The model type that this factory creates providers for. + * + * @return the model type + */ + Class<M> getModelType(); + +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/ProviderFactoryExtensionPoint.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/ProviderFactoryExtensionPoint.java new file mode 100644 index 0000000000..d8f9973338 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/ProviderFactoryExtensionPoint.java @@ -0,0 +1,63 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.provider; + +import java.util.List; + + +/** + * An extension point for provider factories. Holds all of the provider + * factories from loaded extension points. Allows a provider factory + * to be located based on a given model type. Hence the runtime can + * generate runtime artifacts from the in memory assembly model. + * + * @version $Rev$ $Date$ + */ +public interface ProviderFactoryExtensionPoint { + + + /** + * Add a provider factory. + * + * @param providerFactory The provider factory + */ + void addProviderFactory(ProviderFactory providerFactory); + + /** + * Remove a provider factory. + * + * @param providerFactory The provider factory + */ + void removeProviderFactory(ProviderFactory providerFactory); + + /** + * Returns the provider factory associated with the given model type. + * @param modelType A model type + * @return The provider factory associated with the given model type + */ + ProviderFactory getProviderFactory(Class<?> modelType); + + /** + * Get a list of registered PolicyProviderFactory + * @return a list of registered PolicyProviderFactory + */ + List<PolicyProviderFactory> getPolicyProviderFactories(); + +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/ReferenceBindingProvider.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/ReferenceBindingProvider.java new file mode 100644 index 0000000000..b3ab1d8b87 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/ReferenceBindingProvider.java @@ -0,0 +1,76 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.provider; + +import org.apache.tuscany.sca.interfacedef.InterfaceContract; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.Invoker; + +/** + * A reference binding implementation can options implement this + * interface to tie into the Tuscany SCA runtime + * + * @version $Rev$ $Date$ + */ +public interface ReferenceBindingProvider { + + /** + * This method will be invoked when the component reference binding is + * activated. + */ + void start(); + + /** + * This method will be invoked when the component reference binding is + * deactivated. + */ + void stop(); + + /** + * Create an invoker for the reference binding in the invocation chain. The + * invoker is responsible for making the outbound invocation over the + * binding protocol. + * + * @param operation The operation that the interceptor will handle + * @return An invoker that handles the invocation logic, null should be + * returned if no invoker is required + */ + Invoker createInvoker(Operation operation); + + /** + * Get the effective interface contract imposed by the binding. For example, + * it will be interface contract introspected from the WSDL portType used by + * the endpoint for a WebService binding. + * + * @return The effective interface contract, if null is returned, the + * interface contract for the component reference will be used + */ + InterfaceContract getBindingInterfaceContract(); + + /** + * For bindings that invoke one-way operations asynchronously, there is no + * need to perform a thread switch before calling the invoker. This method + * indicates whether the binding has this capability. + * + * @return true if the binding invoker is able to invoke one-way operations + * asynchronously, false if all invocations are synchronous + */ + boolean supportsOneWayInvocation(); +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/ReferenceBindingProviderRRB.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/ReferenceBindingProviderRRB.java new file mode 100644 index 0000000000..3ea9d0ac3c --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/ReferenceBindingProviderRRB.java @@ -0,0 +1,35 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.provider; + +import org.apache.tuscany.sca.runtime.RuntimeWire; + +/** + * TODO RRB experiment + * This is an experiment extension to try out the request response + * binding function + * + * @version $Rev$ $Date$ + */ +public interface ReferenceBindingProviderRRB extends ReferenceBindingProvider { + + void configureBindingChain(RuntimeWire runtimeWire); + +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/SCADefinitionsProvider.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/SCADefinitionsProvider.java new file mode 100644 index 0000000000..bd0f4d4b75 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/SCADefinitionsProvider.java @@ -0,0 +1,33 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.provider; + +import org.apache.tuscany.sca.definitions.SCADefinitions; + +/** + * Models a provider of SCA Definitions. Typically SCA Definitions providers + * may either load a definitions.xml file or create the SCA Definitions model + * programmatically. + * + * @version $Rev$ $Date$ + */ +public interface SCADefinitionsProvider { + SCADefinitions getSCADefinition() throws SCADefinitionsProviderException ; +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/SCADefinitionsProviderException.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/SCADefinitionsProviderException.java new file mode 100644 index 0000000000..b05130d6c8 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/SCADefinitionsProviderException.java @@ -0,0 +1,30 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.provider; + +/** + * @version $Rev$ $Date$ + */ +public class SCADefinitionsProviderException extends Exception { + + public SCADefinitionsProviderException(Throwable e) { + super(e); + } +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/SCADefinitionsProviderExtensionPoint.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/SCADefinitionsProviderExtensionPoint.java new file mode 100644 index 0000000000..a5d60cc6eb --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/SCADefinitionsProviderExtensionPoint.java @@ -0,0 +1,35 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.provider; + +import java.util.List; + +/** + * An extension point for SCA Definitions Providers. SCA Definition providers, load SCA Definitions + * items that are being specifically contributed by the module that hosts the provider in question. + * + * @version $Rev$ $Date$ + */ +public interface SCADefinitionsProviderExtensionPoint { + + void addSCADefinitionsProvider(SCADefinitionsProvider provider); + void removeSCADefinitionsProvider(SCADefinitionsProvider provider); + List<SCADefinitionsProvider> getSCADefinitionsProviders(); +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/ServiceBindingProvider.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/ServiceBindingProvider.java new file mode 100644 index 0000000000..e15234a549 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/ServiceBindingProvider.java @@ -0,0 +1,63 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.provider; + +import org.apache.tuscany.sca.interfacedef.InterfaceContract; + +/** + * A service binding can optionally implement this interface to tie + * into the Tuscany SCA runtime + * + * @version $Rev$ $Date$ + */ +public interface ServiceBindingProvider { + /** + * This method will be invoked when the component service binding is + * activated. + */ + void start(); + + /** + * This method will be invoked when the component service binding is + * deactivated. + */ + void stop(); + + /** + * Get the effective interface contract imposed by the binding. For example, + * it will be interface contract introspected from the WSDL portType used by + * the endpoint for a WebService binding. + * + * @return The effective interface contract, if null is returned, the + * interface contract for the component service will be used + */ + InterfaceContract getBindingInterfaceContract(); + + /** + * For bindings that invoke one-way callback operations asynchronously, + * there is no need to perform a thread switch before calling the invoker. + * This method indicates whether the binding has this capability. + * + * @return true if the callback invoker is able to invoke one-way operations + * asynchronously, false if all invocations are synchronous + */ + boolean supportsOneWayInvocation(); + +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/ServiceBindingProviderRRB.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/ServiceBindingProviderRRB.java new file mode 100644 index 0000000000..e23a37360a --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/ServiceBindingProviderRRB.java @@ -0,0 +1,39 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.provider; + +import java.util.List; + +import org.apache.tuscany.sca.interfacedef.InterfaceContract; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.runtime.RuntimeWire; + +/** + * TODO RRB experiment + * This is an experiment extension to try out the request response + * binding function + * + * @version $Rev$ $Date$ + */ +public interface ServiceBindingProviderRRB extends ServiceBindingProvider { + + void configureBindingChain(RuntimeWire runtimeWire); + +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/WireFormatProvider.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/WireFormatProvider.java new file mode 100644 index 0000000000..35526cb251 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/WireFormatProvider.java @@ -0,0 +1,54 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.provider; + +import org.apache.tuscany.sca.interfacedef.InterfaceContract; +import org.apache.tuscany.sca.invocation.Interceptor; + +/** + * @version $Rev$ $Date$ + */ +public interface WireFormatProvider { + + /** + * Set up the contract that describes the interface that + * is providing data to or accepting data from the + * wire format interceptor. The wire format's job + * is to translate between this interface contract and the + * format on the wire. The interface contract may be + * configured separately for request and response + * wire formats + * + * @return the wire format interface contract + */ + public InterfaceContract configureWireFormatInterfaceContract(InterfaceContract interfaceContract); + + /** + * Create an interceptor for the wire format + * @return An interceptor that realize the policySet + */ + Interceptor createInterceptor(); + + /** + * Get the phase that the interceptor should be added + * @return The phase that this interceptor belongs to + */ + String getPhase(); +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/WireFormatProviderFactory.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/WireFormatProviderFactory.java new file mode 100644 index 0000000000..fd748df6ca --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/provider/WireFormatProviderFactory.java @@ -0,0 +1,53 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.provider; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.assembly.WireFormat; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; + +/** + * @version $Rev$ $Date$ + */ +public interface WireFormatProviderFactory<M extends WireFormat> extends ProviderFactory<M> { + /** + * Create wire format provider for a given reference binding + * @param component + * @param reference + * @param binding + * @return + */ + WireFormatProvider createReferenceWireFormatProvider(RuntimeComponent component, + RuntimeComponentReference reference, + Binding binding); + + /** + * Create policy provider for a given service binding + * @param component + * @param service + * @param binding + * @return + */ + WireFormatProvider createServiceWireFormatProvider(RuntimeComponent component, + RuntimeComponentService service, + Binding binding); +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/runtime/DefaultWireProcessorExtensionPoint.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/runtime/DefaultWireProcessorExtensionPoint.java new file mode 100644 index 0000000000..851afee3c1 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/runtime/DefaultWireProcessorExtensionPoint.java @@ -0,0 +1,63 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.runtime; + +import java.util.ArrayList; +import java.util.List; + + +/** + * The default implementation of a <code>WireProcessorExtensionPoint</code> + * + * @version $Rev$ $Date$ + */ +public class DefaultWireProcessorExtensionPoint implements RuntimeWireProcessorExtensionPoint { + + /** + * The list of WireProcessors available to the runtime + */ + private final List<RuntimeWireProcessor> processors = new ArrayList<RuntimeWireProcessor>(); + + /** + * Registers a wire-processor in the runtime + * + * @param processor The processor to register + */ + public void addWireProcessor(RuntimeWireProcessor processor) { + processors.add(processor); + } + + /** + * De-registers a wire-processor in the runtime + * + * @param processor The processor to de-register + */ + public void removeWireProcessor(RuntimeWireProcessor processor) { + processors.remove(processor); + } + + /** + * Returns a list of registered wire-processors. + * + * @return The list of wire processors + */ + public List<RuntimeWireProcessor> getWireProcessors() { + return processors; + } +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/runtime/EndpointReference.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/runtime/EndpointReference.java new file mode 100644 index 0000000000..b6fafa5fb6 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/runtime/EndpointReference.java @@ -0,0 +1,93 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.runtime; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.assembly.Contract; +import org.apache.tuscany.sca.interfacedef.InterfaceContract; + +/** + * The endpoint reference for a component service or reference + * + * @version $Rev$ $Date$ + */ +public interface EndpointReference extends Cloneable { + /** + * Get the component for the endpoint + * @return The component, null of the EPR is for a non-SCA service + */ + RuntimeComponent getComponent(); + + /** + * Get the component service or reference for the endpoint + * @return The component service or reference, null if the EPR is for a non-SCA service + */ + Contract getContract(); + + /** + * Get the binding for the endpoint + * @return The binding + */ + Binding getBinding(); + + /** + * Get the interface contract for the endpoint + * @return The interface contract + */ + InterfaceContract getInterfaceContract(); + + /** + * Update the interface contract for the endpoint + * @param interfaceContract The updated interface contract + */ + void setInterfaceContract(InterfaceContract interfaceContract); + + /** + * Get the URI for this endpoint + * @return The URI of the endpoint + */ + String getURI(); + + /** + * Set the URI for this endpoint + * @param uri The new URI of the endpoint + */ + void setURI(String uri); + + /** + * Get the callback endpoint for this endpoint + * @return The callback endpoint for this endpoint + */ + EndpointReference getCallbackEndpoint(); + + /** + * Set the callback endpoint for this endpoint + * @param callbackEndpoint The new callback endpoint for this endpoint + */ + void setCallbackEndpoint(EndpointReference callbackEndpoint); + + Object clone() throws CloneNotSupportedException; + + void setReferenceParameters(ReferenceParameters parameters); + ReferenceParameters getReferenceParameters(); + + void mergeEndpoint(EndpointReference epr); + +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/runtime/ReferenceParameters.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/runtime/ReferenceParameters.java new file mode 100644 index 0000000000..0e19538aff --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/runtime/ReferenceParameters.java @@ -0,0 +1,69 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.runtime; + +/** + * Parameters for the EndPointReference + * + * @version $Rev$ $Date$ + */ +public interface ReferenceParameters extends Cloneable { + /** + * Get the callback ID + * @return the callbackID + */ + Object getCallbackID(); + + /** + * Set the callback ID + * @param callbackID the callbackID to set + */ + void setCallbackID(Object callbackID); + + /** + * Get the conversation ID + * @return the conversationID + */ + Object getConversationID(); + + /** + * Set the conversation ID + * @param conversationID the conversationID to set + */ + void setConversationID(Object conversationID); + + /** + * Get the ID for the non-ServiceReference callback object + * @return + */ + Object getCallbackObjectID(); + + /** + * Set the ID for the non-ServiceReference callback object + * @param callbackObjectID + */ + void setCallbackObjectID(Object callbackObjectID); + + EndpointReference getCallbackReference(); + + void setCallbackReference(EndpointReference callback); + + Object clone() throws CloneNotSupportedException; +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/runtime/RuntimeComponent.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/runtime/RuntimeComponent.java new file mode 100644 index 0000000000..30bba78a40 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/runtime/RuntimeComponent.java @@ -0,0 +1,83 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.runtime; + +import java.util.List; + +import org.apache.tuscany.sca.assembly.Component; +import org.apache.tuscany.sca.provider.ImplementationProvider; +import org.apache.tuscany.sca.provider.PolicyProvider; + +/** + * The runtime component interface. Provides the bridge between the + * assembly model representation of a component and its runtime + * realization. + * + * @version $Rev$ $Date$ + */ +public interface RuntimeComponent extends Component { + /** + * Set the implementation-specific configuration for this component + * @param implementationProvider The object that manages the component implementation + */ + void setImplementationProvider(ImplementationProvider implementationProvider); + + /** + * Get the implementation-specific configuration for this component + * @return The implementation provider for this component + */ + ImplementationProvider getImplementationProvider(); + + /** + * Get the associated component context + * @return + */ + RuntimeComponentContext getComponentContext(); + + /** + * Set the associated component context + * @param context + */ + void setComponentContext(RuntimeComponentContext context); + + /** + * Tests if the RuntimeComponent is started + * @return true if the RuntimeComponent is started otherwise false + */ + boolean isStarted(); + + /** + * Sets the RuntimeComponent started state + * @param started the state to set + */ + void setStarted(boolean started); + + /** + * Add a policy provider to the component + * @param policyProvider + */ + void addPolicyProvider(PolicyProvider policyProvider); + + /** + * Get a list of policy providers configured for this component + * @return + */ + List<PolicyProvider> getPolicyProviders(); +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/runtime/RuntimeComponentContext.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/runtime/RuntimeComponentContext.java new file mode 100644 index 0000000000..f61bff9735 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/runtime/RuntimeComponentContext.java @@ -0,0 +1,105 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.runtime; + +import java.io.IOException; +import java.io.Reader; +import java.io.Writer; + +import org.apache.tuscany.sca.api.ComponentContextExtension; +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.assembly.ComponentService; +import org.osoa.sca.CallableReference; +import org.osoa.sca.ComponentContext; +import org.osoa.sca.ServiceReference; + +/** + * @version $Rev$ $Date$ + */ +public interface RuntimeComponentContext extends ComponentContextExtension { + /** + * Activate the reference (creating runtime wires) + * @param reference + */ + void start(RuntimeComponentReference reference); + + /** + * Deserialize the component reference + * @param reader + * @return A component that contains the reference + * @throws IOException + */ + RuntimeComponent read(Reader reader) throws IOException; + + /** + * Serialize the component reference + * @param reference + * @param writer + * @throws IOException + */ + void write(RuntimeComponentReference reference, Writer writer) throws IOException; + + /** + * Get the CallableReference for a given component reference + * @param <B> + * @param businessInterface The business interface + * @param reference The reference to be wired + * @param binding The binding to be used, if it's null, either binding.sca or the 1st binding + * will be selected + * @return A service reference representing the wire + */ + <B> ServiceReference<B> getServiceReference(Class<B> businessInterface, + RuntimeComponentReference reference, + Binding binding); + + /** + * Bind the reference to a target component/componentService + * @param <B> + * @param businessInterface The business interface + * @param reference The reference to be wired + * @param component The target component + * @param service The target component service + * @return A service reference representing the wire + */ + <B> ServiceReference<B> getServiceReference(Class<B> businessInterface, + RuntimeComponentReference reference, + RuntimeComponent component, + RuntimeComponentService service); + + /** + * Create a CallableReference for the given component service + * @param <B> + * @param businessInterface + * @param component + * @param service + * @return + */ + <B> CallableReference<B> getCallableReference(Class<B> businessInterface, + RuntimeComponent component, + RuntimeComponentService service); + + /** + * @param <B> + * @param businessInterface + * @param service + * @return + */ + <B> ServiceReference<B> createSelfReference(Class<B> businessInterface, ComponentService service); +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/runtime/RuntimeComponentReference.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/runtime/RuntimeComponentReference.java new file mode 100644 index 0000000000..44ae7f552a --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/runtime/RuntimeComponentReference.java @@ -0,0 +1,119 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.runtime; + +import java.util.List; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.assembly.ComponentReference; +import org.apache.tuscany.sca.assembly.Endpoint; +import org.apache.tuscany.sca.endpointresolver.EndpointResolver; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.provider.PolicyProvider; +import org.apache.tuscany.sca.provider.ReferenceBindingProvider; + +/** + * The runtime component reference. Provides the bridge between the + * assembly model representation of a component reference and its runtime + * realization + * + * @version $Rev$ $Date$ + */ +public interface RuntimeComponentReference extends ComponentReference { + + /** + * Get a list of runtime wires to the reference + * + * @return The list of wires + */ + List<RuntimeWire> getRuntimeWires(); + + /** + * Get the runtime wire for the given binding + * @param binding The assembly model binding + * @return The runtime wire + */ + RuntimeWire getRuntimeWire(Binding binding); + + /** + * Returns the reference binding provider associated with this + * component reference and the given binding. + * + * @param binding The assembly model binding + * @return The runtime reference binding provider + */ + ReferenceBindingProvider getBindingProvider(Binding binding); + + /** + * Sets the reference binding provider associated with this + * component reference and the given binding. + * + * @param binding The assembly model binding + * @param bindingProvider The runtime reference binding provider + */ + void setBindingProvider(Binding binding, ReferenceBindingProvider bindingProvider); + + /** + * Returns the endpoint resolver associated with this + * component reference and the given endpoint. + * + * @param endpont The assembly model endpoint + * @return The enpoint resolver + */ + EndpointResolver getEndpointResolver(Endpoint endpoint); + + /** + * Sets the endpoint resolver associated with this + * component reference and the given endpoint. + * + * @param binding The assembly model binding + * @param bindingProvider The runtime reference binding provider + */ + void setEndpointResolver(Endpoint endpoint, EndpointResolver endpointResolver); + + /** + * Add a policy provider for the given binding to the reference + * @param binding The assembly model binding + * @param policyProvider The policy handler + */ + void addPolicyProvider(Binding binding, PolicyProvider policyProvider); + + /** + * Get a list of policy providers for the given binding + * @param binding The assembly model binding + * @return A list of policy providers for the given binding + */ + List<PolicyProvider> getPolicyProviders(Binding binding); + + /** + * Get the invoker for the given binding and operation + * @param binding The assembly model binding + * @param operation The assembly model operation + * @return The runtime Invoker + */ + Invoker getInvoker(Binding binding, Operation operation); + + /** + * Set the owning component + * @param component + */ + void setComponent(RuntimeComponent component); +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/runtime/RuntimeComponentService.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/runtime/RuntimeComponentService.java new file mode 100644 index 0000000000..982724d798 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/runtime/RuntimeComponentService.java @@ -0,0 +1,138 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.runtime; + +import java.util.List; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.assembly.ComponentService; +import org.apache.tuscany.sca.interfacedef.InterfaceContract; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.InvocationChain; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.provider.PolicyProvider; +import org.apache.tuscany.sca.provider.ServiceBindingProvider; + +/** + * The runtime component service. Provides the bridge between the + * assembly model representation of a component service and its runtime + * realization + * + * @version $Rev$ $Date$ + */ +public interface RuntimeComponentService extends ComponentService { + + /** + * Get a list of runtime wires to the service + * + * @return The list of wires + */ + List<RuntimeWire> getRuntimeWires(); + /** + * Get the runtime wire for the given binding + * @param binding The assembly model binding + * @return The runtime wire + */ + RuntimeWire getRuntimeWire(Binding binding); + + /** + * Get the callback wires associated with this service + * + * @return The list of runtime callback wires + */ + List<RuntimeWire> getCallbackWires(); + + /** + * Returns the service binding provider associated with this + * component service and the given binding. + * + * @param binding The assembly model binding + * @return The runtime service binding provider + */ + ServiceBindingProvider getBindingProvider(Binding binding); + + /** + * Returns the service binding provider associated with this + * component service and the given binding. + * + * @param binding + * @param interfaceContract + * @return + */ + RuntimeWire getRuntimeWire(Binding binding, InterfaceContract interfaceContract); + + /** + * Sets the service binding provider associated with this + * component service and the given binding. + * + * @param binding The assembly model binding + * @param bindingProvider The runtime service binding provider + */ + void setBindingProvider(Binding binding, ServiceBindingProvider bindingProvider); + + /** + * Get the invoker for the given binding and operation + * @param binding The assembly model binding + * @param operation The assembly model operation + * @return The runtime invoker + */ + Invoker getInvoker(Binding binding, Operation operation); + + /** + * Get the invoker for the given binding and operation + * @param binding The assembly model binding + * @param interfaceContract the client interface contract + * @param operation The assembly model operation + * @return The runtime invoker + */ + Invoker getInvoker(Binding binding, InterfaceContract interfaceContract, Operation operation); + + /** + * Get the invocation chain for the given binding and operation + * @param binding The assembly model binding + * @param operation The assembly model operation + * @return The runtime invocation chain + */ + InvocationChain getInvocationChain(Binding binding, Operation operation); + + /** + * Get the invocation chain for the given binding and operation + * @param binding The assembly model binding + * @param operation The assembly model operation + * @param interfaceContract the client interface contract + * @return The runtime invocation chain + */ + InvocationChain getInvocationChain(Binding binding, InterfaceContract interfaceContract, Operation operation); + + /** + * Add a policy provider for the given binding to the service + * @param binding The assembly model binding + * @param policyProvider The policy handler + */ + void addPolicyProvider(Binding binding, PolicyProvider policyProvider); + + /** + * Get a list of policy providers for the given binding + * @param binding The assembly model binding + * @return A list of policy providers for the given binding + */ + List<PolicyProvider> getPolicyProviders(Binding binding); + +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/runtime/RuntimeWire.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/runtime/RuntimeWire.java new file mode 100644 index 0000000000..a2e7152202 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/runtime/RuntimeWire.java @@ -0,0 +1,117 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.runtime; + +import java.lang.reflect.InvocationTargetException; +import java.util.List; + +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.InvocationChain; +import org.apache.tuscany.sca.invocation.Message; + +/** + * The runtime wire interface that connects a component reference to a + * component service (or an external service) over the selected binding + * + * @version $Rev$ $Date$ + */ +public interface RuntimeWire extends Cloneable { + + /** + * Get the source of the wire + * + * @return The end point reference of the source + */ + EndpointReference getSource(); + + /** + * Get the target of the wire + * + * @return The end point reference of the target + */ + EndpointReference getTarget(); + + /** + * Rebind the runtime wire with the given target + * @param target The target endpoint reference + */ + void setTarget(EndpointReference target); + + /** + * Force the invocation chains to be rebuilt + */ + void rebuild(); + + /** + * Returns the invocation chains for service operations associated with the + * wire + * + * @return the invocation chains for service operations associated with the + * wire + */ + List<InvocationChain> getInvocationChains(); + + /** + * Lookup the invocation chain by operation + * @param operation The operation + * @return The invocation chain for the given operation + */ + InvocationChain getInvocationChain(Operation operation); + + /** + * Get the invocation chain for the binding-specific handling + * @return + */ + InvocationChain getBindingInvocationChain(); + + /** + * This invoke method assumes that the binding invocation chain is in force + * and that there will be an operation selector element there to + * determine which operation to call + * @param msg The message + * @return The result + * @throws InvocationTargetException + */ + Object invoke(Message msg) throws InvocationTargetException; + + /** + * Invoke an operation with given arguments + * @param operation The operation + * @param args The arguments + * @return The result + * @throws InvocationTargetException + */ + Object invoke(Operation operation, Object[] args) throws InvocationTargetException; + + /** + * Invoke an operation with a context message + * @param operation The operation + * @param msg The message + * @return The result + * @throws InvocationTargetException + */ + Object invoke(Operation operation, Message msg) throws InvocationTargetException; + + /** + * @return a clone of the runtime wire + * @throws CloneNotSupportedException + */ + Object clone() throws CloneNotSupportedException; +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/runtime/RuntimeWireProcessor.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/runtime/RuntimeWireProcessor.java new file mode 100644 index 0000000000..fbb7aae467 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/runtime/RuntimeWireProcessor.java @@ -0,0 +1,35 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.runtime; + +/** + * Implementations are called after wires are decorated with policy and before they are connected. + * + * @version $Rev$ $Date$ + */ +public interface RuntimeWireProcessor { + + /** + * Process the runtime wire to add interceptors + * + * @param wire + */ + void process(RuntimeWire wire); + +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/runtime/RuntimeWireProcessorExtensionPoint.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/runtime/RuntimeWireProcessorExtensionPoint.java new file mode 100644 index 0000000000..4b2c71b397 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/runtime/RuntimeWireProcessorExtensionPoint.java @@ -0,0 +1,53 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.runtime; + +import java.util.List; + +/** + * Acts as a delegating <code>WireProcessorExtensionPoint</code>, delegating + * processing of wires after policies have been applied and source and targets + * have been connected. + * + * @version $Rev$ $Date$ + */ +public interface RuntimeWireProcessorExtensionPoint { + + /** + * Registers a wire-processor in the runtime + * + * @param processor The processor to register + */ + void addWireProcessor(RuntimeWireProcessor processor); + + /** + * De-registers a wire-processor in the runtime + * + * @param processor The processor to de-register + */ + void removeWireProcessor(RuntimeWireProcessor processor); + + /** + * Returns a list of registered wire-processors. + * + * @return The list of wire processors + */ + List<RuntimeWireProcessor> getWireProcessors(); + +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/store/DuplicateRecordException.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/store/DuplicateRecordException.java new file mode 100644 index 0000000000..7d5cd6c54b --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/store/DuplicateRecordException.java @@ -0,0 +1,56 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.store; + +/** + * thrown when a record already exists during an insert operation + * + * @version $Rev$ $Date$ + */ +public class DuplicateRecordException extends StoreWriteException { + private static final long serialVersionUID = 3116253222569378447L; + + /** + * {@inheritDoc} + */ + public DuplicateRecordException() { + super(); + } + + /** + * {@inheritDoc} + */ + public DuplicateRecordException(String message, Throwable cause) { + super(message, cause); + } + + /** + * {@inheritDoc} + */ + public DuplicateRecordException(String message) { + super(message); + } + + /** + * {@inheritDoc} + */ + public DuplicateRecordException(Throwable cause) { + super(cause); + } +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/store/RecoveryListener.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/store/RecoveryListener.java new file mode 100644 index 0000000000..9d965a3369 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/store/RecoveryListener.java @@ -0,0 +1,46 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.store; + +import java.util.UUID; + +/** + * Implementations receive callback events during a store recovery operation + * + * @version $Rev$ $Date$ + */ +public interface RecoveryListener { + + /** + * Signals the start of a recovery + */ + void onBegin(); + + /** + * Received when a record is recovered + * + * @param id + */ + void onRecord(UUID id); + + /** + * Signals the end of recovery + */ + void onEnd(); +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/store/Store.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/store/Store.java new file mode 100644 index 0000000000..b15cde066a --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/store/Store.java @@ -0,0 +1,96 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.store; + +import org.apache.tuscany.sca.event.EventPublisher; +import org.apache.tuscany.sca.runtime.RuntimeComponent; + +/** + * Implementations provide a persistent store for runtime data such as conversational state. A persistent store could be + * implemented in a durable fashion using JDBC or a journaling system, or using a non-durable mechanism such as an + * in-memory map. + * + * @version $Rev$ $Date$ + */ +public interface Store extends EventPublisher { + + /* Used to indicate an the default expiration offset for records for the store */ + long DEFAULT_EXPIRATION_OFFSET = -1; + + /* Used to indicate an entry should not expire */ + long NEVER = -2; + + /** + * Adds the given record to the store. Implementations may choose different strategies for writing data such as + * write-through or write-behind. + * + * @param owner the instance owner + * @param id the unique id of the record + * @param object the object representing the data to write + * @param expiration the time in milliseconds when the entry expires + * @throws StoreWriteException if an error occurs during the write operation + */ + void insertRecord(RuntimeComponent owner, String id, Object object, long expiration) throws StoreWriteException; + + /** + * Updates a given record in the store, overwriting previous information. + * + * @param owner the instance owner + * @param id the unique id of the record + * @param object the object representing the data to write + * @param expiration the time in milliseconds when the entry expires + * @throws StoreWriteException + */ + void updateRecord(RuntimeComponent owner, String id, Object object, long expiration) throws StoreWriteException; + + /** + * Returns the deserialized object in the store corresponding to the given id + * + * @param owner the instance owner + * @param id the unique id of the record + * @return the deserialized object or null if one is not found + * @throws StoreReadException + */ + Object readRecord(RuntimeComponent owner, String id) throws StoreReadException; + + /** + * Removes a record from the store + * + * @param owner the instance owner + * @param id the unique id of the record + * @throws StoreWriteException + */ + void removeRecord(RuntimeComponent owner, String id) throws StoreWriteException; + + /** + * Removes all records from the store + * + * @throws StoreWriteException + */ + void removeRecords() throws StoreWriteException; + + /** + * Initiates a recovery operation, for example during restart after a crash + * + * @param listener the listener to receive recovery callback events + * @throws StoreReadException + */ + void recover(RecoveryListener listener) throws StoreReadException; + +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/store/StoreException.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/store/StoreException.java new file mode 100644 index 0000000000..24eaddd3e0 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/store/StoreException.java @@ -0,0 +1,57 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.store; + + +/** + * Represents a generic exception thrown by a <code>Store</code> + * + * @version $Rev$ $Date$ + */ +public class StoreException extends Exception { + private static final long serialVersionUID = -319152147419962709L; + + /** + * {@inheritDoc} + */ + public StoreException() { + super(); + } + + /** + * {@inheritDoc} + */ + public StoreException(String message, Throwable cause) { + super(message, cause); + } + + /** + * {@inheritDoc} + */ + public StoreException(String message) { + super(message); + } + + /** + * {@inheritDoc} + */ + public StoreException(Throwable cause) { + super(cause); + } +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/store/StoreExpirationEvent.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/store/StoreExpirationEvent.java new file mode 100644 index 0000000000..5c1a3ca79d --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/store/StoreExpirationEvent.java @@ -0,0 +1,71 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.store; + +import org.apache.tuscany.sca.event.Event; +import org.apache.tuscany.sca.runtime.RuntimeComponent; + +/** + * Fired when a store implementation expires a resource + * + * @version $Rev$ $Date$ + */ +public class StoreExpirationEvent implements Event { + private Object source; + private RuntimeComponent owner; + private Object instance; + + /** + * Constructor. + * + * @param source the source of the event + * @param owner the owner of the expiring object + * @param instance the expiring object + */ + public StoreExpirationEvent(Object source, RuntimeComponent owner, Object instance) { + assert source != null; + assert owner != null; + assert instance != null; + this.source = source; + this.owner = owner; + this.instance = instance; + } + + public Object getSource() { + return source; + } + + /** + * Returns the owner of the expiring object. + * + * @return the owner of the expiring object. + */ + public RuntimeComponent getOwner() { + return owner; + } + + /** + * Returns the expiring object. + * + * @return the expiring object. + */ + public Object getInstance() { + return instance; + } +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/store/StoreMonitor.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/store/StoreMonitor.java new file mode 100644 index 0000000000..4bc7facf39 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/store/StoreMonitor.java @@ -0,0 +1,71 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.store; + + +/** + * A generic monitor interface for services to log events + * + * @version $Rev$ $Date$ + */ +public interface StoreMonitor { + + /** + * Signals the service has started + * + * @param msg + */ + void start(String msg); + + /** + * Signals the service has been shutdown + * + * @param msg + */ + void stop(String msg); + + /** + * Fired when recovery is started + */ + + void beginRecover(); + + /** + * Fired when recovery is completed + */ + + void endRecover(); + + /** + * Fired when a record is processed during recovery + * + * @param recordId the id of the record being recovered + */ + + void recover(Object recordId); + + /** + * Signals an error event + * + * @param e the error + */ + + void error(Throwable e); + +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/store/StoreReadException.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/store/StoreReadException.java new file mode 100644 index 0000000000..c2346bddca --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/store/StoreReadException.java @@ -0,0 +1,56 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.store; + +/** + * Thrown when an error occurs reading from persistent storage + * + * @version $Rev$ $Date$ + */ +public class StoreReadException extends StoreException { + private static final long serialVersionUID = -8624542082121467271L; + + /** + * {@inheritDoc} + */ + public StoreReadException() { + super(); + } + + /** + * {@inheritDoc} + */ + public StoreReadException(String message, Throwable cause) { + super(message, cause); + } + + /** + * {@inheritDoc} + */ + public StoreReadException(String message) { + super(message); + } + + /** + * {@inheritDoc} + */ + public StoreReadException(Throwable cause) { + super(cause); + } +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/store/StoreWriteException.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/store/StoreWriteException.java new file mode 100644 index 0000000000..b37519b31c --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/store/StoreWriteException.java @@ -0,0 +1,56 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.store; + +/** + * Thrown when an error occurs writing to persistent storage + * + * @version $Rev$ $Date$ + */ +public class StoreWriteException extends StoreException { + private static final long serialVersionUID = 5539070473942048555L; + + /** + * {@inheritDoc} + */ + public StoreWriteException() { + super(); + } + + /** + * {@inheritDoc} + */ + public StoreWriteException(String message, Throwable cause) { + super(message, cause); + } + + /** + * {@inheritDoc} + */ + public StoreWriteException(String message) { + super(message); + } + + /** + * {@inheritDoc} + */ + public StoreWriteException(Throwable cause) { + super(cause); + } +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/work/NotificationListener.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/work/NotificationListener.java new file mode 100644 index 0000000000..d32af450ff --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/work/NotificationListener.java @@ -0,0 +1,67 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.work; + +/** + * A callback interface that can be optionally used for registering + * interest in status of asynchronously scheduled unit of work. + * + * @version $Rev$ $Date$ + */ +public interface NotificationListener<T extends Runnable> { + + /** + * Callback method when the unit of work is accepted. + * + * @param work Work that was accepted. + */ + void workAccepted(T work); + + /** + * Callback method when the unit of work is successfully completed. + * + * @param work Work that was successfully completed. + */ + void workCompleted(T work); + + /** + * Callback when the unit of work is started. + * + * @param work Unit of work that was started. + */ + void workStarted(T work); + + /** + * Callback when the unit of work is rejected. + * + * @param work Unit of work that was rejected. + */ + void workRejected(T work); + + /** + * Callback when the unit of work fails to complete. + * + * @param work Unit of work that failed to complete. + * @param error Error that caused the unit of work to fail. + */ + void workFailed(T work, Throwable error); + + + +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/work/WorkScheduler.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/work/WorkScheduler.java new file mode 100644 index 0000000000..b1beac78e2 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/work/WorkScheduler.java @@ -0,0 +1,58 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.work; + +/** + * Defines the contract for scheduling asynchronous units of work. + * + * <p> + * Units of work can be scheduled with an optional <code>NotificationListener</code>. + * If a notification listener is specified, the caller will be notified regarding the + * status of the work. The unit of work can either be completed, rejected or completed + * with an error. If the work completed with an error, the caller is notified with the + * error details. + * </p> + * + * @version $Rev$ $Date$ + */ +public interface WorkScheduler { + + /** + * Schedules a unit of work for future execution. The notification listener + * is used to register interest in callbacks regarding the status of the work. + * + * @param work The unit of work that needs to be asynchronously executed. + * @param listener Notification listener for callbacks. + */ + <T extends Runnable>void scheduleWork(T work, NotificationListener<T> listener); + + /** + * Schedules a unit of work for future execution. The notification listener + * is used to register interest in callbacks regarding the status of the work. + * + * @param work The unit of work that needs to be asynchronously executed. + */ + <T extends Runnable>void scheduleWork(T work); + + /** + * Destroys the work scheduler + */ + void destroy(); + +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/work/WorkSchedulerException.java b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/work/WorkSchedulerException.java new file mode 100644 index 0000000000..18ec2dfeaa --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/java/org/apache/tuscany/sca/work/WorkSchedulerException.java @@ -0,0 +1,59 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.work; + + +/** + * Exception thrown by the work scheduler in case of unexpected exceptions. + * + * @version $Rev$ $Date$ + * + * @version $Rev$ $Date$ + */ +public class WorkSchedulerException extends RuntimeException { + private static final long serialVersionUID = 1L; + + /** + * {@inheritDoc} + */ + public WorkSchedulerException() { + super(); + } + + /** + * {@inheritDoc} + */ + public WorkSchedulerException(String message, Throwable cause) { + super(message, cause); + } + + /** + * {@inheritDoc} + */ + public WorkSchedulerException(String message) { + super(message); + } + + /** + * {@inheritDoc} + */ + public WorkSchedulerException(Throwable cause) { + super(cause); + } +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/resources/META-INF/services/org.apache.tuscany.sca.context.ContextFactoryExtensionPoint b/branches/sca-java-1.5.1/modules/core-spi/src/main/resources/META-INF/services/org.apache.tuscany.sca.context.ContextFactoryExtensionPoint new file mode 100644 index 0000000000..ddd91bceac --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/resources/META-INF/services/org.apache.tuscany.sca.context.ContextFactoryExtensionPoint @@ -0,0 +1,18 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +org.apache.tuscany.sca.context.DefaultContextFactoryExtensionPoint diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/resources/META-INF/services/org.apache.tuscany.sca.endpointresolver.EndpointResolverFactoryExtensionPoint b/branches/sca-java-1.5.1/modules/core-spi/src/main/resources/META-INF/services/org.apache.tuscany.sca.endpointresolver.EndpointResolverFactoryExtensionPoint new file mode 100644 index 0000000000..91839e998f --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/resources/META-INF/services/org.apache.tuscany.sca.endpointresolver.EndpointResolverFactoryExtensionPoint @@ -0,0 +1,18 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +org.apache.tuscany.sca.endpointresolver.DefaultEndpointResolverFactoryExtensionPoint diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.ProviderFactoryExtensionPoint b/branches/sca-java-1.5.1/modules/core-spi/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.ProviderFactoryExtensionPoint new file mode 100644 index 0000000000..e9de1f135f --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.ProviderFactoryExtensionPoint @@ -0,0 +1,18 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +org.apache.tuscany.sca.provider.DefaultProviderFactoryExtensionPoint diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.SCADefinitionsProviderExtensionPoint b/branches/sca-java-1.5.1/modules/core-spi/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.SCADefinitionsProviderExtensionPoint new file mode 100644 index 0000000000..2f700671ca --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.SCADefinitionsProviderExtensionPoint @@ -0,0 +1,19 @@ +# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+org.apache.tuscany.sca.provider.DefaultSCADefinitionsProviderExtensionPoint
+
\ No newline at end of file diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/main/resources/META-INF/services/org.apache.tuscany.sca.runtime.RuntimeWireProcessorExtensionPoint b/branches/sca-java-1.5.1/modules/core-spi/src/main/resources/META-INF/services/org.apache.tuscany.sca.runtime.RuntimeWireProcessorExtensionPoint new file mode 100644 index 0000000000..95591dca5d --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/main/resources/META-INF/services/org.apache.tuscany.sca.runtime.RuntimeWireProcessorExtensionPoint @@ -0,0 +1,18 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +org.apache.tuscany.sca.runtime.DefaultWireProcessorExtensionPoint diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/test/java/org/apache/tuscany/sca/context/DefaultContextFactoryExtensionPointTestCase.java b/branches/sca-java-1.5.1/modules/core-spi/src/test/java/org/apache/tuscany/sca/context/DefaultContextFactoryExtensionPointTestCase.java new file mode 100644 index 0000000000..3a27569a3b --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/test/java/org/apache/tuscany/sca/context/DefaultContextFactoryExtensionPointTestCase.java @@ -0,0 +1,208 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.context; + +import org.apache.tuscany.sca.core.DefaultExtensionPointRegistry; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; + +import org.junit.Assert; +import org.junit.Test; + +/** + * This test case will test the class + * org.apache.tuscany.sca.context.DefaultContextFactoryExtensionPoint + * + * $Date$ $Rev$ + */ +public class DefaultContextFactoryExtensionPointTestCase { + + /** + * Tests adding/getting/removing a factory with no interfaces + */ + @Test + public void testFactoryWithNoInterfaces() { + Object factory = new FactoryWithNoInterfaces(); + Class<?>[] ifaces = {}; + addGetRemoveFactory(factory, ifaces); + } + + /** + * Tests adding/getting/removing a factory with one interface + */ + @Test + public void testFactoryWithOneInterface() { + Object factory = new FactoryWithOneInterface(); + Class<?>[] ifaces = { FactoryOneInterface.class }; + addGetRemoveFactory(factory, ifaces); + } + + /** + * Tests adding/getting/removing a factory with two interfaces + */ + @Test + public void testFactoryWithTwoInterfaces() { + Object factory = new FactoryWithTwoInterfaces(); + Class<?>[] ifaces = { FactoryTwoInterfacesA.class, FactoryTwoInterfacesB.class }; + addGetRemoveFactory(factory, ifaces); + } + + /** + * Tests having multiple factories registered + */ + @Test + public void testMultipleFactories() { + // Create new factories + FactoryWithOneInterface factory1 = new FactoryWithOneInterface(); + FactoryWithTwoInterfaces factory2 = new FactoryWithTwoInterfaces(); + + ExtensionPointRegistry registry = new DefaultExtensionPointRegistry(); + + // Register the factories + DefaultContextFactoryExtensionPoint ctxFactory = new DefaultContextFactoryExtensionPoint(registry); + ctxFactory.addFactory(factory1); + ctxFactory.addFactory(factory2); + + // Re-get each of the factories + FactoryOneInterface regotFactory1 = ctxFactory.getFactory(FactoryOneInterface.class); + Assert.assertNotNull(regotFactory1); + Assert.assertSame(factory1, regotFactory1); + FactoryTwoInterfacesA regotFactory2A = ctxFactory.getFactory(FactoryTwoInterfacesA.class); + Assert.assertNotNull(regotFactory2A); + Assert.assertSame(factory2, regotFactory2A); + FactoryTwoInterfacesB regotFactory2B = ctxFactory.getFactory(FactoryTwoInterfacesB.class); + Assert.assertNotNull(regotFactory1); + Assert.assertSame(factory2, regotFactory2B); + } + + /** + * Tests passing in null to addFactory() + */ + @Test + public void testAddingNullFactory() { + + ExtensionPointRegistry registry = new DefaultExtensionPointRegistry(); + DefaultContextFactoryExtensionPoint ctxFactory = new DefaultContextFactoryExtensionPoint(registry); + try { + ctxFactory.addFactory(null); + Assert.fail("Should have thrown IllegalArgumentException"); + } catch (IllegalArgumentException ex) { + // As expected + } + } + + /** + * Test passing in null to removeFactory() + */ + @Test + public void testRemovingNullFactory() { + ExtensionPointRegistry registry = new DefaultExtensionPointRegistry(); + DefaultContextFactoryExtensionPoint ctxFactory = new DefaultContextFactoryExtensionPoint(registry); + try { + ctxFactory.removeFactory(null); + Assert.fail("Should have thrown IllegalArgumentException"); + } catch (IllegalArgumentException ex) { + // As expected + } + } + + /** + * Test passing in null to getFactory() + */ + @Test + public void testGetNullFactory() { + ExtensionPointRegistry registry = new DefaultExtensionPointRegistry(); + DefaultContextFactoryExtensionPoint ctxFactory = new DefaultContextFactoryExtensionPoint(registry); + try { + ctxFactory.getFactory(null); + Assert.fail("Should have thrown IllegalArgumentException"); + } catch (IllegalArgumentException ex) { + // As expected + } + } + + /** + * Utility method for testing adding and removing a factory + * + * @param factory The factory class to test + * @param factoryInterfaces The list of interfaces implemented by the factory + */ + private void addGetRemoveFactory(Object factory, Class<?>[] factoryInterfaces) { + ExtensionPointRegistry registry = new DefaultExtensionPointRegistry(); + DefaultContextFactoryExtensionPoint ctxFactory = new DefaultContextFactoryExtensionPoint(registry); + + // Make sure factory not already present + for (Class<?> iface : factoryInterfaces) { + Assert.assertNull(ctxFactory.getFactory(iface)); + } + + // Add the factory + ctxFactory.addFactory(factory); + + // Make sure we can get the factory recently registered factory + for (Class<?> iface : factoryInterfaces) { + Object regot = ctxFactory.getFactory(iface); + Assert.assertNotNull(regot); + Assert.assertSame(factory, regot); + } + + // Remove the factory + ctxFactory.removeFactory(factory); + + // Make sure factory is no longer registered + for (Class<?> iface : factoryInterfaces) { + Assert.assertNull(ctxFactory.getFactory(iface)); + } + } + + /** + * Simple factory with no interfaces + */ + private class FactoryWithNoInterfaces { + } + + /** + * Simple interface for the factory with one interface + */ + private interface FactoryOneInterface { + } + + /** + * Simple factory with one interface + */ + private class FactoryWithOneInterface implements FactoryOneInterface { + } + + /** + * Simple interface for the factory with two interfaces + */ + private interface FactoryTwoInterfacesA { + } + + /** + * Simple interface for the factory with two interfaces + */ + private interface FactoryTwoInterfacesB { + } + + /** + * Simple factory with two interfaces + */ + private class FactoryWithTwoInterfaces implements FactoryTwoInterfacesA, FactoryTwoInterfacesB { + } +} diff --git a/branches/sca-java-1.5.1/modules/core-spi/src/test/java/org/apache/tuscany/sca/event/TrueFilterTestCase.java b/branches/sca-java-1.5.1/modules/core-spi/src/test/java/org/apache/tuscany/sca/event/TrueFilterTestCase.java new file mode 100644 index 0000000000..2425133273 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core-spi/src/test/java/org/apache/tuscany/sca/event/TrueFilterTestCase.java @@ -0,0 +1,63 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.event; + +import org.junit.Assert; +import org.junit.Test; + +/** + * Test case for TrueFilter + * + * @version $Rev$ $Date$ + */ +public class TrueFilterTestCase { + + /** + * Test TrueFilter matching an event + */ + @Test + public void testTrueFilterMatch() { + EventFilter filter = new TrueFilter(); + + Assert.assertTrue(filter.match(new DummyEvent())); + } + + /** + * Test TrueFilter matching null + */ + @Test + public void testTrueFilterMatchNull() { + EventFilter filter = new TrueFilter(); + + Assert.assertTrue(filter.match(null)); + } + + /** + * Dummy Event implementation for testing + */ + private class DummyEvent implements Event { + + /** + * {@inheritDoc} + */ + public Object getSource() { + throw new UnsupportedOperationException(); + } + } +} diff --git a/branches/sca-java-1.5.1/modules/core/LICENSE b/branches/sca-java-1.5.1/modules/core/LICENSE new file mode 100644 index 0000000000..8aa906c321 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/LICENSE @@ -0,0 +1,205 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + diff --git a/branches/sca-java-1.5.1/modules/core/NOTICE b/branches/sca-java-1.5.1/modules/core/NOTICE new file mode 100644 index 0000000000..fdfa0e9faa --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2008 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/branches/sca-java-1.5.1/modules/core/pom.xml b/branches/sca-java-1.5.1/modules/core/pom.xml new file mode 100644 index 0000000000..de5e7f42d4 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/pom.xml @@ -0,0 +1,114 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. +--> +<project> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>org.apache.tuscany.sca</groupId> + <artifactId>tuscany-modules</artifactId> + <version>1.6-SNAPSHOT</version> + <relativePath>../pom.xml</relativePath> + </parent> + <artifactId>tuscany-core</artifactId> + <name>Apache Tuscany SCA Core Runtime</name> + + <dependencies> + <dependency> + <groupId>org.apache.tuscany.sca</groupId> + <artifactId>tuscany-extensibility</artifactId> + <version>1.6-SNAPSHOT</version> + </dependency> + + <dependency> + <groupId>org.apache.tuscany.sca</groupId> + <artifactId>tuscany-core-spi</artifactId> + <version>1.6-SNAPSHOT</version> + </dependency> + + <dependency> + <groupId>org.apache.tuscany.sca</groupId> + <artifactId>tuscany-contribution</artifactId> + <version>1.6-SNAPSHOT</version> + </dependency> + + <dependency> + <groupId>org.apache.tuscany.sca</groupId> + <artifactId>tuscany-contribution-java</artifactId> + <version>1.6-SNAPSHOT</version> + </dependency> + + <dependency> + <groupId>org.apache.tuscany.sca</groupId> + <artifactId>tuscany-interface-java</artifactId> + <version>1.6-SNAPSHOT</version> + </dependency> + + <dependency> + <groupId>org.codehaus.woodstox</groupId> + <artifactId>wstx-asl</artifactId> + <version>3.2.4</version> + <scope>runtime</scope> + <exclusions> + <exclusion> + <groupId>stax</groupId> + <artifactId>stax-api</artifactId> + </exclusion> + </exclusions> + </dependency> + + <dependency> + <groupId>cglib</groupId> + <artifactId>cglib-nodep</artifactId> + <version>2.2</version> + </dependency> + + <dependency> + <groupId>javax.xml.ws</groupId> + <artifactId>jaxws-api</artifactId> + <version>2.1</version> + <exclusions> + <exclusion> + <groupId>javax.xml.soap</groupId> + <artifactId>saaj-api</artifactId> + </exclusion> + </exclusions> + </dependency> + + </dependencies> + + + <build> + <plugins> + <plugin> + <groupId>org.apache.felix</groupId> + <artifactId>maven-bundle-plugin</artifactId> + + <configuration> + <instructions> + <Bundle-Version>${tuscany.version}</Bundle-Version> + <Bundle-SymbolicName>org.apache.tuscany.sca.core</Bundle-SymbolicName> + <Bundle-Description>${pom.name}</Bundle-Description> + <Export-Package>org.apache.tuscany.sca.core*</Export-Package> + </instructions> + </configuration> + </plugin> + </plugins> + </build> + +</project> diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/assembly/ActivationException.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/assembly/ActivationException.java new file mode 100644 index 0000000000..c86c876075 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/assembly/ActivationException.java @@ -0,0 +1,37 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.assembly; + + +/** + * Denotes an error starting the runtime + * + * @version $Rev$ $Date$ + */ +public class ActivationException extends Exception { + private static final long serialVersionUID = 8612661660934426123L; + + public ActivationException(String message) { + super(message); + } + + public ActivationException(Throwable cause) { + super(cause); + } +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/assembly/CompositeActivator.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/assembly/CompositeActivator.java new file mode 100644 index 0000000000..29dcc20f0b --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/assembly/CompositeActivator.java @@ -0,0 +1,154 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core.assembly; + +import org.apache.tuscany.sca.assembly.Component; +import org.apache.tuscany.sca.assembly.Composite; +import org.apache.tuscany.sca.core.context.ComponentContextHelper; +import org.apache.tuscany.sca.core.conversation.ConversationManager; +import org.apache.tuscany.sca.core.invocation.ProxyFactory; +import org.apache.tuscany.sca.interfacedef.java.JavaInterfaceFactory; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; + +/** + * Start/stop a composite + * + * @version $Rev$ $Date$ + */ +public interface CompositeActivator { + /** + * Activate a composite + * @param composite + */ + void activate(Composite composite) throws ActivationException; + + /** + * Activate a component reference + * @param component + * @param ref + */ + void start(RuntimeComponent component, RuntimeComponentReference ref); + + /** + * Activate a component reference + * @param component + * @param ref + */ + void activate(RuntimeComponent component, RuntimeComponentReference ref); + + /** + * Activate a component reference + * @param component + * @param ref + */ + void activate(RuntimeComponent component, RuntimeComponentService service); + + /** + * De-activate a component reference + * @param component + * @param ref + */ + void deactivate(RuntimeComponent component, RuntimeComponentReference ref); + + /** + * De-activate a component reference + * @param component + * @param ref + */ + void deactivate(RuntimeComponent component, RuntimeComponentService service); + + /** + * Stop a composite + * @param composite + */ + void deactivate(Composite composite) throws ActivationException; + + /** + * Start a component + * @param component + */ + void start(Component component) throws ActivationException; + + /** + * Stop a component + * @param component + */ + void stop(Component component) throws ActivationException; + + /** + * Start components in a composite + * @param composite + */ + void start(Composite composite) throws ActivationException; + + /** + * Stop components in a composite + * @param composite + */ + void stop(Composite composite) throws ActivationException; + + /** + * Get the component context helper + * @return + */ + ComponentContextHelper getComponentContextHelper(); + + /** + * Get the proxy factory + * @return + */ + ProxyFactory getProxyFactory(); + + /** + * Get the java interface factory + * @return + */ + JavaInterfaceFactory getJavaInterfaceFactory(); + + ConversationManager getConversationManager(); + + /** + * Configure the runtime component with component context + * @param component + */ + void configureComponentContext(RuntimeComponent component); + + /** + * Resolve a component by URI in the domain + * @param componentURI + * @return + */ + Component resolve(String componentURI); + + /** + * Set the domain composite + * @param domainComposite + */ + void setDomainComposite(Composite domainComposite); + + /** + * Get the domain composite + * @return + */ + Composite getDomainComposite(); + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/assembly/CompositeActivatorImpl.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/assembly/CompositeActivatorImpl.java new file mode 100644 index 0000000000..f51931c53b --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/assembly/CompositeActivatorImpl.java @@ -0,0 +1,1101 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core.assembly; + +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.apache.tuscany.sca.assembly.AssemblyFactory; +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.assembly.Component; +import org.apache.tuscany.sca.assembly.ComponentReference; +import org.apache.tuscany.sca.assembly.ComponentService; +import org.apache.tuscany.sca.assembly.Composite; +import org.apache.tuscany.sca.assembly.CompositeService; +import org.apache.tuscany.sca.assembly.Endpoint; +import org.apache.tuscany.sca.assembly.Implementation; +import org.apache.tuscany.sca.assembly.OptimizableBinding; +import org.apache.tuscany.sca.assembly.Reference; +import org.apache.tuscany.sca.assembly.SCABindingFactory; +import org.apache.tuscany.sca.assembly.Service; +import org.apache.tuscany.sca.context.RequestContextFactory; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessorExtensionPoint; +import org.apache.tuscany.sca.core.context.ComponentContextHelper; +import org.apache.tuscany.sca.core.context.ComponentContextImpl; +import org.apache.tuscany.sca.core.conversation.ConversationManager; +import org.apache.tuscany.sca.core.invocation.ProxyFactory; +import org.apache.tuscany.sca.core.scope.ConversationalScopeContainer; +import org.apache.tuscany.sca.core.scope.Scope; +import org.apache.tuscany.sca.core.scope.ScopeContainer; +import org.apache.tuscany.sca.core.scope.ScopeRegistry; +import org.apache.tuscany.sca.core.scope.ScopedRuntimeComponent; +import org.apache.tuscany.sca.endpointresolver.EndpointResolver; +import org.apache.tuscany.sca.endpointresolver.EndpointResolverFactory; +import org.apache.tuscany.sca.endpointresolver.EndpointResolverFactoryExtensionPoint; +import org.apache.tuscany.sca.interfacedef.InterfaceContract; +import org.apache.tuscany.sca.interfacedef.InterfaceContractMapper; +import org.apache.tuscany.sca.interfacedef.java.JavaInterfaceFactory; +import org.apache.tuscany.sca.invocation.MessageFactory; +import org.apache.tuscany.sca.provider.BindingProviderFactory; +import org.apache.tuscany.sca.provider.ImplementationProvider; +import org.apache.tuscany.sca.provider.ImplementationProviderFactory; +import org.apache.tuscany.sca.provider.PolicyProvider; +import org.apache.tuscany.sca.provider.PolicyProviderFactory; +import org.apache.tuscany.sca.provider.ProviderFactoryExtensionPoint; +import org.apache.tuscany.sca.provider.ReferenceBindingProvider; +import org.apache.tuscany.sca.provider.ServiceBindingProvider; +import org.apache.tuscany.sca.runtime.EndpointReference; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentContext; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; +import org.apache.tuscany.sca.runtime.RuntimeWire; +import org.apache.tuscany.sca.runtime.RuntimeWireProcessor; +import org.apache.tuscany.sca.work.WorkScheduler; + +/** + * @version $Rev$ $Date$ + */ +public class CompositeActivatorImpl implements CompositeActivator { + private static final Logger logger = Logger.getLogger(CompositeActivatorImpl.class.getName()); + + private final AssemblyFactory assemblyFactory; + private final MessageFactory messageFactory; + private final InterfaceContractMapper interfaceContractMapper; + private final ScopeRegistry scopeRegistry; + private final WorkScheduler workScheduler; + private final RuntimeWireProcessor wireProcessor; + private final ProviderFactoryExtensionPoint providerFactories; + private final EndpointResolverFactoryExtensionPoint endpointResolverFactories; + + private final RequestContextFactory requestContextFactory; + private final ProxyFactory proxyFactory; + private final JavaInterfaceFactory javaInterfaceFactory; + private final ConversationManager conversationManager; + + private final ComponentContextHelper componentContextHelper; + + private Composite domainComposite; + + /** + * @param assemblyFactory + * @param interfaceContractMapper + * @param workScheduler + * @param conversationManager TODO + * @param workContext + * @param wirePostProcessorRegistry + */ + public CompositeActivatorImpl(AssemblyFactory assemblyFactory, + MessageFactory messageFactory, + JavaInterfaceFactory javaInterfaceFactory, + SCABindingFactory scaBindingFactory, + InterfaceContractMapper interfaceContractMapper, + ScopeRegistry scopeRegistry, + WorkScheduler workScheduler, + RuntimeWireProcessor wireProcessor, + RequestContextFactory requestContextFactory, + ProxyFactory proxyFactory, + ProviderFactoryExtensionPoint providerFactories, + EndpointResolverFactoryExtensionPoint endpointResolverFactories, + StAXArtifactProcessorExtensionPoint processors, + ConversationManager conversationManager) { + this.assemblyFactory = assemblyFactory; + this.messageFactory = messageFactory; + this.interfaceContractMapper = interfaceContractMapper; + this.scopeRegistry = scopeRegistry; + this.workScheduler = workScheduler; + this.wireProcessor = wireProcessor; + this.providerFactories = providerFactories; + this.endpointResolverFactories = endpointResolverFactories; + this.javaInterfaceFactory = javaInterfaceFactory; + this.requestContextFactory = requestContextFactory; + this.proxyFactory = proxyFactory; + this.conversationManager = conversationManager; + this.componentContextHelper = new ComponentContextHelper(assemblyFactory, javaInterfaceFactory, processors); + } + + /** + * @see org.apache.tuscany.sca.core.assembly.CompositeActivator#activate(org.apache.tuscany.sca.runtime.RuntimeComponent, org.apache.tuscany.sca.runtime.RuntimeComponentReference) + */ + public void activate(RuntimeComponent component, RuntimeComponentReference ref) { + if (logger.isLoggable(Level.FINE)) { + logger.fine("Activating component reference: " + component.getURI() + "#" + ref.getName()); + } + resolveTargets(ref); + for (Binding binding : ref.getBindings()) { + addReferenceBindingProvider(component, ref, binding); + } + + for (Endpoint endpoint : ref.getEndpoints()){ + // TODO - source component should be set in the builder but the + // way the builder is written it's difficult to get at it + endpoint.setSourceComponent(component); + + addEndpointResolver(component, ref, endpoint); + } + } + + public void start(RuntimeComponent component, RuntimeComponentReference ref) { + synchronized (ref) { + resolveTargets(ref); + for (Binding binding : ref.getBindings()) { + ReferenceBindingProvider provider = ref.getBindingProvider(binding); + if (provider == null) { + provider = addReferenceBindingProvider(component, ref, binding); + } + if (provider != null) { + provider.start(); + } + addReferenceWire(component, ref, binding); + } + + // targets now have an endpoint representation. We can use this to + // look for unresolved endpoints using dummy wires for late resolution + for (Endpoint endpoint : ref.getEndpoints()){ + addReferenceEndpointWire(component, ref, endpoint); + } + } + } + + public void stop(Component component, ComponentReference reference) { + if (logger.isLoggable(Level.FINE)) { + logger.fine("Stopping component reference: " + component.getURI() + "#" + reference.getName()); + } + RuntimeComponentReference runtimeRef = ((RuntimeComponentReference)reference); + for (Binding binding : reference.getBindings()) { + ReferenceBindingProvider bindingProvider = runtimeRef.getBindingProvider(binding); + if (bindingProvider != null) { + bindingProvider.stop(); + } + } + } + + public void deactivate(RuntimeComponent component, RuntimeComponentReference ref) { + if (logger.isLoggable(Level.FINE)) { + logger.fine("Deactivating component reference: " + component.getURI() + "#" + ref.getName()); + } + removeReferenceWires(ref); + for (Binding binding : ref.getBindings()) { + removeReferenceBindingProvider(component, ref, binding); + } + + } + + /** + * @param component + * @param reference + * @param binding + */ + private EndpointResolver addEndpointResolver(RuntimeComponent component, + RuntimeComponentReference reference, + Endpoint endpoint){ + + // only create endpoint resolvers for unresolved endpoints currently + // this will also prevent a wire from being created later + if (!endpoint.isUnresolved()){ + return null; + } + + // This souldn't happen as the endpoint resolver extension point is in core-spi but + // just in case returning null here will mean that no wire is created and calling + // the reference will fail with NPE + if (endpointResolverFactories == null){ + return null; + } + + EndpointResolverFactory<Endpoint> resolverFactory = + (EndpointResolverFactory<Endpoint>)endpointResolverFactories.getEndpointResolverFactory(endpoint.getClass()); + + if (resolverFactory != null) { + @SuppressWarnings("unchecked") + EndpointResolver endpointResolver = + resolverFactory.createEndpointResolver(endpoint, null); + if (endpointResolver != null) { + ((RuntimeComponentReference)reference).setEndpointResolver(endpoint, endpointResolver); + } + + return endpointResolver; + } else { + // TODO - for the time being allow the lack of an endpoint provider to be the + // switch to turn off endpoint processing + return null; + //throw new IllegalStateException("Endpoint provider factory not found for class: " + endpoint.getClass().getName()); + } + } + + public void addReferenceBindingProviderForEndpoint(Endpoint endpoint){ + addReferenceBindingProvider((RuntimeComponent)endpoint.getSourceComponent(), + (RuntimeComponentReference)endpoint.getSourceComponentReference(), + endpoint.getSourceBinding()); + } + + /** + * @param component + * @param reference + * @param binding + */ + private ReferenceBindingProvider addReferenceBindingProvider(RuntimeComponent component, + RuntimeComponentReference reference, + Binding binding) { + BindingProviderFactory providerFactory = + (BindingProviderFactory)providerFactories.getProviderFactory(binding.getClass()); + if (providerFactory != null) { + @SuppressWarnings("unchecked") + ReferenceBindingProvider bindingProvider = + providerFactory.createReferenceBindingProvider((RuntimeComponent)component, + (RuntimeComponentReference)reference, + binding); + if (bindingProvider != null) { + ((RuntimeComponentReference)reference).setBindingProvider(binding, bindingProvider); + } + for (PolicyProviderFactory f : providerFactories.getPolicyProviderFactories()) { + PolicyProvider policyProvider = f.createReferencePolicyProvider(component, reference, binding); + if (policyProvider != null) { + reference.addPolicyProvider(binding, policyProvider); + } + } + + return bindingProvider; + } else { + throw new IllegalStateException("Provider factory not found for class: " + binding.getClass().getName()); + } + } + + /** + * @param reference + */ + private void resolveTargets(RuntimeComponentReference reference) { + // The code that used to be here to resolved unresolved targets is now + // at the bottom of BaseWireBuilder.connectComponentReferences() + } + + /** + * Create the runtime wires for a reference endpoint. Currently this method + * only deals with the late binding case and creates a dummy wire that + * will use the Endpoint to resolve the target at the point when the + * wire chains are created. + * + * @param component + * @param reference + * @param binding + */ + private void addReferenceEndpointWire(Component component, ComponentReference reference, Endpoint endpoint) { + // only deal with unresolved endpoints as, to prevent breaking changes, targets that are resolved + // at build time are still represented as bindings in the binding list + if (((RuntimeComponentReference)reference).getEndpointResolver(endpoint) == null){ + // no endpoint provider has previously been created so don't create the + // wire + return; + } + + // TODO: TUSCANY-2580: avoid NPE if the InterfaceCOntract is null + Reference ctref = endpoint.getSourceComponentReference().getReference(); + if (ctref != null && ctref.getInterfaceContract() == null) { + ctref.setInterfaceContract(reference.getInterfaceContract()); + } + + RuntimeWire wire = new EndpointWireImpl(endpoint, this); + + RuntimeComponentReference runtimeRef = (RuntimeComponentReference)reference; + runtimeRef.getRuntimeWires().add(wire); + } + + + /** + * Create the runtime wires for a reference binding + * + * @param component + * @param reference + * @param binding + */ + private void addReferenceWire(Component component, ComponentReference reference, Binding binding) { + if (!(reference instanceof RuntimeComponentReference)) { + return; + } + + // create wire if binding has an endpoint + Component targetComponent = null; + ComponentService targetComponentService = null; + Binding targetBinding = null; + + if (binding instanceof OptimizableBinding) { + OptimizableBinding endpoint = (OptimizableBinding)binding; + targetComponent = endpoint.getTargetComponent(); + targetComponentService = endpoint.getTargetComponentService(); + targetBinding = endpoint.getTargetBinding(); + // FIXME: TUSCANY-2136, For unresolved binding, don't add wire. Is it the right solution? + if (!reference.isCallback() && binding.getURI() == null && targetComponentService == null) { + return; + } + } + + // create a forward wire, either static or dynamic + addReferenceWire(component, reference, binding, targetComponent, targetComponentService, targetBinding); + + /* + // if static forward wire (not from self-reference), try to create a static callback wire + if (targetComponentService != null && !reference.getName().startsWith("$self$.")) { + ComponentReference callbackReference = targetComponentService.getCallbackReference(); + if (callbackReference != null) { + Binding callbackBinding = null; + Binding callbackServiceBinding = null; + // select a service callback binding that can be wired back to this component + for (Binding refBinding : callbackReference.getBindings()) { + // first look for a callback binding whose name matches the target binding name + if (refBinding.getName().equals(targetBinding.getName())) { + callbackBinding = refBinding; + break; + } + } + // see if there is a matching reference callback binding + if (callbackBinding != null) { + callbackServiceBinding = reference.getCallbackService().getBinding(callbackBinding.getClass()); + } + // if there isn't an end-to-end match, try again based on target binding type + if (callbackBinding == null || callbackServiceBinding == null) { + callbackBinding = callbackReference.getBinding(targetBinding.getClass()); + if (callbackBinding != null) { + callbackServiceBinding = reference.getCallbackService().getBinding(callbackBinding.getClass()); + } + } + if (callbackBinding != null && callbackServiceBinding != null) { + // end-to-end match, so create a static callback wire as well as the static forward wire + + addReferenceWire(targetComponent, callbackReference, callbackBinding, component, reference + .getCallbackService(), callbackServiceBinding); + } else { + // no end-to-end match, so do not create a static callback wire + } + } + } + */ + } + + public void addReferenceWireForEndpoint(Endpoint endpoint){ + addReferenceWire(endpoint.getSourceComponent(), + endpoint.getSourceComponentReference(), + endpoint.getSourceBinding(), + endpoint.getTargetComponent(), + endpoint.getTargetComponentService(), + endpoint.getTargetBinding()); + } + /** + * Create a reference wire for a forward call or a callback + * @param reference + * @param service + * @param serviceBinding + * @param component + * @param referenceBinding + */ + private RuntimeWire addReferenceWire(Component refComponent, + ComponentReference reference, + Binding refBinding, + Component serviceComponent, + ComponentService service, + Binding serviceBinding) { + RuntimeComponentReference runtimeRef = (RuntimeComponentReference)reference; + InterfaceContract bindingContract = getInterfaceContract(reference, refBinding); + + // Use the interface contract of the reference on the component type + Reference componentTypeRef = reference.getReference(); + + InterfaceContract sourceContract; + if (componentTypeRef == null || componentTypeRef.getInterfaceContract() == null) { + sourceContract = reference.getInterfaceContract(); + } else { + sourceContract = componentTypeRef.getInterfaceContract(); + } + + sourceContract = sourceContract.makeUnidirectional(false); + + EndpointReference wireSource = + new EndpointReferenceImpl((RuntimeComponent)refComponent, reference, refBinding, sourceContract); + ComponentService callbackService = reference.getCallbackService(); + if (callbackService != null) { + // select a reference callback binding to pass with invocations on this wire + Binding callbackBinding = null; + for (Binding binding : callbackService.getBindings()) { + // first look for a callback binding whose name matches the reference binding name + if (refBinding.getName().startsWith(binding.getName())) { + callbackBinding = binding; + break; + } + } + // if no callback binding found, try again based on reference binding type + if (callbackBinding == null) { + callbackBinding = callbackService.getBinding(refBinding.getClass()); + } + InterfaceContract callbackContract = callbackService.getInterfaceContract(); + EndpointReference callbackEndpoint = + new EndpointReferenceImpl((RuntimeComponent)refComponent, callbackService, callbackBinding, + callbackContract); + wireSource.setCallbackEndpoint(callbackEndpoint); + } + + EndpointReference wireTarget = + new EndpointReferenceImpl((RuntimeComponent)serviceComponent, service, serviceBinding, bindingContract); + + // TUSCANY-2029 - We should use the URI of the serviceBinding because the target may be a Component in a + // nested composite. + if (serviceBinding != null) { + wireTarget.setURI(serviceBinding.getURI()); + } + + RuntimeWire wire = + new RuntimeWireImpl(wireSource, wireTarget, interfaceContractMapper, workScheduler, wireProcessor, + messageFactory, conversationManager); + runtimeRef.getRuntimeWires().add(wire); + + return wire; + } + + private void addImplementationProvider(RuntimeComponent component, Implementation implementation) { + ImplementationProviderFactory providerFactory = + (ImplementationProviderFactory)providerFactories.getProviderFactory(implementation.getClass()); + if (providerFactory != null) { + @SuppressWarnings("unchecked") + ImplementationProvider implementationProvider = + providerFactory.createImplementationProvider(component, implementation); + if (implementationProvider != null) { + component.setImplementationProvider(implementationProvider); + } + } else { + throw new IllegalStateException("Provider factory not found for class: " + implementation.getClass() + .getName()); + } + for (PolicyProviderFactory f : providerFactories.getPolicyProviderFactories()) { + PolicyProvider policyProvider = f.createImplementationPolicyProvider(component, implementation); + if (policyProvider != null) { + component.addPolicyProvider(policyProvider); + } + } + + } + + private void removeImplementationProvider(RuntimeComponent component) { + component.setImplementationProvider(null); + component.getPolicyProviders().clear(); + } + + /** + * @param component + * @param service + * @param binding + */ + private ServiceBindingProvider addServiceBindingProvider(RuntimeComponent component, + RuntimeComponentService service, + Binding binding) { + BindingProviderFactory providerFactory = + (BindingProviderFactory)providerFactories.getProviderFactory(binding.getClass()); + if (providerFactory != null) { + @SuppressWarnings("unchecked") + ServiceBindingProvider bindingProvider = + providerFactory.createServiceBindingProvider((RuntimeComponent)component, + (RuntimeComponentService)service, + binding); + if (bindingProvider != null) { + ((RuntimeComponentService)service).setBindingProvider(binding, bindingProvider); + } + for (PolicyProviderFactory f : providerFactories.getPolicyProviderFactories()) { + PolicyProvider policyProvider = f.createServicePolicyProvider(component, service, binding); + if (policyProvider != null) { + service.addPolicyProvider(binding, policyProvider); + } + } + return bindingProvider; + } else { + throw new IllegalStateException("Provider factory not found for class: " + binding.getClass().getName()); + } + } + + private void removeServiceBindingProvider(RuntimeComponent component, + RuntimeComponentService service, + Binding binding) { + service.setBindingProvider(binding, null); + for (Binding b : service.getBindings()) { + List<PolicyProvider> pps = service.getPolicyProviders(b); + if (pps != null) { + pps.clear(); + } + } + } + + private void removeReferenceBindingProvider(RuntimeComponent component, + RuntimeComponentReference reference, + Binding binding) { + reference.setBindingProvider(binding, null); + for (Binding b : reference.getBindings()) { + List<PolicyProvider> pps = reference.getPolicyProviders(b); + if (pps != null) { + pps.clear(); + } + } + } + + public void start(Composite composite) { + if (logger.isLoggable(Level.FINE)) { + logger.fine("Starting composite: " + composite.getName()); + } + for (Component component : composite.getComponents()) { + start(component); + } + } + + public void stop(Composite composite) { + if (logger.isLoggable(Level.FINE)) { + logger.fine("Stopping composite: " + composite.getName()); + } + for (final Component component : composite.getComponents()) { + stop(component); + } + } + + public void start(Component component) { + if (logger.isLoggable(Level.FINE)) { + logger.fine("Starting component: " + component.getURI()); + } + RuntimeComponent runtimeComponent = ((RuntimeComponent)component); + if(runtimeComponent.isStarted()) { + return; + } + + configureComponentContext(runtimeComponent); + + for (ComponentReference reference : component.getReferences()) { + if (logger.isLoggable(Level.FINE)) { + logger.fine("Starting component reference: " + component.getURI() + "#" + reference.getName()); + } + RuntimeComponentReference runtimeRef = ((RuntimeComponentReference)reference); + runtimeRef.setComponent(runtimeComponent); + + for (Endpoint endpoint : reference.getEndpoints()) { + final EndpointResolver endpointResolver = runtimeRef.getEndpointResolver(endpoint); + if (endpointResolver != null) { + // Allow endpoint resolvers to do any startup reference manipulation + AccessController.doPrivileged(new PrivilegedAction<Object>() { + public Object run() { + endpointResolver.start(); + return null; + } + }); + } + } + + for (Binding binding : reference.getBindings()) { + final ReferenceBindingProvider bindingProvider = runtimeRef.getBindingProvider(binding); + if (bindingProvider != null) { + // Allow bindings to add shutdown hooks. Requires RuntimePermission shutdownHooks in policy. + AccessController.doPrivileged(new PrivilegedAction<Object>() { + public Object run() { + bindingProvider.start(); + return null; + } + }); + } + } + } + + for (ComponentService service : component.getServices()) { + if (logger.isLoggable(Level.FINE)) { + logger.fine("Starting component service: " + component.getURI() + "#" + service.getName()); + } + RuntimeComponentService runtimeService = (RuntimeComponentService)service; + for (Binding binding : service.getBindings()) { + final ServiceBindingProvider bindingProvider = runtimeService.getBindingProvider(binding); + if (bindingProvider != null) { + // bindingProvider.start(); + // Allow bindings to add shutdown hooks. Requires RuntimePermission shutdownHooks in policy. + AccessController.doPrivileged(new PrivilegedAction<Object>() { + public Object run() { + bindingProvider.start(); + return null; + } + }); + } + } + } + + Implementation implementation = component.getImplementation(); + if (implementation instanceof Composite) { + start((Composite)implementation); + } else { + ImplementationProvider implementationProvider = runtimeComponent.getImplementationProvider(); + if (implementationProvider != null) { + implementationProvider.start(); + } + } + + if (component instanceof ScopedRuntimeComponent) { + ScopedRuntimeComponent scopedRuntimeComponent = (ScopedRuntimeComponent)component; + if (scopedRuntimeComponent.getScopeContainer() != null) { + scopedRuntimeComponent.getScopeContainer().start(); + } + } + + runtimeComponent.setStarted(true); + } + + /** + * @param runtimeComponent + */ + public void configureComponentContext(RuntimeComponent runtimeComponent) { + RuntimeComponentContext componentContext = + new ComponentContextImpl(this, assemblyFactory, proxyFactory, interfaceContractMapper, + requestContextFactory, javaInterfaceFactory, runtimeComponent); + runtimeComponent.setComponentContext(componentContext); + } + + /** + * Stop a component + */ + public void stop(Component component) { + if (!((RuntimeComponent)component).isStarted()) { + return; + } + if (logger.isLoggable(Level.FINE)) { + logger.fine("Stopping component: " + component.getURI()); + } + for (ComponentService service : component.getServices()) { + if (logger.isLoggable(Level.FINE)) { + logger.fine("Stopping component service: " + component.getURI() + "#" + service.getName()); + } + for (Binding binding : service.getBindings()) { + final ServiceBindingProvider bindingProvider = ((RuntimeComponentService)service).getBindingProvider(binding); + if (bindingProvider != null) { + // Allow bindings to read properties. Requires PropertyPermission read in security policy. + AccessController.doPrivileged(new PrivilegedAction<Object>() { + public Object run() { + bindingProvider.stop(); + return null; + } + }); + } + } + } + for (ComponentReference reference : component.getReferences()) { + if (logger.isLoggable(Level.FINE)) { + logger.fine("Starting component reference: " + component.getURI() + "#" + reference.getName()); + } + RuntimeComponentReference runtimeRef = ((RuntimeComponentReference)reference); + + for (Binding binding : reference.getBindings()) { + final ReferenceBindingProvider bindingProvider = runtimeRef.getBindingProvider(binding); + if (bindingProvider != null) { + // Allow bindings to read properties. Requires PropertyPermission read in security policy. + AccessController.doPrivileged(new PrivilegedAction<Object>() { + public Object run() { + bindingProvider.stop(); + return null; + } + }); + } + } + + for (Endpoint endpoint : reference.getEndpoints()) { + final EndpointResolver endpointResolver = runtimeRef.getEndpointResolver(endpoint); + if (endpointResolver != null) { + // Allow endpoint resolvers to do any shutdown reference manipulation + AccessController.doPrivileged(new PrivilegedAction<Object>() { + public Object run() { + endpointResolver.stop(); + return null; + } + }); + } + } + } + Implementation implementation = component.getImplementation(); + if (implementation instanceof Composite) { + stop((Composite)implementation); + } else { + final ImplementationProvider implementationProvider = ((RuntimeComponent)component).getImplementationProvider(); + if (implementationProvider != null) { + // Allow bindings to read properties. Requires PropertyPermission read in security policy. + AccessController.doPrivileged(new PrivilegedAction<Object>() { + public Object run() { + implementationProvider.stop(); + return null; + } + }); + } + } + + if (component instanceof ScopedRuntimeComponent) { + ScopedRuntimeComponent runtimeComponent = (ScopedRuntimeComponent)component; + if (runtimeComponent.getScopeContainer() != null && + runtimeComponent.getScopeContainer().getLifecycleState() != ScopeContainer.STOPPED) { + runtimeComponent.getScopeContainer().stop(); + } + } + + ((RuntimeComponent)component).setStarted(false); + } + + /** + * Get the effective interface contract for a reference binding + * + * @param reference + * @param binding + * @return + */ + private InterfaceContract getInterfaceContract(ComponentReference reference, Binding binding) { + InterfaceContract interfaceContract = reference.getInterfaceContract(); + ReferenceBindingProvider provider = ((RuntimeComponentReference)reference).getBindingProvider(binding); + if (provider != null) { + InterfaceContract bindingContract = provider.getBindingInterfaceContract(); + if (bindingContract != null) { + interfaceContract = bindingContract; + } + } + return interfaceContract.makeUnidirectional(false); + } + + /** + * Remove the runtime wires for a reference binding + * @param reference + */ + private void removeReferenceWires(ComponentReference reference) { + if (!(reference instanceof RuntimeComponentReference)) { + return; + } + // [rfeng] Comment out the following statements to avoid the on-demand activation + // RuntimeComponentReference runtimeRef = (RuntimeComponentReference)reference; + // runtimeRef.getRuntimeWires().clear(); + } + + /** + * Get the effective interface contract for the service binding + * + * @param service + * @param binding + * @return + */ + private InterfaceContract getInterfaceContract(ComponentService service, Binding binding) { + InterfaceContract interfaceContract = service.getInterfaceContract(); + + ServiceBindingProvider provider = ((RuntimeComponentService)service).getBindingProvider(binding); + if (provider != null) { + InterfaceContract bindingContract = provider.getBindingInterfaceContract(); + if (bindingContract != null) { + interfaceContract = bindingContract; + } + } + return interfaceContract.makeUnidirectional(false); + } + + /** + * Remove runtime wires for a service binding + * + * @param component + * @param service + */ + private void removeServiceWires(ComponentService service) { + if (!(service instanceof RuntimeComponentService)) { + return; + } + RuntimeComponentService runtimeService = (RuntimeComponentService)service; + runtimeService.getRuntimeWires().clear(); + } + + /** + * Create a service wire for a forward call or a callback + * @param service + * @param serviceBinding + * @param reference + * @param component + * @param referenceBinding + */ + private RuntimeWire addServiceWire(Component serviceComponent, ComponentService service, Binding serviceBinding) { + if (!(service instanceof RuntimeComponentService)) { + return null; + } + RuntimeComponentService runtimeService = (RuntimeComponentService)service; + + // FIXME: [rfeng] We might need a better way to get the impl interface contract + Service targetService = service.getService(); + if (targetService == null) { + targetService = service; + } + InterfaceContract targetContract = targetService.getInterfaceContract().makeUnidirectional(false); + + InterfaceContract sourceContract = getInterfaceContract(service, serviceBinding); + + EndpointReference wireSource = new EndpointReferenceImpl(null, null, serviceBinding, sourceContract); + + EndpointReference wireTarget = + new EndpointReferenceImpl((RuntimeComponent)serviceComponent, (RuntimeComponentService)service, + serviceBinding, targetContract); + + RuntimeWire wire = + new RuntimeWireImpl(wireSource, wireTarget, interfaceContractMapper, workScheduler, wireProcessor, + messageFactory, conversationManager); + runtimeService.getRuntimeWires().add(wire); + + return wire; + } + + public void activate(RuntimeComponent component, RuntimeComponentService service) { + if (service.getService() == null) { + if (logger.isLoggable(Level.WARNING)) { + logger.warning("Skipping component service not defined in the component type: " + component.getURI() + + "#" + + service.getName()); + } + return; + } + if (service.getService() instanceof CompositeService) { + return; + } + if (logger.isLoggable(Level.FINE)) { + logger.fine("Activating component service: " + component.getURI() + "#" + service.getName()); + } + + for (Binding binding : service.getBindings()) { + addServiceBindingProvider(component, service, binding); + addServiceWire(component, service, binding); + } + } + + public void deactivate(RuntimeComponent component, RuntimeComponentService service) { + if (logger.isLoggable(Level.FINE)) { + logger.fine("Deactivating component service: " + component.getURI() + "#" + service.getName()); + } + removeServiceWires(service); + for (Binding binding : service.getBindings()) { + removeServiceBindingProvider(component, service, binding); + } + } + + private void addScopeContainer(Component component) { + if (!(component instanceof ScopedRuntimeComponent)) { + return; + } + ScopedRuntimeComponent runtimeComponent = (ScopedRuntimeComponent)component; + ScopeContainer scopeContainer = scopeRegistry.getScopeContainer(runtimeComponent); + if (scopeContainer != null && scopeContainer.getScope() == Scope.CONVERSATION) { + conversationManager.addListener((ConversationalScopeContainer)scopeContainer); + } + runtimeComponent.setScopeContainer(scopeContainer); + } + + private void removeScopeContainer(Component component) { + if (!(component instanceof ScopedRuntimeComponent)) { + return; + } + ScopedRuntimeComponent runtimeComponent = (ScopedRuntimeComponent)component; + ScopeContainer scopeContainer = runtimeComponent.getScopeContainer(); + if(scopeContainer != null && scopeContainer.getScope() == Scope.CONVERSATION) { + conversationManager.removeListener((ConversationalScopeContainer) scopeContainer); + } + runtimeComponent.setScopeContainer(null); + } + + public void activateComponent(Component component) + throws ActivationException { + try { + if (logger.isLoggable(Level.FINE)) { + logger.fine("Activating component: " + component.getURI()); + } + + Implementation implementation = component.getImplementation(); + if (implementation instanceof Composite) { + activate((Composite) implementation); + } else if (implementation != null) { + addImplementationProvider((RuntimeComponent) component, + implementation); + addScopeContainer(component); + } + + for (ComponentService service : component.getServices()) { + activate((RuntimeComponent) component, + (RuntimeComponentService) service); + } + + for (ComponentReference reference : component.getReferences()) { + activate((RuntimeComponent) component, + (RuntimeComponentReference) reference); + } + } catch (Exception e) { + throw new ActivationException(e); + } + } + + public void deactivateComponent(Component component) + throws ActivationException { + try { + if (logger.isLoggable(Level.FINE)) { + logger.fine("Deactivating component: " + component.getURI()); + } + for (ComponentService service : component.getServices()) { + deactivate((RuntimeComponent) component, + (RuntimeComponentService) service); + } + + for (ComponentReference reference : component.getReferences()) { + deactivate((RuntimeComponent) component, + (RuntimeComponentReference) reference); + } + + Implementation implementation = component.getImplementation(); + if (implementation instanceof Composite) { + deactivate((Composite) implementation); + } else if (implementation != null) { + removeImplementationProvider((RuntimeComponent) component); + removeScopeContainer(component); + } + } catch (Exception e) { + throw new ActivationException(e); + } + } + + public void activate(Composite composite) throws ActivationException { + try { + if (logger.isLoggable(Level.FINE)) { + logger.fine("Activating composite: " + composite.getName()); + } + for (Component component : composite.getComponents()) { + if (logger.isLoggable(Level.FINE)) { + logger.fine("Activating component: " + component.getURI()); + } + + Implementation implementation = component.getImplementation(); + if (implementation instanceof Composite) { + activate((Composite)implementation); + } else if (implementation != null) { + addImplementationProvider((RuntimeComponent)component, implementation); + addScopeContainer(component); + } + + for (ComponentService service : component.getServices()) { + activate((RuntimeComponent)component, (RuntimeComponentService)service); + } + + for (ComponentReference reference : component.getReferences()) { + activate((RuntimeComponent)component, (RuntimeComponentReference)reference); + } + } + } catch (Exception e) { + throw new ActivationException(e); + } + } + + public void deactivate(Composite composite) throws ActivationException { + try { + if (logger.isLoggable(Level.FINE)) { + logger.fine("Deactivating composite: " + composite.getName()); + } + for (Component component : composite.getComponents()) { + if (logger.isLoggable(Level.FINE)) { + logger.fine("Deactivating component: " + component.getURI()); + } + for (ComponentService service : component.getServices()) { + deactivate((RuntimeComponent)component, (RuntimeComponentService)service); + } + + for (ComponentReference reference : component.getReferences()) { + deactivate((RuntimeComponent)component, (RuntimeComponentReference)reference); + } + + Implementation implementation = component.getImplementation(); + if (implementation instanceof Composite) { + deactivate((Composite)implementation); + } else if (implementation != null) { + removeImplementationProvider((RuntimeComponent)component); + removeScopeContainer(component); + } + } + } catch (Exception e) { + throw new ActivationException(e); + } + } + + /** + * @return the referenceHelper + */ + public ComponentContextHelper getComponentContextHelper() { + return componentContextHelper; + } + + /** + * @return the proxyFactory + */ + public ProxyFactory getProxyFactory() { + return proxyFactory; + } + + /** + * @return the domainComposite + */ + public Composite getDomainComposite() { + return domainComposite; + } + + /** + * @param domainComposite the domainComposite to set + */ + public void setDomainComposite(Composite domainComposite) { + this.domainComposite = domainComposite; + } + + public Component resolve(String componentURI) { + for (Composite composite : domainComposite.getIncludes()) { + Component component = resolve(composite, componentURI); + if (component != null) { + return component; + } + } + return null; + } + + public Component resolve(Composite composite, String componentURI) { + for (Component component : composite.getComponents()) { + String uri = component.getURI(); + if (uri.equals(componentURI)) { + return component; + } + if (componentURI.startsWith(uri)) { + Implementation implementation = component.getImplementation(); + if (!(implementation instanceof Composite)) { + return null; + } + return resolve((Composite)implementation, componentURI); + } + } + return null; + } + + /** + * @return the javaInterfaceFactory + */ + public JavaInterfaceFactory getJavaInterfaceFactory() { + return javaInterfaceFactory; + } + + /** + * @return the conversationManager + */ + public ConversationManager getConversationManager() { + return conversationManager; + } + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/assembly/EndpointReferenceImpl.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/assembly/EndpointReferenceImpl.java new file mode 100644 index 0000000000..78096b20ab --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/assembly/EndpointReferenceImpl.java @@ -0,0 +1,186 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core.assembly; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.assembly.Contract; +import org.apache.tuscany.sca.interfacedef.InterfaceContract; +import org.apache.tuscany.sca.runtime.EndpointReference; +import org.apache.tuscany.sca.runtime.ReferenceParameters; +import org.apache.tuscany.sca.runtime.RuntimeComponent; + +/** + * @version $Rev$ $Date$ + */ +public class EndpointReferenceImpl implements EndpointReference { + private RuntimeComponent component; + private Contract contract; + private Binding binding; + private InterfaceContract interfaceContract; + private String uri; + private EndpointReference callbackEndpoint; + private ReferenceParameters parameters = new ReferenceParametersImpl(); + + /** + * @param component + * @param contract + * @param binding + * @param interfaceContract + */ + public EndpointReferenceImpl(RuntimeComponent component, + Contract contract, + Binding binding, + InterfaceContract interfaceContract) { + super(); + this.component = component; + this.contract = contract; + this.binding = binding; + this.interfaceContract = interfaceContract; + this.uri = (component != null ? component.getURI() : "") + '/' + + (contract != null ? contract.getName() : ""); + } + + /** + * @param uri + */ + public EndpointReferenceImpl(String uri) { + super(); + this.uri = uri; + } + + public Binding getBinding() { + return binding; + } + + public void setBinding(Binding binding) { + this.binding = binding; + } + + public RuntimeComponent getComponent() { + return component; + } + + public void setComponent(RuntimeComponent component) { + this.component = component; + } + + public Contract getContract() { + return contract; + } + + public void setContract(Contract contract) { + this.contract = contract; + } + + public InterfaceContract getInterfaceContract() { + return interfaceContract; + } + + public void setInterfaceContract(InterfaceContract interfaceContract) { + this.interfaceContract = interfaceContract; + } + + public String getURI() { + return uri; + } + + public void setURI(String uri) { + this.uri = uri; + } + + public EndpointReference getCallbackEndpoint() { + return callbackEndpoint; + } + + public void setCallbackEndpoint(EndpointReference callbackEndpoint) { + this.callbackEndpoint = callbackEndpoint; + } + + @Override + public int hashCode() { + final int PRIME = 31; + int result = 1; + result = PRIME * result + ((uri == null) ? 0 : uri.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 EndpointReferenceImpl other = (EndpointReferenceImpl)obj; + if (uri == null) { + if (other.uri != null) { + return false; + } + } else if (!uri.equals(other.uri)) { + return false; + } + return true; + } + + /** + * @see java.lang.Object#clone() + */ + @Override + public Object clone() throws CloneNotSupportedException { + EndpointReferenceImpl copy = (EndpointReferenceImpl)super.clone(); + /* [nash] no need to copy callback endpoint + if (callbackEndpoint != null) { + copy.callbackEndpoint = (EndpointReference)callbackEndpoint.clone(); + } + */ + if (parameters != null) { + copy.parameters = (ReferenceParameters)parameters.clone(); + } + return copy; + } + + /** + * @return the parameters + */ + public ReferenceParameters getReferenceParameters() { + return parameters; + } + + /** + * @param parameters the parameters to set + */ + public void setReferenceParameters(ReferenceParameters parameters) { + this.parameters = parameters; + } + + public void mergeEndpoint(EndpointReference epr) { + this.component = epr.getComponent(); + this.contract = epr.getContract(); + this.binding = epr.getBinding(); + this.interfaceContract = epr.getInterfaceContract(); + this.uri = epr.getURI(); + this.callbackEndpoint = epr.getCallbackEndpoint(); + } + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/assembly/EndpointWireImpl.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/assembly/EndpointWireImpl.java new file mode 100644 index 0000000000..4f463b105d --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/assembly/EndpointWireImpl.java @@ -0,0 +1,185 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core.assembly; + +import java.lang.reflect.InvocationTargetException; +import java.util.List; + +import org.apache.tuscany.sca.assembly.Endpoint; +import org.apache.tuscany.sca.assembly.Reference; +import org.apache.tuscany.sca.core.invocation.InvocationChainImpl; +import org.apache.tuscany.sca.endpointresolver.EndpointResolver; +import org.apache.tuscany.sca.interfacedef.InterfaceContract; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.InvocationChain; +import org.apache.tuscany.sca.invocation.Message; +import org.apache.tuscany.sca.provider.ReferenceBindingProvider; +import org.apache.tuscany.sca.runtime.EndpointReference; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.apache.tuscany.sca.runtime.RuntimeWire; +import org.osoa.sca.ServiceUnavailableException; + +/** + * @version $Rev$ $Date$ + */ +public class EndpointWireImpl implements RuntimeWire { + + private Endpoint endpoint; + private CompositeActivatorImpl compositeActivator; + + private EndpointResolver endpointResolver; + private EndpointReference source; + private RuntimeWire wire; + private InvocationChain binidngInvocationChain; + + /** + * @param endpoint + */ + public EndpointWireImpl(Endpoint endpoint, CompositeActivator compositeActivator) { + super(); + this.endpoint = endpoint; + // TODO - improve the SPI to get rid of this cast + this.compositeActivator = (CompositeActivatorImpl)compositeActivator; + + // store source configuration as we have most of this now. We don't though know what the + // target is yet. + Reference componentTypeRef = endpoint.getSourceComponentReference().getReference(); + InterfaceContract sourceContract = + componentTypeRef == null ? endpoint.getSourceComponentReference().getInterfaceContract() : componentTypeRef.getInterfaceContract(); + sourceContract = sourceContract.makeUnidirectional(false); + + source = new EndpointReferenceImpl((RuntimeComponent)endpoint.getSourceComponent(), + endpoint.getSourceComponentReference(), + null, + sourceContract); + + RuntimeComponentReference runtimeRef = ((RuntimeComponentReference)endpoint.getSourceComponentReference()); + endpointResolver = runtimeRef.getEndpointResolver(endpoint); + + } + + public synchronized List<InvocationChain> getInvocationChains() { + // where late binding happens. Find the endpoint provider and + // ask it to do the endpoint resolution. + if (endpoint.isUnresolved()){ + + // this method should locate a viable target service and complete the + // endpoint configuration + endpointResolver.resolve(); + + if (endpoint.isUnresolved()){ + throw new ServiceUnavailableException("Unable to resolve service for component: " + + endpoint.getSourceComponent().getName() + + " reference: " + + endpoint.getSourceComponentReference().getName() + + " target: " + + endpoint.getTargetName()); + } + } + + if (wire == null){ + RuntimeComponentReference runtimeRef = ((RuntimeComponentReference)endpoint.getSourceComponentReference()); + + // add the resolved binding into the reference + runtimeRef.getBindings().add(endpoint.getSourceBinding()); + + // add a binding provider into the reference for the resolved binding + compositeActivator.addReferenceBindingProviderForEndpoint(endpoint); + + // extract the binding provider that has been created + ReferenceBindingProvider bindingProvider = runtimeRef.getBindingProvider(endpoint.getSourceBinding()); + + // start the binding provider + bindingProvider.start(); + + // create the wire + compositeActivator.addReferenceWireForEndpoint(endpoint); + + // extract the wire that has been created + wire = runtimeRef.getRuntimeWire(endpoint.getSourceBinding()); + } + + return wire.getInvocationChains(); + } + + public InvocationChain getInvocationChain(Operation operation) { + if (wire ==null){ + return null; + } else { + return wire.getInvocationChain(operation); + } + } + + public Object invoke(Message msg) throws InvocationTargetException { + // not called as the endpoint wire only appears on the reference side + return null; + } + + public Object invoke(Operation operation, Object[] args) throws InvocationTargetException { + // not called as the endpoint wire only appears on the reference side + return null; + } + + public Object invoke(Operation operation, Message msg) throws InvocationTargetException { + // not called as the endpoint wire only appears on the reference side + return null; + } + + + public EndpointReference getSource() { + return source; + } + + public EndpointReference getTarget() { + return null; + } + + public void setTarget(EndpointReference target) { + } + + public void rebuild() { + } + + public synchronized InvocationChain getBindingInvocationChain() { + if (binidngInvocationChain == null) { + if (source instanceof RuntimeComponentReference) { + binidngInvocationChain = new InvocationChainImpl(null, null, true); + } else { + binidngInvocationChain = new InvocationChainImpl(null, null, false); + } + } + return binidngInvocationChain; + } + + // TODO: TUSCANY-2580: give RuntimeComponentReferenceImpl a way to get at the endpoint + public Endpoint getEndpoint() { + return endpoint; + } + + /** + * @see java.lang.Object#clone() + */ + @Override + public Object clone() throws CloneNotSupportedException { + EndpointWireImpl copy = (EndpointWireImpl)super.clone(); + return copy; + } +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/assembly/ReferenceParameterProcessor.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/assembly/ReferenceParameterProcessor.java new file mode 100644 index 0000000000..c82543c4ca --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/assembly/ReferenceParameterProcessor.java @@ -0,0 +1,101 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core.assembly; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; + +import org.apache.tuscany.sca.contribution.ModelFactoryExtensionPoint; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.contribution.service.ContributionReadException; +import org.apache.tuscany.sca.contribution.service.ContributionResolveException; +import org.apache.tuscany.sca.contribution.service.ContributionWriteException; +import org.apache.tuscany.sca.monitor.Monitor; +import org.apache.tuscany.sca.runtime.ReferenceParameters; + +/** + * Artifact processor for reference parameters. + * + * @version $Rev$ $Date$ + */ +public class ReferenceParameterProcessor implements StAXArtifactProcessor<ReferenceParameters> { + private static final QName REFERENCE_PARAMETERS = + new QName("http://tuscany.apache.org/xmlns/sca/1.0", "referenceParameters", "tuscany"); + + /** + * Constructs a new processor. + * + * @param modelFactories + */ + public ReferenceParameterProcessor(ModelFactoryExtensionPoint modelFactories, Monitor monitor) { + } + + /** + * @see org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor#getArtifactType() + */ + public QName getArtifactType() { + return REFERENCE_PARAMETERS; + } + + /** + * @see org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor#read(javax.xml.stream.XMLStreamReader) + */ + public ReferenceParameters read(XMLStreamReader reader) throws ContributionReadException, XMLStreamException { + ReferenceParameters parameters = new ReferenceParametersImpl(); + parameters.setConversationID(reader.getAttributeValue(null, "conversationID")); + parameters.setCallbackID(reader.getAttributeValue(null, "callbackID")); + return parameters; + } + + /** + * @see org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor#write(java.lang.Object, javax.xml.stream.XMLStreamWriter) + */ + public void write(ReferenceParameters model, XMLStreamWriter writer) throws ContributionWriteException, + XMLStreamException { + writer.writeStartElement(REFERENCE_PARAMETERS.getPrefix(), + REFERENCE_PARAMETERS.getLocalPart(), + REFERENCE_PARAMETERS.getNamespaceURI()); + writer.writeNamespace(REFERENCE_PARAMETERS.getPrefix(), REFERENCE_PARAMETERS.getNamespaceURI()); + if (model.getConversationID() != null) { + writer.writeAttribute("conversationID", model.getConversationID().toString()); + } + if (model.getCallbackID() != null) { + writer.writeAttribute("callbackID", model.getCallbackID().toString()); + } + writer.writeEndElement(); + } + + /** + * @see org.apache.tuscany.sca.contribution.processor.ArtifactProcessor#getModelType() + */ + public Class<ReferenceParameters> getModelType() { + return ReferenceParameters.class; + } + + /** + * @see org.apache.tuscany.sca.contribution.processor.ArtifactProcessor#resolve(java.lang.Object, org.apache.tuscany.sca.contribution.resolver.ModelResolver) + */ + public void resolve(ReferenceParameters model, ModelResolver resolver) throws ContributionResolveException { + } + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/assembly/ReferenceParametersImpl.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/assembly/ReferenceParametersImpl.java new file mode 100644 index 0000000000..14a5f565fc --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/assembly/ReferenceParametersImpl.java @@ -0,0 +1,139 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core.assembly; + +import org.apache.tuscany.sca.runtime.EndpointReference; +import org.apache.tuscany.sca.runtime.ReferenceParameters; + +/** + * @version $Rev$ $Date$ + */ +public class ReferenceParametersImpl implements ReferenceParameters { + private Object callbackID; + private Object conversationID; + private EndpointReference callbackReference; + private Object callbackObjectID; + + /** + * @return the callbackID + */ + public Object getCallbackID() { + return callbackID; + } + /** + * @param callbackID the callbackID to set + */ + public void setCallbackID(Object callbackID) { + this.callbackID = callbackID; + } + /** + * @return the conversationID + */ + public Object getConversationID() { + return conversationID; + } + /** + * @param conversationID the conversationID to set + */ + public void setConversationID(Object conversationID) { + this.conversationID = conversationID; + } + + /** + * @see org.apache.tuscany.sca.runtime.ReferenceParameters#getCallbackReference() + */ + public EndpointReference getCallbackReference() { + return callbackReference; + } + /** + * @see org.apache.tuscany.sca.runtime.ReferenceParameters#setCallback(java.lang.Object) + */ + public void setCallbackReference(EndpointReference callback) { + this.callbackReference = callback; + } + + /** + * @see java.lang.Object#clone() + */ + @Override + public Object clone() throws CloneNotSupportedException { + return super.clone(); + } + + /** + * @return the callbackObjectID + */ + public Object getCallbackObjectID() { + return callbackObjectID; + } + /** + * @param callbackObjectID the callbackObjectID to set + */ + public void setCallbackObjectID(Object callbackObjectID) { + this.callbackObjectID = callbackObjectID; + } + /** + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((callbackID == null) ? 0 : callbackID.hashCode()); + result = prime * result + ((callbackObjectID == null) ? 0 : callbackObjectID.hashCode()); + result = prime * result + ((callbackReference == null) ? 0 : callbackReference.hashCode()); + result = prime * result + ((conversationID == null) ? 0 : conversationID.hashCode()); + return result; + } + /** + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (!(obj instanceof ReferenceParametersImpl)) + return false; + final ReferenceParametersImpl other = (ReferenceParametersImpl)obj; + if (callbackID == null) { + if (other.callbackID != null) + return false; + } else if (!callbackID.equals(other.callbackID)) + return false; + if (callbackObjectID == null) { + if (other.callbackObjectID != null) + return false; + } else if (!callbackObjectID.equals(other.callbackObjectID)) + return false; + if (callbackReference == null) { + if (other.callbackReference != null) + return false; + } else if (!callbackReference.equals(other.callbackReference)) + return false; + if (conversationID == null) { + if (other.conversationID != null) + return false; + } else if (!conversationID.equals(other.conversationID)) + return false; + return true; + } +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/assembly/RuntimeAssemblyFactory.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/assembly/RuntimeAssemblyFactory.java new file mode 100644 index 0000000000..b174dea6ce --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/assembly/RuntimeAssemblyFactory.java @@ -0,0 +1,53 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core.assembly; + +import org.apache.tuscany.sca.assembly.AssemblyFactory; +import org.apache.tuscany.sca.assembly.Component; +import org.apache.tuscany.sca.assembly.ComponentReference; +import org.apache.tuscany.sca.assembly.ComponentService; +import org.apache.tuscany.sca.assembly.DefaultAssemblyFactory; + +/** + * The runtime version of assembly factory + * @version $Rev$ $Date$ + */ +public class RuntimeAssemblyFactory extends DefaultAssemblyFactory implements AssemblyFactory { + + public RuntimeAssemblyFactory() { + super(); + } + + @Override + public Component createComponent() { + return new RuntimeComponentImpl(); + } + + @Override + public ComponentReference createComponentReference() { + return new RuntimeComponentReferenceImpl(); + } + + @Override + public ComponentService createComponentService() { + return new RuntimeComponentServiceImpl(); + } + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/assembly/RuntimeComponentImpl.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/assembly/RuntimeComponentImpl.java new file mode 100644 index 0000000000..32ac611e54 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/assembly/RuntimeComponentImpl.java @@ -0,0 +1,111 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core.assembly; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.tuscany.sca.assembly.impl.ComponentImpl; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.contribution.resolver.ResolverExtension; +import org.apache.tuscany.sca.core.scope.ScopeContainer; +import org.apache.tuscany.sca.core.scope.ScopedRuntimeComponent; +import org.apache.tuscany.sca.provider.ImplementationProvider; +import org.apache.tuscany.sca.provider.PolicyProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentContext; + +/** + * @version $Rev$ $Date$ + */ +public class RuntimeComponentImpl extends ComponentImpl implements RuntimeComponent, + ScopedRuntimeComponent, ResolverExtension { + protected RuntimeComponentContext componentContext; + protected ImplementationProvider implementationProvider; + protected List<PolicyProvider> policyProviders = new ArrayList<PolicyProvider>(); + protected ScopeContainer scopeContainer; + protected boolean started; + protected ModelResolver modelResolver; + + /** + */ + public RuntimeComponentImpl() { + super(); + } + + public ImplementationProvider getImplementationProvider() { + return implementationProvider; + } + + public void setImplementationProvider(ImplementationProvider provider) { + this.implementationProvider = provider; + } + + public ScopeContainer getScopeContainer() { + return scopeContainer; + } + + public void setScopeContainer(ScopeContainer scopeContainer) { + this.scopeContainer = scopeContainer; + } + + public boolean isStarted() { + return started; + } + + public void setStarted(boolean started) { + this.started = started; + } + + /** + * @return the componentContext + */ + public RuntimeComponentContext getComponentContext() { + return componentContext; + } + + /** + * @param componentContext the componentContext to set + */ + public void setComponentContext(RuntimeComponentContext componentContext) { + this.componentContext = componentContext; + } + + public void addPolicyProvider(PolicyProvider policyProvider) { + policyProviders.add(policyProvider); + } + + public List<PolicyProvider> getPolicyProviders() { + return policyProviders; + } + + public ModelResolver getModelResolver() { + return modelResolver; + } + + public void setModelResolver(ModelResolver modelResolver) { + this.modelResolver = modelResolver; + } + + @Override + public String toString() { + return getName(); + } +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/assembly/RuntimeComponentReferenceImpl.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/assembly/RuntimeComponentReferenceImpl.java new file mode 100644 index 0000000000..b386495a08 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/assembly/RuntimeComponentReferenceImpl.java @@ -0,0 +1,155 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core.assembly; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.assembly.Endpoint; +import org.apache.tuscany.sca.assembly.impl.ComponentReferenceImpl; +import org.apache.tuscany.sca.endpointresolver.EndpointResolver; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.InvocationChain; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.provider.PolicyProvider; +import org.apache.tuscany.sca.provider.ReferenceBindingProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.apache.tuscany.sca.runtime.RuntimeWire; + +/** + * Implementation of a Component Reference. + * + * @version $Rev$ $Date$ + */ +public class RuntimeComponentReferenceImpl extends ComponentReferenceImpl implements RuntimeComponentReference { + private ArrayList<RuntimeWire> wires; + private HashMap<Binding, ReferenceBindingProvider> bindingProviders = + new HashMap<Binding, ReferenceBindingProvider>(); + private HashMap<Endpoint, EndpointResolver> endpointResolvers = + new HashMap<Endpoint, EndpointResolver>(); + private HashMap<Binding, List<PolicyProvider>> policyProviders = new HashMap<Binding, List<PolicyProvider>>(); + + private RuntimeComponent component; + + public RuntimeComponentReferenceImpl() { + super(); + } + + public synchronized List<RuntimeWire> getRuntimeWires() { + if (wires == null) { + wires = new ArrayList<RuntimeWire>(); + component.getComponentContext().start(this); + } + return wires; + } + + public RuntimeWire getRuntimeWire(Binding binding) { + for (RuntimeWire wire : getRuntimeWires()) { + if (wire.getSource().getBinding() == binding) { + return wire; + } + } + + // TODO: TUSCANY-2580: before returning null see if a candidate binding matches + for (RuntimeWire wire : getRuntimeWires()) { + if (wire instanceof EndpointWireImpl) { + Endpoint endpoint = ((EndpointWireImpl)wire).getEndpoint(); + for (Binding b : endpoint.getCandidateBindings()) { + if (b == binding) { + return wire; + } + } + } + } + return null; + } + + public ReferenceBindingProvider getBindingProvider(Binding binding) { + return bindingProviders.get(binding); + } + + public void setBindingProvider(Binding binding, ReferenceBindingProvider bindingProvider) { + bindingProviders.put(binding, bindingProvider); + } + + public EndpointResolver getEndpointResolver(Endpoint endpoint){ + return endpointResolvers.get(endpoint); + } + + public void setEndpointResolver(Endpoint endpoint, EndpointResolver endpointResolver){ + endpointResolvers.put(endpoint, endpointResolver); + } + + public Invoker getInvoker(Binding binding, Operation operation) { + RuntimeWire wire = getRuntimeWire(binding); + if (wire == null) { + return null; + } + InvocationChain chain = wire.getInvocationChain(operation); + return chain == null ? null : chain.getHeadInvoker(); + } + + /** + * @return the component + */ + public RuntimeComponent getComponent() { + return component; + } + + /** + * @param component the component to set + */ + public void setComponent(RuntimeComponent component) { + this.component = component; + } + + /** + * @see org.apache.tuscany.sca.assembly.impl.ComponentReferenceImpl#clone() + */ + @Override + public Object clone() throws CloneNotSupportedException { + RuntimeComponentReferenceImpl ref = (RuntimeComponentReferenceImpl)super.clone(); + ref.wires = null; + ref.bindingProviders = new HashMap<Binding, ReferenceBindingProvider>(); + ref.policyProviders = new HashMap<Binding, List<PolicyProvider>>(); + return ref; + } + + public void addPolicyProvider(Binding binding, PolicyProvider policyProvider) { + List<PolicyProvider> providers = policyProviders.get(binding); + if (providers == null) { + providers = new ArrayList<PolicyProvider>(); + policyProviders.put(binding, providers); + } + providers.add(policyProvider); + } + + public List<PolicyProvider> getPolicyProviders(Binding binding) { + return policyProviders.get(binding); + } + + @Override + public String toString() { + return getName(); + } +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/assembly/RuntimeComponentServiceImpl.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/assembly/RuntimeComponentServiceImpl.java new file mode 100644 index 0000000000..af5230a163 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/assembly/RuntimeComponentServiceImpl.java @@ -0,0 +1,163 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core.assembly; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.assembly.impl.ComponentServiceImpl; +import org.apache.tuscany.sca.interfacedef.InterfaceContract; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.InvocationChain; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.provider.PolicyProvider; +import org.apache.tuscany.sca.provider.ServiceBindingProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; +import org.apache.tuscany.sca.runtime.RuntimeWire; +import org.osoa.sca.ServiceRuntimeException; + +/** + * Implementation of a Component Service. + * + * @version $Rev$ $Date$ + */ +public class RuntimeComponentServiceImpl extends ComponentServiceImpl implements RuntimeComponentService { + private ArrayList<RuntimeWire> wires = new ArrayList<RuntimeWire>(); + private ArrayList<RuntimeWire> callbackWires = new ArrayList<RuntimeWire>(); + private HashMap<Binding, ServiceBindingProvider> bindingProviders = new HashMap<Binding, ServiceBindingProvider>(); + private HashMap<Binding, List<PolicyProvider>> policyProviders = new HashMap<Binding, List<PolicyProvider>>(); + + public RuntimeComponentServiceImpl() { + super(); + } + + public List<RuntimeWire> getRuntimeWires() { + return wires; + } + + public RuntimeWire getRuntimeWire(Binding binding) { + for (RuntimeWire wire : wires) { + if (wire.getTarget().getBinding() == binding) { + return wire; + } + } + return null; + } + + public RuntimeWire getRuntimeWire(Binding binding, InterfaceContract interfaceContract) { + RuntimeWire wire = getRuntimeWire(binding); + if (wire == null) { + return null; + } + if (interfaceContract != null && interfaceContract != wire.getSource().getInterfaceContract()) { + try { + // FIXME: [rfeng] We could avoid clone() using a better comparison of the two interface contracts + wire = (RuntimeWire)wire.clone(); + wire.getSource().setInterfaceContract(interfaceContract); + wire.rebuild(); + } catch (CloneNotSupportedException e) { + throw new ServiceRuntimeException(e); + } + } + + return wire; + } + + public List<RuntimeWire> getCallbackWires() { + return callbackWires; + } + + public ServiceBindingProvider getBindingProvider(Binding binding) { + return bindingProviders.get(binding); + } + + public void setBindingProvider(Binding binding, ServiceBindingProvider bindingProvider) { + bindingProviders.put(binding, bindingProvider); + } + + public Invoker getInvoker(Binding binding, Operation operation) { + return getInvoker(binding, null, operation); + } + + public Invoker getInvoker(Binding binding, InterfaceContract interfaceContract, Operation operation) { + InvocationChain chain = getInvocationChain(binding, interfaceContract, operation); + if (chain != null) { + return chain.getHeadInvoker(); + } else { + return null; + } + } + + public InvocationChain getInvocationChain(Binding binding, InterfaceContract interfaceContract, Operation operation) { + RuntimeWire wire = getRuntimeWire(binding); + if (wire == null) { + return null; + } + if (interfaceContract != null && interfaceContract != wire.getSource().getInterfaceContract()) { + try { + // FIXME: [rfeng] We could avoid clone() using a better comparison of the two interface contracts + wire = (RuntimeWire)wire.clone(); + wire.getSource().setInterfaceContract(interfaceContract); + wire.rebuild(); + } catch (CloneNotSupportedException e) { + throw new ServiceRuntimeException(e); + } + } + return wire.getInvocationChain(operation); + } + + public InvocationChain getInvocationChain(Binding binding, Operation operation) { + return getInvocationChain(binding, null, operation); + } + + /** + * @see org.apache.tuscany.sca.assembly.impl.ComponentServiceImpl#clone() + */ + @SuppressWarnings("unchecked") + @Override + public Object clone() throws CloneNotSupportedException { + RuntimeComponentServiceImpl clone = (RuntimeComponentServiceImpl)super.clone(); + clone.bindingProviders = (HashMap<Binding, ServiceBindingProvider>)bindingProviders.clone(); + clone.wires = (ArrayList<RuntimeWire>)wires.clone(); + clone.callbackWires = (ArrayList<RuntimeWire>)callbackWires.clone(); + clone.policyProviders = (HashMap<Binding, List<PolicyProvider>>)policyProviders.clone(); + return clone; + } + + public void addPolicyProvider(Binding binding, PolicyProvider policyProvider) { + List<PolicyProvider> providers = policyProviders.get(binding); + if (providers == null) { + providers = new ArrayList<PolicyProvider>(); + policyProviders.put(binding, providers); + } + providers.add(policyProvider); + } + + public List<PolicyProvider> getPolicyProviders(Binding binding) { + return policyProviders.get(binding); + } + + @Override + public String toString() { + return getName(); + } +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/assembly/RuntimeWireImpl.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/assembly/RuntimeWireImpl.java new file mode 100644 index 0000000000..ad38906e9d --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/assembly/RuntimeWireImpl.java @@ -0,0 +1,459 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core.assembly; + +import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.List; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.assembly.Component; +import org.apache.tuscany.sca.assembly.ComponentReference; +import org.apache.tuscany.sca.assembly.ComponentService; +import org.apache.tuscany.sca.assembly.Contract; +import org.apache.tuscany.sca.core.conversation.ConversationManager; +import org.apache.tuscany.sca.core.invocation.InvocationChainImpl; +import org.apache.tuscany.sca.core.invocation.NonBlockingInterceptor; +import org.apache.tuscany.sca.core.invocation.RuntimeWireInvoker; +import org.apache.tuscany.sca.interfacedef.InterfaceContract; +import org.apache.tuscany.sca.interfacedef.InterfaceContractMapper; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.Interceptor; +import org.apache.tuscany.sca.invocation.InvocationChain; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.Message; +import org.apache.tuscany.sca.invocation.MessageFactory; +import org.apache.tuscany.sca.invocation.Phase; +import org.apache.tuscany.sca.provider.ImplementationProvider; +import org.apache.tuscany.sca.provider.PolicyProvider; +import org.apache.tuscany.sca.provider.ReferenceBindingProvider; +import org.apache.tuscany.sca.provider.ReferenceBindingProviderRRB; +import org.apache.tuscany.sca.provider.ServiceBindingProvider; +import org.apache.tuscany.sca.provider.ServiceBindingProviderRRB; +import org.apache.tuscany.sca.runtime.EndpointReference; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; +import org.apache.tuscany.sca.runtime.RuntimeWire; +import org.apache.tuscany.sca.runtime.RuntimeWireProcessor; +import org.apache.tuscany.sca.work.WorkScheduler; +import org.osoa.sca.ServiceRuntimeException; + +/** + * @version $Rev$ $Date$ + */ +public class RuntimeWireImpl implements RuntimeWire { + private EndpointReference wireSource; + private EndpointReference wireTarget; + + private transient RuntimeWireProcessor wireProcessor; + private transient InterfaceContractMapper interfaceContractMapper; + private transient WorkScheduler workScheduler; + private transient MessageFactory messageFactory; + private transient ConversationManager conversationManager; + private transient RuntimeWireInvoker invoker; + + // the following is a very simple cache that avoids re-cloning a wire + // when consecutive callbacks to the same endpoint are made + private EndpointReference lastCallback; + private RuntimeWire cachedWire; + private boolean wireReserved; + private RuntimeWireImpl clonedFrom; + + private List<InvocationChain> chains; + private InvocationChain bindingInvocationChain; + + /** + * @param source + * @param target + * @param interfaceContractMapper + * @param workScheduler + * @param wireProcessor + * @param messageFactory + * @param conversationManager + */ + public RuntimeWireImpl(EndpointReference source, + EndpointReference target, + InterfaceContractMapper interfaceContractMapper, + WorkScheduler workScheduler, + RuntimeWireProcessor wireProcessor, + MessageFactory messageFactory, + ConversationManager conversationManager) { + super(); + this.wireSource = source; + this.wireTarget = target; + this.interfaceContractMapper = interfaceContractMapper; + this.workScheduler = workScheduler; + this.wireProcessor = wireProcessor; + this.messageFactory = messageFactory; + this.conversationManager = conversationManager; + this.invoker = new RuntimeWireInvoker(this.messageFactory, this.conversationManager, this); + } + + public synchronized List<InvocationChain> getInvocationChains() { + if (chains == null) { + initInvocationChains(); + } + return chains; + } + + public synchronized InvocationChain getBindingInvocationChain() { + if (bindingInvocationChain == null) { + Contract source = wireSource.getContract(); + if (source instanceof RuntimeComponentReference) { + bindingInvocationChain = new InvocationChainImpl(null, null, true); + initReferenceBindingInvocationChains(); + } else { + bindingInvocationChain = new InvocationChainImpl(null, null, false); + initServiceBindingInvocationChains(); + } + } + return bindingInvocationChain; + } + + public InvocationChain getInvocationChain(Operation operation) { + for (InvocationChain chain : getInvocationChains()) { + Operation op = null; + if (wireSource.getContract() != null) { + // Reference chain + op = chain.getSourceOperation(); + } else { + // Service chain + op = chain.getTargetOperation(); + } + if (interfaceContractMapper.isCompatible(operation, op, op.getInterface().isRemotable())) { + return chain; + } + } + return null; + } + + public Object invoke(Message msg) throws InvocationTargetException { + return getBindingInvocationChain().getHeadInvoker().invoke(msg); + } + + public Object invoke(Operation operation, Object[] args) throws InvocationTargetException { + Message msg = messageFactory.createMessage(); + msg.setBody(args); + return invoker.invoke(operation, msg); + } + + public Object invoke(Operation operation, Message msg) throws InvocationTargetException { + return invoker.invoke(operation, msg); + } + + /** + * Initialize the invocation chains + */ + private void initInvocationChains() { + chains = new ArrayList<InvocationChain>(); + InterfaceContract sourceContract = wireSource.getInterfaceContract(); + InterfaceContract targetContract = wireTarget.getInterfaceContract(); + + Contract source = wireSource.getContract(); + if (source instanceof RuntimeComponentReference) { + // It's the reference wire + RuntimeComponentReference reference = (RuntimeComponentReference)wireSource.getContract(); + Binding refBinding = wireSource.getBinding(); + for (Operation operation : sourceContract.getInterface().getOperations()) { + Operation targetOperation = interfaceContractMapper.map(targetContract.getInterface(), operation); + if (targetOperation == null) { + throw new ServiceRuntimeException("No matching operation for " + operation.getName() + + " is found in reference " + + wireSource.getComponent().getURI() + + "#" + + reference.getName()); + } + InvocationChain chain = new InvocationChainImpl(operation, targetOperation, true); + if (operation.isNonBlocking()) { + addNonBlockingInterceptor(reference, refBinding, chain); + } + addReferenceBindingInterceptor(reference, refBinding, chain, operation); + chains.add(chain); + } + + } else { + // It's the service wire + RuntimeComponentService service = (RuntimeComponentService)wireTarget.getContract(); + RuntimeComponent serviceComponent = wireTarget.getComponent(); + Binding serviceBinding = wireTarget.getBinding(); + for (Operation operation : sourceContract.getInterface().getOperations()) { + Operation targetOperation = interfaceContractMapper.map(targetContract.getInterface(), operation); + if (targetOperation == null) { + throw new ServiceRuntimeException("No matching operation for " + operation.getName() + + " is found in service " + + serviceComponent.getURI() + + "#" + + service.getName()); + } + InvocationChain chain = new InvocationChainImpl(operation, targetOperation, false); + if (operation.isNonBlocking()) { + addNonBlockingInterceptor(service, serviceBinding, chain); + } + addServiceBindingInterceptor(service, serviceBinding, chain, operation); + addImplementationInterceptor(serviceComponent, service, chain, targetOperation); + chains.add(chain); + } + + } + wireProcessor.process(this); + } + + private void initReferenceBindingInvocationChains() { + RuntimeComponentReference reference = (RuntimeComponentReference)wireSource.getContract(); + Binding referenceBinding = wireSource.getBinding(); + + // add the binding interceptors to the reference binding wire + ReferenceBindingProvider provider = reference.getBindingProvider(referenceBinding); + if ((provider != null) && + (provider instanceof ReferenceBindingProviderRRB)){ + ((ReferenceBindingProviderRRB)provider).configureBindingChain(this); + } + + // add the policy interceptors to the service binding wire + // find out which policies are active + List<PolicyProvider> pps = ((RuntimeComponentReference)reference).getPolicyProviders(referenceBinding); + if (pps != null) { + for (PolicyProvider p : pps) { + if (p.getPhase().equals(Phase.REFERENCE_BINDING_POLICY)) { + Interceptor interceptor = p.createInterceptor(null); + if (interceptor != null) { + bindingInvocationChain.addInterceptor(Phase.REFERENCE_BINDING_POLICY, interceptor); + } + } + } + } + } + + private void initServiceBindingInvocationChains() { + RuntimeComponentService service = (RuntimeComponentService)wireTarget.getContract(); + Binding serviceBinding = wireTarget.getBinding(); + + // add the binding interceptors to the service binding wire + ServiceBindingProvider provider = service.getBindingProvider(serviceBinding); + if ((provider != null) && + (provider instanceof ServiceBindingProviderRRB)){ + ((ServiceBindingProviderRRB)provider).configureBindingChain(this); + } + + // add the policy interceptors to the service binding wire + List<PolicyProvider> pps = ((RuntimeComponentService)service).getPolicyProviders(serviceBinding); + if (pps != null) { + for (PolicyProvider p : pps) { + if (p.getPhase().equals(Phase.SERVICE_BINDING_POLICY)) { + Interceptor interceptor = p.createInterceptor(null); + if (interceptor != null) { + bindingInvocationChain.addInterceptor(Phase.SERVICE_BINDING_POLICY, interceptor); + } + } + } + } + + // TODO - add something on the end of the wire to invoke the + // invocation chain. Need to split out the runtime + // wire invoker into conversation, callback interceptors etc + bindingInvocationChain.addInvoker(invoker); + + } + + public EndpointReference getSource() { + return wireSource; + } + + public EndpointReference getTarget() { + return wireTarget; + } + + public void setTarget(EndpointReference target) { + if (this.wireTarget != target) { + rebuild(); + } + this.wireTarget = target; + } + + public void rebuild() { + this.chains = null; + } + + /** + * Add the interceptor for a reference binding + * + * @param reference + * @param binding + * @param chain + * @param operation + */ + private void addReferenceBindingInterceptor(ComponentReference reference, + Binding binding, + InvocationChain chain, + Operation operation) { + ReferenceBindingProvider provider = ((RuntimeComponentReference)reference).getBindingProvider(binding); + if (provider != null) { + Invoker invoker = provider.createInvoker(operation); + if (invoker != null) { + chain.addInvoker(invoker); + } + } + List<PolicyProvider> pps = ((RuntimeComponentReference)reference).getPolicyProviders(binding); + if (pps != null) { + for (PolicyProvider p : pps) { + Interceptor interceptor = p.createInterceptor(operation); + if (interceptor != null) { + chain.addInterceptor(p.getPhase(), p.createInterceptor(operation)); + } + } + } + } + + /** + * Add the interceptor for a binding + * + * @param reference + * @param binding + * @param chain + * @param operation + */ + private void addServiceBindingInterceptor(ComponentService service, + Binding binding, + InvocationChain chain, + Operation operation) { + List<PolicyProvider> pps = ((RuntimeComponentService)service).getPolicyProviders(binding); + if (pps != null) { + for (PolicyProvider p : pps) { + Interceptor interceptor = p.createInterceptor(operation); + if (interceptor != null) { + chain.addInterceptor(p.getPhase(), p.createInterceptor(operation)); + } + } + } + } + + /** + * Add a non-blocking interceptor if the reference binding needs it + * + * @param reference + * @param binding + * @param chain + */ + private void addNonBlockingInterceptor(ComponentReference reference, Binding binding, InvocationChain chain) { + ReferenceBindingProvider provider = ((RuntimeComponentReference)reference).getBindingProvider(binding); + if (provider != null) { + boolean supportsOneWayInvocation = provider.supportsOneWayInvocation(); + if (!supportsOneWayInvocation) { + chain.addInterceptor(Phase.REFERENCE, new NonBlockingInterceptor(workScheduler)); + } + } + } + + /** + * Add a non-blocking interceptor if the service binding needs it + * + * @param service + * @param binding + * @param chain + */ + private void addNonBlockingInterceptor(ComponentService service, Binding binding, InvocationChain chain) { + ServiceBindingProvider provider = ((RuntimeComponentService)service).getBindingProvider(binding); + if (provider != null) { + if (!provider.supportsOneWayInvocation()) { + chain.addInterceptor(Phase.SERVICE, new NonBlockingInterceptor(workScheduler)); + } + } + } + + /** + * Add the interceptor for a component implementation + * + * @param component + * @param service + * @param chain + * @param operation + */ + private void addImplementationInterceptor(Component component, + ComponentService service, + InvocationChain chain, + Operation operation) { + ImplementationProvider provider = ((RuntimeComponent)component).getImplementationProvider(); + if (provider != null) { + Invoker invoker = null; + invoker = provider.createInvoker((RuntimeComponentService)service, operation); + chain.addInvoker(invoker); + } + List<PolicyProvider> pps = ((RuntimeComponent)component).getPolicyProviders(); + if (pps != null) { + for (PolicyProvider p : pps) { + Interceptor interceptor = p.createInterceptor(operation); + if (interceptor != null) { + chain.addInterceptor(p.getPhase(), p.createInterceptor(operation)); + } + } + } + } + + /** + * @see java.lang.Object#clone() + */ + @Override + public Object clone() throws CloneNotSupportedException { + RuntimeWireImpl copy = (RuntimeWireImpl)super.clone(); + copy.wireSource = (EndpointReference)wireSource.clone(); + copy.wireTarget = (EndpointReference)wireTarget.clone(); + copy.invoker = new RuntimeWireInvoker(copy.messageFactory, copy.conversationManager, copy); + copy.cachedWire = null; // TUSCANY-2630 + return copy; + } + + /** + * @return the conversationManager + */ + public ConversationManager getConversationManager() { + return conversationManager; + } + + public synchronized RuntimeWire lookupCache(EndpointReference callback) { + if (lastCallback != null && callback.getURI().equals(lastCallback.getURI()) && !wireReserved) { + wireReserved = true; + return cachedWire; + } else { + return null; + } + } + + public synchronized void addToCache(EndpointReference callback, RuntimeWire clonedWire) { + ((RuntimeWireImpl)clonedWire).setClonedFrom(this); + lastCallback = callback; + cachedWire = clonedWire; + wireReserved = true; + } + + public synchronized void releaseClonedWire(RuntimeWire wire) { + if (cachedWire == wire) { + wireReserved = false; + } + } + + public synchronized void releaseWire() { + clonedFrom.releaseClonedWire(this); + } + + private void setClonedFrom(RuntimeWireImpl wire) { + clonedFrom = wire; + } +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/context/CallableReferenceImpl.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/context/CallableReferenceImpl.java new file mode 100644 index 0000000000..fc6d7abf6a --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/context/CallableReferenceImpl.java @@ -0,0 +1,605 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.context; + +import java.io.Externalizable; +import java.io.IOException; +import java.io.ObjectInput; +import java.io.ObjectOutput; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.UUID; + +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.assembly.Component; +import org.apache.tuscany.sca.assembly.ComponentService; +import org.apache.tuscany.sca.assembly.CompositeService; +import org.apache.tuscany.sca.assembly.OptimizableBinding; +import org.apache.tuscany.sca.assembly.Reference; +import org.apache.tuscany.sca.assembly.SCABinding; +import org.apache.tuscany.sca.assembly.Service; +import org.apache.tuscany.sca.assembly.builder.BindingBuilderExtension; +import org.apache.tuscany.sca.core.assembly.CompositeActivator; +import org.apache.tuscany.sca.core.assembly.CompositeActivatorImpl; +import org.apache.tuscany.sca.core.assembly.EndpointReferenceImpl; +import org.apache.tuscany.sca.core.assembly.EndpointWireImpl; +import org.apache.tuscany.sca.core.assembly.ReferenceParametersImpl; +import org.apache.tuscany.sca.core.conversation.ConversationManager; +import org.apache.tuscany.sca.core.conversation.ConversationState; +import org.apache.tuscany.sca.core.conversation.ExtendedConversation; +import org.apache.tuscany.sca.core.factory.ObjectCreationException; +import org.apache.tuscany.sca.core.invocation.ProxyFactory; +import org.apache.tuscany.sca.interfacedef.Interface; +import org.apache.tuscany.sca.interfacedef.InterfaceContract; +import org.apache.tuscany.sca.interfacedef.java.JavaInterface; +import org.apache.tuscany.sca.runtime.EndpointReference; +import org.apache.tuscany.sca.runtime.ReferenceParameters; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.apache.tuscany.sca.runtime.RuntimeWire; +import org.osoa.sca.CallableReference; +import org.osoa.sca.Conversation; +import org.osoa.sca.ServiceRuntimeException; + +/** + * Base class for implementations of service and callback references. + * + * @version $Rev$ $Date$ + * @param <B> the type of the business interface + */ +public class CallableReferenceImpl<B> implements CallableReference<B>, Externalizable { + static final long serialVersionUID = -521548304761848325L; + protected transient CompositeActivator compositeActivator; + protected transient ProxyFactory proxyFactory; + protected transient Class<B> businessInterface; + protected transient Object proxy; + + // if the wire targets a conversational service this holds the conversation state + protected transient ConversationManager conversationManager; + protected transient ExtendedConversation conversation; + protected transient Object conversationID; + protected Object callbackID; // The callbackID should be serializable + + protected transient RuntimeComponent component; + protected transient RuntimeComponentReference reference; + protected transient Binding binding; + + protected String scdl; + + private transient RuntimeComponentReference clonedRef; + private transient ReferenceParameters refParams; + private transient XMLStreamReader xmlReader; + + private transient RuntimeWire endpointWire; + + /* + * Public constructor for Externalizable serialization/deserialization + */ + public CallableReferenceImpl() { + super(); + } + + /* + * Public constructor for use by XMLStreamReader2CallableReference + */ + public CallableReferenceImpl(XMLStreamReader xmlReader) throws Exception { + this.xmlReader = xmlReader; + resolve(); + } + + protected CallableReferenceImpl(Class<B> businessInterface, + RuntimeComponent component, + RuntimeComponentReference reference, + Binding binding, + ProxyFactory proxyFactory, + CompositeActivator compositeActivator) { + this.proxyFactory = proxyFactory; + this.businessInterface = businessInterface; + this.component = component; + this.reference = reference; + this.binding = binding; + // FIXME: The SCA Specification is not clear how we should handle multiplicity + // for CallableReference + if (this.binding == null) { + this.binding = this.reference.getBinding(SCABinding.class); + if (this.binding == null) { + + // TODO: TUSCANY-2580: if the refernece doesn't have a binding yet then instead of NPE use a candidate one if its avaialable + if (reference.getBindings() != null && reference.getBindings().size() > 0) { + this.binding = this.reference.getBindings().get(0); + } else { + this.binding = this.reference.getEndpoints().get(0).getCandidateBindings().get(0); + if (this.reference.getEndpoints().get(0).getInterfaceContract() == null) { + this.reference.getEndpoints().get(0).setInterfaceContract(reference.getInterfaceContract()); + } + } + } + } + + // FIXME: Should we normalize the componentName/serviceName URI into an absolute SCA URI in the SCA binding? + // sca:component1/component11/component112/service1? + this.compositeActivator = compositeActivator; + this.conversationManager = this.compositeActivator.getConversationManager(); + initCallbackID(); + } + + public CallableReferenceImpl(Class<B> businessInterface, RuntimeWire wire, ProxyFactory proxyFactory) { + this.proxyFactory = proxyFactory; + this.businessInterface = businessInterface; + bind(wire); + } + + public RuntimeWire getRuntimeWire() { + try { + resolve(); + if (endpointWire != null){ + return endpointWire; + } else if (reference != null) { + return reference.getRuntimeWire(binding); + } else { + return null; + } + } catch (Exception e) { + throw new ServiceRuntimeException(e); + } + } + + protected void bind(RuntimeWire wire) { + if (wire != null) { + + if (wire instanceof EndpointWireImpl){ + endpointWire = wire; + } + this.component = wire.getSource().getComponent(); + this.reference = (RuntimeComponentReference)wire.getSource().getContract(); + this.binding = wire.getSource().getBinding(); + this.compositeActivator = ((ComponentContextImpl)component.getComponentContext()).getCompositeActivator(); + this.conversationManager = this.compositeActivator.getConversationManager(); + initCallbackID(); + } + } + + protected void initCallbackID() { + if (reference.getInterfaceContract() != null) { + if (reference.getInterfaceContract().getCallbackInterface() != null) { + this.callbackID = createCallbackID(); + } + } + } + + public B getProxy() throws ObjectCreationException { + try { + if (proxy == null) { + proxy = createProxy(); + } + return businessInterface.cast(proxy); + } catch (Exception e) { + throw new ObjectCreationException(e); + } + } + + public void setProxy(Object proxy) { + this.proxy = proxy; + } + + protected Object createProxy() throws Exception { + return proxyFactory.createProxy(this); + } + + public B getService() { + try { + resolve(); + return getProxy(); + } catch (Exception e) { + throw new ServiceRuntimeException(e); + } + } + + public Class<B> getBusinessInterface() { + try { + resolve(); + return businessInterface; + } catch (Exception e) { + throw new ServiceRuntimeException(e); + } + } + + public boolean isConversational() { + try { + resolve(); + return reference == null ? false : reference.getInterfaceContract().getInterface().isConversational(); + } catch (Exception e) { + throw new ServiceRuntimeException(e); + } + } + + public Conversation getConversation() { + try { + // resolve from XML just in case this CallableReference is the result of + // passing a CallableReference as a parameter + resolve(); + + if (conversation == null || conversation.getState() == ConversationState.ENDED) { + conversation = null; + } + return conversation; + + } catch (Exception e) { + throw new ServiceRuntimeException(e); + } + } + + public Object getCallbackID() { + try { + resolve(); + return callbackID; + } catch (Exception e) { + throw new ServiceRuntimeException(e); + } + } + + /** + * @see java.io.Externalizable#readExternal(java.io.ObjectInput) + */ + public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { + final boolean hasSCDL = in.readBoolean(); + if (hasSCDL) { + this.scdl = in.readUTF(); + } else { + this.scdl = null; + } + } + + /** + * @throws IOException + */ + private synchronized void resolve() throws Exception { + if ((scdl != null || xmlReader != null) && component == null && reference == null) { + ComponentContextHelper componentContextHelper = ComponentContextHelper.getCurrentComponentContextHelper(); + if (componentContextHelper != null) { + this.compositeActivator = ComponentContextHelper.getCurrentCompositeActivator(); + this.conversationManager = this.compositeActivator.getConversationManager(); + Component c; + if (xmlReader != null) { + c = componentContextHelper.fromXML(xmlReader); + xmlReader = null; // OK to GC this now + } else { + c = componentContextHelper.fromXML(scdl); + scdl = null; // OK to GC this now + } + this.component = (RuntimeComponent)c; + compositeActivator.configureComponentContext(this.component); + this.reference = (RuntimeComponentReference)c.getReferences().get(0); + this.reference.setComponent(this.component); + clonedRef = reference; + ReferenceParameters parameters = null; + for (Object ext : reference.getExtensions()) { + if (ext instanceof ReferenceParameters) { + parameters = (ReferenceParameters)ext; + break; + } + } + if (parameters != null) { + refParams = parameters; + this.callbackID = parameters.getCallbackID(); + attachConversation(parameters.getConversationID()); + } + + for (Binding binding : reference.getBindings()) { + if (binding instanceof OptimizableBinding) { + // Resolve the Component + final String bindingURI = binding.getURI(); + final Component targetComponent = resolveComponentURI(bindingURI); + + // Find the Service + ComponentService targetService = resolveServiceURI(bindingURI, targetComponent); + + // if the target service is a promoted service then find the + // service it promotes + if ((targetService != null) && (targetService.getService() instanceof CompositeService)) { + CompositeService compositeService = (CompositeService) targetService.getService(); + // Find the promoted component service + ComponentService promotedComponentService = getPromotedComponentService(compositeService); + if (promotedComponentService != null && !promotedComponentService.isUnresolved()) { + targetService = promotedComponentService; + } + } + + OptimizableBinding optimizableBinding = (OptimizableBinding)binding; + optimizableBinding.setTargetComponent(targetComponent); + optimizableBinding.setTargetComponentService(targetService); + if (targetService != null) { + for (Binding serviceBinding : targetService.getBindings()) { + if (serviceBinding.getClass() == binding.getClass()) { + optimizableBinding.setTargetBinding(serviceBinding); + break; + } + } + } + } + } + // FIXME: The SCA Specification is not clear how we should handle multiplicity + // for CallableReference + if (binding == null) { + binding = reference.getBinding(SCABinding.class); + if (binding == null) { + binding = reference.getBindings().get(0); + } + } + Interface i = reference.getInterfaceContract().getInterface(); + if (i instanceof JavaInterface) { + JavaInterface javaInterface = (JavaInterface)i; + if (javaInterface.isUnresolved()) { + // Allow privileged access to get ClassLoader. Requires RuntimePermission in + // security policy. + ClassLoader classLoader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() { + public ClassLoader run() { + return Thread.currentThread().getContextClassLoader(); + } + }); + javaInterface.setJavaClass(classLoader.loadClass(javaInterface.getName())); + compositeActivator.getJavaInterfaceFactory().createJavaInterface(javaInterface, + javaInterface.getJavaClass()); + //FIXME: If the interface needs XSDs to be loaded (e.g., for static SDO), + // this needs to be done here. We usually search for XSDs in the current + // contribution at resolve time. Is it possible to locate the current + // contribution at runtime? + } + this.businessInterface = (Class<B>)javaInterface.getJavaClass(); + } + if (binding instanceof BindingBuilderExtension) { + ((BindingBuilderExtension)binding).getBuilder().build(component, reference, binding, null); + } + this.proxyFactory = compositeActivator.getProxyFactory(); + } + } else { + this.compositeActivator = ComponentContextHelper.getCurrentCompositeActivator(); + if (this.compositeActivator != null) { + this.proxyFactory = this.compositeActivator.getProxyFactory(); + } + } + } + + /** + * Follow a service promotion chain down to the inner most (non composite) + * component service. + * + * @param topCompositeService + * @return + */ + private ComponentService getPromotedComponentService(CompositeService compositeService) { + ComponentService componentService = compositeService.getPromotedService(); + if (componentService != null) { + Service service = componentService.getService(); + if (componentService.getName() != null && service instanceof CompositeService) { + + // Continue to follow the service promotion chain + return getPromotedComponentService((CompositeService)service); + + } else { + + // Found a non-composite service + return componentService; + } + } else { + + // No promoted service + return null; + } + } + + /** + * @see java.io.Externalizable#writeExternal(java.io.ObjectOutput) + */ + public void writeExternal(ObjectOutput out) throws IOException { + try { + final String xml = toXMLString(); + if (xml == null) { + out.writeBoolean(false); + } else { + out.writeBoolean(true); + out.writeUTF(xml); + } + } catch (Exception e) { + // e.printStackTrace(); + throw new IOException(e.toString()); + } + } + + public String toXMLString() throws IOException { + if (reference != null) { + if (clonedRef == null) { + try { + clonedRef = (RuntimeComponentReference)reference.clone(); + } catch (CloneNotSupportedException e) { + // will not happen + } + } + if (refParams == null) { + refParams = new ReferenceParametersImpl(); + + // remove any existing reference parameters from the clone + Object toRemove = null; + for (Object extension : clonedRef.getExtensions()){ + if (extension instanceof ReferenceParameters){ + toRemove = extension; + } + } + + if (toRemove != null){ + clonedRef.getExtensions().remove(toRemove); + } + + // add the new reference parameter object + clonedRef.getExtensions().add(refParams); + } + refParams.setCallbackID(callbackID); + if (conversation != null){ + refParams.setConversationID(conversation.getConversationID()); + } + return ((CompositeActivatorImpl)compositeActivator).getComponentContextHelper() + .toXML(component, clonedRef); + } else { + return scdl; + } + } + + /** + * Create a callback id + * + * @return the callback id + */ + private String createCallbackID() { + return UUID.randomUUID().toString(); + } + + public void attachCallbackID(Object callbackID) { + this.callbackID = callbackID; + } + + public void attachConversationID(Object conversationID) { + this.conversationID = conversationID; + } + + public void attachConversation(ExtendedConversation conversation) { + this.conversation = conversation; + } + + public void attachConversation(Object conversationID) { + if (conversationID != null) { + ExtendedConversation conversation = conversationManager.getConversation(conversationID); + if (conversation == null){ + conversation = conversationManager.startConversation(conversationID); + } + this.conversation = conversation; + } else { + this.conversation = null; + } + } + + protected ReferenceParameters getReferenceParameters() { + ReferenceParameters parameters = new ReferenceParametersImpl(); + parameters.setCallbackID(callbackID); + if (getConversation() != null) { + parameters.setConversationID(conversation.getConversationID()); + } + return parameters; + } + + public EndpointReference getEndpointReference() { + try { + resolve(); + + // Use the interface contract of the reference on the component type + Reference componentTypeRef = reference.getReference(); + InterfaceContract sourceContract = + componentTypeRef == null ? reference.getInterfaceContract() : componentTypeRef.getInterfaceContract(); + sourceContract = sourceContract.makeUnidirectional(false); + EndpointReference epr = new EndpointReferenceImpl(component, reference, binding, sourceContract); + ReferenceParameters parameters = getReferenceParameters(); + epr.setReferenceParameters(parameters); + return epr; + } catch (Exception e) { + throw new ServiceRuntimeException(e); + } + } + + public XMLStreamReader getXMLReader() { + return xmlReader; + } + + /** + * Resolves the specified URI to a Component using the compositeActivator. + * There are two cases that we need to handle: + * <ul> + * <li>URI containing just Composite name(s) (i.e. no Service name specified) + * <li>URI containing Composite name(s) and a Service Name + * </ul> + * + * @param componentURI The URI of the Component to resolve + * @return The Component for the specified URI or null if not founds + */ + protected Component resolveComponentURI(String componentURI) { + // If the URI has come from a binding, it may well start with a '/'. We will need + // to remove this so we can match it to the composite names. + if (componentURI.startsWith("/")) { + componentURI = componentURI.substring(1); + } + + // First assume that we are dealing with a Component URI without a Service Name + Component component = compositeActivator.resolve(componentURI); + if (component != null) { + return component; + } + + // Perhaps we have a ComponentURI that has a ServiceName on the end of it + final int index = componentURI.lastIndexOf('/'); + if (index > -1) { + componentURI = componentURI.substring(0, index); + return compositeActivator.resolve(componentURI); + } + + // We could not resolve the Component URI + return null; + } + + /** + * Examines the Services on the specified Component and returns the Service that matches the + * specified Binding URI. + * + * @param bindingURI The Binding URI to resolve on the Component + * @param targetComponent The Component containing the Services + * @return The Service with the specified serviceName or null if no such Service found. + */ + protected ComponentService resolveServiceURI(String bindingURI, Component targetComponent) { + + ComponentService targetService = null; + + if (targetComponent != null) { + if (bindingURI.startsWith("/")) { + bindingURI = bindingURI.substring(1); + } + + final String componentURI = targetComponent.getURI(); + final String serviceName; + if (componentURI.equals(bindingURI)) { + // No service specified + serviceName = ""; + } else { + // Get the Service name from the Binding URI + serviceName = bindingURI.substring(componentURI.length() + 1); + } + + if ("".equals(serviceName)) { + targetService = ComponentContextHelper.getSingleService(targetComponent); + } else { + for (ComponentService service : targetComponent.getServices()) { + if (service.getName().equals(serviceName)) { + targetService = service; + break; + } + } + } + } + + return targetService; + } +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/context/ComponentContextHelper.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/context/ComponentContextHelper.java new file mode 100644 index 0000000000..78b0887482 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/context/ComponentContextHelper.java @@ -0,0 +1,320 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core.context; + +import java.io.IOException; +import java.io.Reader; +import java.io.StringReader; +import java.io.StringWriter; +import java.io.Writer; +import java.util.ArrayList; +import java.util.List; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLOutputFactory; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; + +import org.apache.tuscany.sca.assembly.AssemblyFactory; +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.assembly.Component; +import org.apache.tuscany.sca.assembly.ComponentReference; +import org.apache.tuscany.sca.assembly.ComponentService; +import org.apache.tuscany.sca.assembly.Composite; +import org.apache.tuscany.sca.assembly.Multiplicity; +import org.apache.tuscany.sca.assembly.OptimizableBinding; +import org.apache.tuscany.sca.assembly.Reference; +import org.apache.tuscany.sca.assembly.Service; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessorExtensionPoint; +import org.apache.tuscany.sca.core.assembly.CompositeActivator; +import org.apache.tuscany.sca.core.invocation.ThreadMessageContext; +import org.apache.tuscany.sca.interfacedef.Interface; +import org.apache.tuscany.sca.interfacedef.InterfaceContract; +import org.apache.tuscany.sca.interfacedef.InvalidInterfaceException; +import org.apache.tuscany.sca.interfacedef.java.JavaInterface; +import org.apache.tuscany.sca.interfacedef.java.JavaInterfaceFactory; +import org.apache.tuscany.sca.invocation.Message; +import org.apache.tuscany.sca.runtime.EndpointReference; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; +import org.osoa.sca.ServiceRuntimeException; + +/** + * @version $Rev$ $Date$ + */ +public class ComponentContextHelper { + + private final AssemblyFactory assemblyFactory; + private final JavaInterfaceFactory javaInterfaceFactory; + private final StAXArtifactProcessorExtensionPoint staxProcessors; + + /** + * @param assemblyFactory The factory to create assembly models + * @param processors The extension point for StAX artifact processors + */ + public ComponentContextHelper(AssemblyFactory assemblyFactory, + JavaInterfaceFactory javaInterfaceFactory, + StAXArtifactProcessorExtensionPoint processors) { + this.assemblyFactory = assemblyFactory; + this.javaInterfaceFactory = javaInterfaceFactory; + this.staxProcessors = processors; + } + + /** + * Create a self-reference for a component service + * @param component + * @param service + * @throws CloneNotSupportedException + * @throws InvalidInterfaceException + */ + public ComponentReference createSelfReference(Component component, + ComponentService service, + Class<?> businessInterface) throws CloneNotSupportedException, + InvalidInterfaceException { + ComponentReference componentReference = assemblyFactory.createComponentReference(); + componentReference.setName("$self$." + service.getName()); + for (Binding binding : service.getBindings()) { + if (binding instanceof OptimizableBinding) { + OptimizableBinding optimizableBinding = (OptimizableBinding)((OptimizableBinding)binding).clone(); + optimizableBinding.setTargetBinding(binding); + optimizableBinding.setTargetComponent(component); + optimizableBinding.setTargetComponentService(service); + componentReference.getBindings().add(optimizableBinding); + } else { + componentReference.getBindings().add(binding); + } + } + + componentReference.setCallback(service.getCallback()); + componentReference.getTargets().add(service); + componentReference.getPolicySets().addAll(service.getPolicySets()); + componentReference.getRequiredIntents().addAll(service.getRequiredIntents()); + + InterfaceContract interfaceContract = service.getInterfaceContract(); + Service componentTypeService = service.getService(); + if (componentTypeService != null && componentTypeService.getInterfaceContract() != null) { + interfaceContract = componentTypeService.getInterfaceContract(); + } + interfaceContract = getInterfaceContract(interfaceContract, businessInterface); + componentReference.setInterfaceContract(interfaceContract); + componentReference.setMultiplicity(Multiplicity.ONE_ONE); + // component.getReferences().add(componentReference); + return componentReference; + } + + /** + * @param interfaceContract + * @param businessInterface + * @return + * @throws CloneNotSupportedException + * @throws InvalidInterfaceException + */ + private InterfaceContract getInterfaceContract(InterfaceContract interfaceContract, Class<?> businessInterface) + throws CloneNotSupportedException, InvalidInterfaceException { + Interface interfaze = interfaceContract.getInterface(); + boolean compatible = false; + if (interfaze instanceof JavaInterface) { + Class<?> cls = ((JavaInterface)interfaze).getJavaClass(); + if (businessInterface.isAssignableFrom(cls)) { + compatible = true; + } + } + if (!compatible) { + // The interface is not assignable from the interface contract + interfaceContract = (InterfaceContract)interfaceContract.clone(); + interfaceContract.setInterface(javaInterfaceFactory.createJavaInterface(businessInterface)); + } + + return interfaceContract; + } + + /** + * Bind a component reference to a component service + * @param <B> + * @param businessInterface + * @param reference + * @param service + * @return + * @throws CloneNotSupportedException + * @throws InvalidInterfaceException + */ + public RuntimeComponentReference bindComponentReference(Class<?> businessInterface, + RuntimeComponentReference reference, + RuntimeComponent component, + RuntimeComponentService service) + throws CloneNotSupportedException, InvalidInterfaceException { + RuntimeComponentReference ref = (RuntimeComponentReference)reference.clone(); + InterfaceContract interfaceContract = reference.getInterfaceContract(); + Reference componentTypeReference = reference.getReference(); + if (componentTypeReference != null && componentTypeReference.getInterfaceContract() != null) { + interfaceContract = componentTypeReference.getInterfaceContract(); + } + InterfaceContract refInterfaceContract = getInterfaceContract(interfaceContract, businessInterface); + if (refInterfaceContract != interfaceContract) { + ref = (RuntimeComponentReference)reference.clone(); + ref.setInterfaceContract(interfaceContract); + } + ref.setComponent(component); + ref.getTargets().add(service); + ref.getBindings().clear(); + for (Binding binding : service.getBindings()) { + if (binding instanceof OptimizableBinding) { + OptimizableBinding optimizableBinding = (OptimizableBinding)((OptimizableBinding)binding).clone(); + optimizableBinding.setTargetBinding(binding); + optimizableBinding.setTargetComponent(component); + optimizableBinding.setTargetComponentService(service); + ref.getBindings().add(optimizableBinding); + } else { + ref.getBindings().add(binding); + } + } + return ref; + } + + public void write(Component component, ComponentReference reference, Writer writer) throws IOException { + write(component, reference, null, writer); + } + + public void write(Component component, ComponentReference reference, ComponentService service, Writer writer) throws IOException { + try { + StAXArtifactProcessor<Composite> processor = staxProcessors.getProcessor(Composite.class); + Composite composite = assemblyFactory.createComposite(); + composite.setName(new QName("http://tuscany.apache.org/xmlns/sca/1.0", "default")); + Component comp = assemblyFactory.createComponent(); + comp.setName("default"); + comp.setURI(component.getURI()); + composite.getComponents().add(comp); + if (reference != null) { + comp.getReferences().add(reference); + } + if (service != null) { + comp.getServices().add(service); + } + + XMLOutputFactory outputFactory = XMLOutputFactory.newInstance(); + XMLStreamWriter streamWriter = outputFactory.createXMLStreamWriter(writer); + processor.write(composite, streamWriter); + } catch (Exception e) { + throw new IOException(e.getMessage()); + } + } + + public String toXML(Component component, ComponentReference reference) throws IOException { + StringWriter writer = new StringWriter(); + write(component, reference, writer); + return writer.toString(); + } + + public String toXML(Component component, ComponentService service) throws IOException { + StringWriter writer = new StringWriter(); + write(component, null, service, writer); + return writer.toString(); + } + + public RuntimeComponent read(Reader reader) throws IOException { + try { + XMLInputFactory inputFactory = XMLInputFactory.newInstance(); + XMLStreamReader streamReader = inputFactory.createXMLStreamReader(reader); + return read(streamReader); + } catch (Exception e) { + throw new IOException(e.getMessage()); + } + } + + public RuntimeComponent read(XMLStreamReader streamReader) throws IOException { + try { + StAXArtifactProcessor<Composite> processor = staxProcessors.getProcessor(Composite.class); + Composite composite = processor.read(streamReader); + RuntimeComponent component = (RuntimeComponent)composite.getComponents().get(0); + return component; + } catch (Exception e) { + throw new IOException(e.getMessage()); + } + } + + public Component fromXML(String xml) throws IOException { + return read(new StringReader(xml)); + } + + public Component fromXML(XMLStreamReader streamReader) throws IOException { + return read(streamReader); + } + + public static RuntimeComponent getCurrentComponent() { + Message message = ThreadMessageContext.getMessageContext(); + if (message != null) { + EndpointReference to = message.getTo(); + if (to == null) { + return null; + } + RuntimeComponent component = message.getTo().getComponent(); + return component; + } + return null; + } + + public static CompositeActivator getCurrentCompositeActivator() { + RuntimeComponent component = getCurrentComponent(); + if (component != null) { + ComponentContextImpl context = (ComponentContextImpl)component.getComponentContext(); + return context.getCompositeActivator(); + } + return null; + } + + public static ComponentContextHelper getCurrentComponentContextHelper() { + CompositeActivator activator = getCurrentCompositeActivator(); + if (activator != null) { + return activator.getComponentContextHelper(); + } + return null; + } + + /** + * @param component + */ + public static ComponentService getSingleService(Component component) { + ComponentService targetService; + List<ComponentService> services = component.getServices(); + List<ComponentService> regularServices = new ArrayList<ComponentService>(); + for (ComponentService service : services) { + if (service.isCallback()) { + continue; + } + String name = service.getName(); + if (!name.startsWith("$") || name.startsWith("$dynamic$")) { + regularServices.add(service); + } + } + if (regularServices.size() == 0) { + throw new ServiceRuntimeException("No service is declared on component " + component.getURI()); + } + if (regularServices.size() != 1) { + throw new ServiceRuntimeException("More than one service is declared on component " + component.getURI() + + ". Service name is required to get the service."); + } + targetService = regularServices.get(0); + return targetService; + } + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/context/ComponentContextImpl.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/context/ComponentContextImpl.java new file mode 100644 index 0000000000..2bcf13f679 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/context/ComponentContextImpl.java @@ -0,0 +1,452 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.context; + +import java.io.IOException; +import java.io.Reader; +import java.io.Writer; +import java.util.Collection; +import java.util.ArrayList; + +import org.apache.tuscany.sca.assembly.AssemblyFactory; +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.assembly.Component; +import org.apache.tuscany.sca.assembly.ComponentProperty; +import org.apache.tuscany.sca.assembly.ComponentReference; +import org.apache.tuscany.sca.assembly.ComponentService; +import org.apache.tuscany.sca.assembly.Multiplicity; +import org.apache.tuscany.sca.assembly.OptimizableBinding; +import org.apache.tuscany.sca.assembly.Reference; +import org.apache.tuscany.sca.assembly.Service; +import org.apache.tuscany.sca.context.PropertyValueFactory; +import org.apache.tuscany.sca.context.RequestContextFactory; +import org.apache.tuscany.sca.core.assembly.CompositeActivator; +import org.apache.tuscany.sca.core.invocation.ProxyFactory; +import org.apache.tuscany.sca.interfacedef.Interface; +import org.apache.tuscany.sca.interfacedef.InterfaceContract; +import org.apache.tuscany.sca.interfacedef.InterfaceContractMapper; +import org.apache.tuscany.sca.interfacedef.InvalidInterfaceException; +import org.apache.tuscany.sca.interfacedef.java.JavaInterface; +import org.apache.tuscany.sca.interfacedef.java.JavaInterfaceFactory; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentContext; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; +import org.osoa.sca.CallableReference; +import org.osoa.sca.RequestContext; +import org.osoa.sca.ServiceReference; +import org.osoa.sca.ServiceRuntimeException; + +/** + * Implementation of ComponentContext that delegates to a ComponentContextProvider. + * + * @version $Rev$ $Date$ + */ +public class ComponentContextImpl implements RuntimeComponentContext { + private final RuntimeComponent component; + + private final CompositeActivator compositeActivator; + private final RequestContextFactory requestContextFactory; + private final ProxyFactory proxyFactory; + private final AssemblyFactory assemblyFactory; + private final JavaInterfaceFactory javaInterfaceFactory; + + /** + * This is a reference to the PropertyValueFactory that is provided by the Implementation + * that can be used to get the value from a Property Object. + * + * @see #setPropertyValueFactory(PropertyValueFactory) + * @see #getProperty(Class, String) + */ + private PropertyValueFactory propertyFactory; + + public ComponentContextImpl(CompositeActivator compositeActivator, + AssemblyFactory assemblyFactory, + ProxyFactory proxyFactory, + InterfaceContractMapper interfaceContractMapper, + RequestContextFactory requestContextFactory, + JavaInterfaceFactory javaInterfaceFactory, + RuntimeComponent component) { + super(); + this.compositeActivator = compositeActivator; + this.assemblyFactory = assemblyFactory; + this.proxyFactory = proxyFactory; + this.requestContextFactory = requestContextFactory; + this.javaInterfaceFactory = javaInterfaceFactory; + this.component = component; + } + + public String getURI() { + return component.getURI(); + } + + public <B, R extends CallableReference<B>> R cast(B target) throws IllegalArgumentException { + return (R)proxyFactory.cast(target); + } + + public <B> B getService(Class<B> businessInterface, String referenceName) { + ServiceReference<B> serviceRef = getServiceReference(businessInterface, referenceName); + return serviceRef.getService(); + } + + public <B> ServiceReference<B> getServiceReference(Class<B> businessInterface, String referenceName) { + try { + for (ComponentReference ref : component.getReferences()) { + if (referenceName.equals(ref.getName())) { + /* ******************** Contribution for issue TUSCANY-2281 ******************** */ + Multiplicity multiplicity = ref.getMultiplicity(); + if( multiplicity == Multiplicity.ZERO_N || multiplicity == Multiplicity.ONE_N) + { + throw new IllegalArgumentException("Reference " + referenceName + " has multiplicity " + multiplicity); + } + /* ******************** Contribution for issue TUSCANY-2281 ******************** */ + + return getServiceReference(businessInterface, (RuntimeComponentReference)ref, null); + } + } + throw new ServiceRuntimeException("Reference not found: " + referenceName); + } catch (ServiceRuntimeException e) { + throw e; + } catch (Exception e) { + throw new ServiceRuntimeException(e.getMessage(), e); + } + } + + /** + * The Implementation is responsible for calling this method to set the + * PropertyValueFactory that is used to get the Property Value from + * a Tuscany Property object. + * + * @param factory The PropertyValueFactory to use + * + * @see #getProperty(Class, String) + */ + public void setPropertyValueFactory(PropertyValueFactory factory) { + propertyFactory = factory; + } + + /** + * Gets the value for the specified property with the specified type. + * + * @param type The type of the property value we are getting + * @param propertyName The name of the property we are getting + * @param B The class of the property value we are getting + * + * @throws ServiceRuntimeException If a Property for the specified propertyName + * is not found + * + * @see #setPropertyValueFactory(PropertyValueFactory) + */ + public <B> B getProperty(Class<B> type, String propertyName) { + for (ComponentProperty p : component.getProperties()) { + if (propertyName.equals(p.getName())) { + return propertyFactory.createPropertyValue(p, type); + } + } + throw new ServiceRuntimeException("Property not found: " + propertyName); + } + + public <B> ServiceReference<B> createSelfReference(Class<B> businessInterface) { + ComponentService service = ComponentContextHelper.getSingleService(component); + try { + return createSelfReference(businessInterface, service); + } catch (Exception e) { + throw new ServiceRuntimeException(e.getMessage(), e); + } + } + + public <B> ServiceReference<B> createSelfReference(Class<B> businessInterface, String serviceName) { + try { + for (ComponentService service : component.getServices()) { + if (serviceName.equals(service.getName())) { + return createSelfReference(businessInterface, service); + } + } + throw new ServiceRuntimeException("Service not found: " + serviceName); + } catch (ServiceRuntimeException e) { + throw e; + } catch (Exception e) { + throw new ServiceRuntimeException(e.getMessage(), e); + } + } + + /** + * @param <B> + * @param businessInterface + * @param service + * @return + */ + public <B> ServiceReference<B> createSelfReference(Class<B> businessInterface, ComponentService service) { + try { + RuntimeComponentReference ref = + (RuntimeComponentReference)createSelfReference(component, service, businessInterface); + ref.setComponent(component); + return getServiceReference(businessInterface, ref, null); + } catch (Exception e) { + throw new ServiceRuntimeException(e); + } + } + + public RequestContext getRequestContext() { + if (requestContextFactory != null) { + return requestContextFactory.createRequestContext(); + } else { + return new RequestContextImpl(proxyFactory); + } + } + + /** + * @param businessInterface + * @param reference + * @return + * @throws CloneNotSupportedException + * @throws InvalidInterfaceException + */ + public <B> ServiceReference<B> getServiceReference(Class<B> businessInterface, RuntimeComponentReference reference, Binding binding) { + try { + RuntimeComponentReference ref = (RuntimeComponentReference)reference; + InterfaceContract interfaceContract = reference.getInterfaceContract(); + Reference componentTypeReference = reference.getReference(); + if (componentTypeReference != null && componentTypeReference.getInterfaceContract() != null) { + interfaceContract = componentTypeReference.getInterfaceContract(); + } + InterfaceContract refInterfaceContract = getInterfaceContract(interfaceContract, businessInterface); + if (refInterfaceContract != interfaceContract) { + ref = (RuntimeComponentReference)reference.clone(); + if (interfaceContract != null) { + ref.setInterfaceContract(interfaceContract); + } else { + ref.setInterfaceContract(refInterfaceContract); + } + } + ref.setComponent(component); + return new ServiceReferenceImpl<B>(businessInterface, component, ref, binding, proxyFactory, compositeActivator); + } catch (Exception e) { + throw new ServiceRuntimeException(e); + } + } + + /** + * Bind a component reference to a component service + * @param <B> + * @param businessInterface + * @param reference + * @param service + * @return + * @throws CloneNotSupportedException + * @throws InvalidInterfaceException + */ + public <B> ServiceReference<B> getServiceReference(Class<B> businessInterface, + RuntimeComponentReference reference, + RuntimeComponent component, + RuntimeComponentService service) { + try { + RuntimeComponentReference ref = (RuntimeComponentReference)reference.clone(); + InterfaceContract interfaceContract = reference.getInterfaceContract(); + Reference componentTypeReference = reference.getReference(); + if (componentTypeReference != null && componentTypeReference.getInterfaceContract() != null) { + interfaceContract = componentTypeReference.getInterfaceContract(); + } + InterfaceContract refInterfaceContract = getInterfaceContract(interfaceContract, businessInterface); + if (refInterfaceContract != interfaceContract) { + ref = (RuntimeComponentReference)reference.clone(); + ref.setInterfaceContract(interfaceContract); + } + ref.getTargets().add(service); + ref.getBindings().clear(); + for (Binding binding : service.getBindings()) { + if (binding instanceof OptimizableBinding) { + OptimizableBinding optimizableBinding = (OptimizableBinding)((OptimizableBinding)binding).clone(); + optimizableBinding.setTargetBinding(binding); + optimizableBinding.setTargetComponent(component); + optimizableBinding.setTargetComponentService(service); + ref.getBindings().add(optimizableBinding); + } else { + ref.getBindings().add(binding); + } + } + return new ServiceReferenceImpl<B>(businessInterface, component, ref, proxyFactory, compositeActivator); + } catch (Exception e) { + throw new ServiceRuntimeException(e); + } + } + + public <B> CallableReference<B> getCallableReference(Class<B> businessInterface, + RuntimeComponent component, + RuntimeComponentService service) { + try { + if (businessInterface == null) { + InterfaceContract contract = service.getInterfaceContract(); + businessInterface = (Class<B>)((JavaInterface)contract.getInterface()).getJavaClass(); + } + RuntimeComponentReference ref = + (RuntimeComponentReference)createSelfReference(component, service, businessInterface); + ref.setComponent(component); + return new CallableReferenceImpl<B>(businessInterface, component, ref, null, proxyFactory, + compositeActivator); + } catch (Exception e) { + throw new ServiceRuntimeException(e); + } + } + + /** + * Create a self-reference for a component service + * @param component + * @param service + * @throws CloneNotSupportedException + * @throws InvalidInterfaceException + */ + private ComponentReference createSelfReference(Component component, + ComponentService service, + Class<?> businessInterface) throws CloneNotSupportedException, + InvalidInterfaceException { + ComponentReference componentReference = assemblyFactory.createComponentReference(); + componentReference.setName("$self$." + service.getName()); + for (Binding binding : service.getBindings()) { + if (binding instanceof OptimizableBinding) { + OptimizableBinding optimizableBinding = (OptimizableBinding)((OptimizableBinding)binding).clone(); + optimizableBinding.setTargetBinding(binding); + optimizableBinding.setTargetComponent(component); + optimizableBinding.setTargetComponentService(service); + componentReference.getBindings().add(optimizableBinding); + } else { + componentReference.getBindings().add(binding); + } + } + + componentReference.setCallback(service.getCallback()); + componentReference.getTargets().add(service); + componentReference.getPolicySets().addAll(service.getPolicySets()); + componentReference.getRequiredIntents().addAll(service.getRequiredIntents()); + + InterfaceContract interfaceContract = service.getInterfaceContract(); + Service componentTypeService = service.getService(); + if (componentTypeService != null && componentTypeService.getInterfaceContract() != null) { + interfaceContract = componentTypeService.getInterfaceContract(); + } + interfaceContract = getInterfaceContract(interfaceContract, businessInterface); + componentReference.setInterfaceContract(interfaceContract); + componentReference.setMultiplicity(Multiplicity.ONE_ONE); + // component.getReferences().add(componentReference); + return componentReference; + } + + /** + * @param interfaceContract + * @param businessInterface + * @return + * @throws CloneNotSupportedException + * @throws InvalidInterfaceException + */ + private InterfaceContract getInterfaceContract(InterfaceContract interfaceContract, Class<?> businessInterface) + throws CloneNotSupportedException, InvalidInterfaceException { + boolean compatible = false; + if (interfaceContract != null && interfaceContract.getInterface() != null) { + Interface interfaze = interfaceContract.getInterface(); + if (interfaze instanceof JavaInterface) { + Class<?> cls = ((JavaInterface)interfaze).getJavaClass(); + if (businessInterface.isAssignableFrom(cls)) { + compatible = true; + } + } + } + + if (!compatible) { + // The interface is not assignable from the interface contract + interfaceContract = javaInterfaceFactory.createJavaInterfaceContract(); + JavaInterface callInterface = javaInterfaceFactory.createJavaInterface(businessInterface); + interfaceContract.setInterface(callInterface); + if (callInterface.getCallbackClass() != null) { + interfaceContract.setCallbackInterface(javaInterfaceFactory.createJavaInterface(callInterface + .getCallbackClass())); + } + } + + return interfaceContract; + } + + /** + * @return the compositeActivator + */ + public CompositeActivator getCompositeActivator() { + return compositeActivator; + } + + /** + * @see org.apache.tuscany.sca.runtime.RuntimeComponentContext#start(org.apache.tuscany.sca.runtime.RuntimeComponentReference) + */ + public void start(RuntimeComponentReference reference) { + compositeActivator.start(component, reference); + } + + /** + * @see org.apache.tuscany.sca.runtime.RuntimeComponentContext#read(java.io.Reader) + */ + public RuntimeComponent read(Reader reader) throws IOException { + RuntimeComponent component = compositeActivator.getComponentContextHelper().read(reader); + compositeActivator.configureComponentContext(component); + return component; + } + + /** + * @see org.apache.tuscany.sca.runtime.RuntimeComponentContext#write(org.apache.tuscany.sca.runtime.RuntimeComponentReference, java.io.Writer) + */ + public void write(RuntimeComponentReference reference, Writer writer) throws IOException { + compositeActivator.getComponentContextHelper().write(component, reference, writer); + } + + /* ******************** Contribution for issue TUSCANY-2281 ******************** */ + + /** + * @see ComponentContext#getServices(Class<B>, String) + */ + public <B> Collection<B> getServices(Class<B> businessInterface, String referenceName) { + ArrayList<B> services = new ArrayList<B>(); + Collection<ServiceReference<B>> serviceRefs = getServiceReferences(businessInterface, referenceName); + for (ServiceReference<B> serviceRef : serviceRefs) { + services.add(serviceRef.getService()); + } + return services; + } + + /** + * @see ComponentContext#getServiceReferences(Class<B>, String) + */ + public <B> Collection<ServiceReference<B>> getServiceReferences(Class<B> businessInterface, String referenceName) { + try { + for (ComponentReference ref : component.getReferences()) { + if (referenceName.equals(ref.getName())) { + ArrayList<ServiceReference<B>> serviceRefs = new ArrayList<ServiceReference<B>>(); + for(Binding binding : ref.getBindings()) + { + serviceRefs.add( getServiceReference(businessInterface, (RuntimeComponentReference) ref, binding) ); + } + return serviceRefs; + } + } + throw new ServiceRuntimeException("Reference not found: " + referenceName); + } catch (ServiceRuntimeException e) { + throw e; + } catch (Exception e) { + throw new ServiceRuntimeException(e.getMessage(), e); + } + } + /* ******************** Contribution for issue TUSCANY-2281 ******************** */ + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/context/DefaultComponentContextFactory.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/context/DefaultComponentContextFactory.java new file mode 100644 index 0000000000..c5b68389b2 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/context/DefaultComponentContextFactory.java @@ -0,0 +1,70 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core.context; + +import org.apache.tuscany.sca.assembly.AssemblyFactory; +import org.apache.tuscany.sca.context.ComponentContextFactory; +import org.apache.tuscany.sca.context.RequestContextFactory; +import org.apache.tuscany.sca.core.assembly.CompositeActivator; +import org.apache.tuscany.sca.core.invocation.ProxyFactory; +import org.apache.tuscany.sca.interfacedef.InterfaceContractMapper; +import org.apache.tuscany.sca.interfacedef.java.JavaInterfaceFactory; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.osoa.sca.ComponentContext; + +/** + * @version $Rev$ $Date$ + */ +public class DefaultComponentContextFactory implements ComponentContextFactory { + private final CompositeActivator compositeActivator; + private final RequestContextFactory requestContextFactory; + private final ProxyFactory proxyFactory; + private final AssemblyFactory assemblyFactory; + private final JavaInterfaceFactory javaInterfaceFactory; + private final InterfaceContractMapper interfaceContractMapper; + + public DefaultComponentContextFactory(CompositeActivator compositeActivator, + AssemblyFactory assemblyFactory, + ProxyFactory proxyFactory, + InterfaceContractMapper interfaceContractMapper, + RequestContextFactory requestContextFactory, + JavaInterfaceFactory javaInterfaceFactory) { + super(); + this.compositeActivator = compositeActivator; + this.assemblyFactory = assemblyFactory; + this.proxyFactory = proxyFactory; + this.requestContextFactory = requestContextFactory; + this.javaInterfaceFactory = javaInterfaceFactory; + this.interfaceContractMapper = interfaceContractMapper; + } + + /** + * @see org.apache.tuscany.sca.context.ComponentContextFactory#createComponentContext(org.apache.tuscany.sca.runtime.RuntimeComponent, org.apache.tuscany.sca.context.RequestContextFactory) + */ + public ComponentContext createComponentContext(RuntimeComponent component, + RequestContextFactory requestContextFactory) { + if (requestContextFactory == null) { + requestContextFactory = this.requestContextFactory; + } + return new ComponentContextImpl(compositeActivator, assemblyFactory, proxyFactory, interfaceContractMapper, + requestContextFactory, javaInterfaceFactory, component); + } + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/context/InstanceWrapper.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/context/InstanceWrapper.java new file mode 100644 index 0000000000..b577180291 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/context/InstanceWrapper.java @@ -0,0 +1,48 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.context; + +import org.apache.tuscany.sca.core.scope.TargetDestructionException; +import org.apache.tuscany.sca.core.scope.TargetInitializationException; + + +/** + * Provides lifecycle management for an implementation instance associated with + * a component for use by the component's associated {@link org.apache.tuscany.sca.core.scope.ScopeContainer} + * + * @version $Rev$ $Date$ + */ +public interface InstanceWrapper<T> { + + /** + * @return + */ + T getInstance(); + + /** + * @throws TargetInitializationException + */ + void start() throws TargetInitializationException; + + /** + * @throws TargetDestructionException + */ + void stop() throws TargetDestructionException; + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/context/RequestContextImpl.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/context/RequestContextImpl.java new file mode 100644 index 0000000000..ed6c3df8fa --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/context/RequestContextImpl.java @@ -0,0 +1,113 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.context; + +import java.util.List; + +import javax.security.auth.Subject; + +import org.apache.tuscany.sca.core.invocation.CallbackReferenceImpl; +import org.apache.tuscany.sca.core.invocation.ProxyFactory; +import org.apache.tuscany.sca.core.invocation.ThreadMessageContext; +import org.apache.tuscany.sca.interfacedef.java.JavaInterface; +import org.apache.tuscany.sca.invocation.Message; +import org.apache.tuscany.sca.runtime.EndpointReference; +import org.apache.tuscany.sca.runtime.ReferenceParameters; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; +import org.apache.tuscany.sca.runtime.RuntimeWire; +import org.osoa.sca.CallableReference; +import org.osoa.sca.RequestContext; + +/** + * @version $Rev$ $Date$ + */ +public class RequestContextImpl implements RequestContext { + + private ProxyFactory proxyFactory; + + public RequestContextImpl(ProxyFactory proxyFactory) { + this.proxyFactory = proxyFactory; + } + + public Subject getSecuritySubject() { + Subject subject = null; + + for (Object header : ThreadMessageContext.getMessageContext().getHeaders()){ + if (header instanceof Subject){ + subject = (Subject)header; + break; + } + } + return subject; + } + + public String getServiceName() { + return ThreadMessageContext.getMessageContext().getTo().getContract().getName(); + } + + @SuppressWarnings("unchecked") + public <B> CallableReference<B> getServiceReference() { + Message msgContext = ThreadMessageContext.getMessageContext(); + // FIXME: [rfeng] Is this the service reference matching the caller side? + EndpointReference to = msgContext.getTo(); + RuntimeComponentService service = (RuntimeComponentService) to.getContract(); + RuntimeComponent component = (RuntimeComponent) to.getComponent(); + + CallableReference<B> callableReference = component.getComponentContext().getCallableReference(null, component, service); + ReferenceParameters parameters = msgContext.getFrom().getReferenceParameters(); + ((CallableReferenceImpl<B>) callableReference).attachCallbackID(parameters.getCallbackID()); + ((CallableReferenceImpl<B>) callableReference).attachConversation(parameters.getConversationID()); + return callableReference; + } + + @SuppressWarnings("unchecked") + public <CB> CB getCallback() { + CallableReference<CB> cb = getCallbackReference(); + if (cb == null) { + return null; + } + return cb.getService(); + } + + @SuppressWarnings("unchecked") + public <CB> CallableReference<CB> getCallbackReference() { + Message msgContext = ThreadMessageContext.getMessageContext(); + EndpointReference to = msgContext.getTo(); + RuntimeComponentService service = (RuntimeComponentService) to.getContract(); + RuntimeComponentReference callbackReference = (RuntimeComponentReference)service.getCallbackReference(); + if (callbackReference == null) { + return null; + } + JavaInterface javaInterface = (JavaInterface) callbackReference.getInterfaceContract().getInterface(); + Class<CB> javaClass = (Class<CB>)javaInterface.getJavaClass(); + List<RuntimeWire> wires = callbackReference.getRuntimeWires(); + CallbackReferenceImpl ref = CallbackReferenceImpl.newInstance(javaClass, proxyFactory, wires); + if (ref != null) { + //ref.resolveTarget(); + ReferenceParameters parameters = msgContext.getFrom().getReferenceParameters(); + ref.attachCallbackID(parameters.getCallbackID()); + if (ref.getConversation() != null) { + ref.attachConversationID(parameters.getConversationID()); + } + } + return ref; + } +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/context/ServiceReferenceImpl.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/context/ServiceReferenceImpl.java new file mode 100644 index 0000000000..1d178421cf --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/context/ServiceReferenceImpl.java @@ -0,0 +1,133 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.context; + +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.core.assembly.CompositeActivator; +import org.apache.tuscany.sca.core.conversation.ConversationState; +import org.apache.tuscany.sca.core.invocation.ProxyFactory; +import org.apache.tuscany.sca.runtime.EndpointReference; +import org.apache.tuscany.sca.runtime.ReferenceParameters; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.apache.tuscany.sca.runtime.RuntimeWire; +import org.osoa.sca.CallableReference; +import org.osoa.sca.ServiceReference; + +/** + * Default implementation of a ServiceReference. + * + * @version $Rev$ $Date$ + * @param <B> the type of the business interface + */ +public class ServiceReferenceImpl<B> extends CallableReferenceImpl<B> implements ServiceReference<B> { + private static final long serialVersionUID = 6763709434194361540L; + + protected transient Object callback; + + /* + * Public constructor for Externalizable serialization/deserialization + */ + public ServiceReferenceImpl() { + super(); + } + + /* + * Public constructor for use by XMLStreamReader2CallableReference + */ + public ServiceReferenceImpl(XMLStreamReader xmlReader) throws Exception { + super(xmlReader); + } + + /** + * @param businessInterface + * @param wire + * @param proxyFactory + */ + public ServiceReferenceImpl(Class<B> businessInterface, RuntimeWire wire, ProxyFactory proxyFactory) { + super(businessInterface, wire, proxyFactory); + } + + public ServiceReferenceImpl(Class<B> businessInterface, + RuntimeComponent component, + RuntimeComponentReference reference, + ProxyFactory proxyFactory, + CompositeActivator compositeActivator) { + super(businessInterface, component, reference, null, proxyFactory, compositeActivator); + } + + public ServiceReferenceImpl(Class<B> businessInterface, + RuntimeComponent component, + RuntimeComponentReference reference, + Binding binding, + ProxyFactory proxyFactory, + CompositeActivator compositeActivator) { + super(businessInterface, component, reference, binding, proxyFactory, compositeActivator); + } + + public Object getConversationID() { + return conversationID; + } + + public void setConversationID(Object conversationID) throws IllegalStateException { + if (conversation == null || conversation.getState() != ConversationState.ENDED) { + this.conversationID = conversationID; + this.conversation = null; + } else { + throw new IllegalStateException("Trying to set the conversationId on a service reference but the state of the conversation " + + conversation.getConversationID() + + " is " + + conversation.getState()); + } + } + + public void setCallbackID(Object callbackID) { + this.callbackID = callbackID; + } + + public Object getCallback() { + return callback; + } + + public void setCallback(Object callback) { + if (callback != null && !(callback instanceof CallableReference)) { + //FIXME: need to check if callback object supports the callback interface + // returned by reference.getInterfaceContract().getCallbackInterface() + } + this.callback = callback; + } + + @Override + protected ReferenceParameters getReferenceParameters() { + ReferenceParameters parameters = super.getReferenceParameters(); + if (callback != null) { + if (callback instanceof ServiceReference) { + EndpointReference callbackRef = ((CallableReferenceImpl)callback).getEndpointReference(); + parameters.setCallbackReference(callbackRef); + } else { + EndpointReference callbackRef = getRuntimeWire().getSource().getCallbackEndpoint(); + parameters.setCallbackReference(callbackRef); + parameters.setCallbackObjectID(callback); + } + } + return parameters; + } +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/conversation/ConversationListener.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/conversation/ConversationListener.java new file mode 100644 index 0000000000..efa362a929 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/conversation/ConversationListener.java @@ -0,0 +1,40 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core.conversation; + +/** + * Listener for the events of a conversation + * + * @version $Rev$ $Date$ + */ +public interface ConversationListener { + /** + * The conversation is started + */ + void conversationStarted(ExtendedConversation conversation); + /** + * The conversation is ended + */ + void conversationEnded(ExtendedConversation conversation); + /** + * The conversation is expired + */ + void conversationExpired(ExtendedConversation conversation); +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/conversation/ConversationManager.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/conversation/ConversationManager.java new file mode 100644 index 0000000000..f928f91a02 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/conversation/ConversationManager.java @@ -0,0 +1,73 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core.conversation; + +/** + * The manager of conversations + * + * @version $Rev$ $Date$ + */ +public interface ConversationManager { + /** + * @param conversationID + * @return + */ + ExtendedConversation startConversation(Object conversationID); + + /** + * @param conversationID + */ + void endConversation(Object conversationID); + + /** + * @param conversationID + * @return + */ + ExtendedConversation getConversation(Object conversationID); + + /** + * @param conversationID + */ + void expireConversation(Object conversationID); + + /** + * Add a listener to this conversation + * @param listener + */ + void addListener(ConversationListener listener); + + /** + * Remove a listener from this conversation + * @param listener + */ + void removeListener(ConversationListener listener); + + /** + * @return the default max age for a conversation + */ + long getMaxAge(); + + /** + * @return the default max idle time for a conversation + */ + long getMaxIdleTime(); + + void destroy(); +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/conversation/ConversationManagerImpl.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/conversation/ConversationManagerImpl.java new file mode 100644 index 0000000000..3bea79b076 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/conversation/ConversationManagerImpl.java @@ -0,0 +1,225 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core.conversation; + +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +/** + * @version $Rev$ $Date$ + */ +public class ConversationManagerImpl implements ConversationManager { + + private List<ConversationListener> listeners = Collections.synchronizedList(new ArrayList<ConversationListener>()); + private Map<Object, ExtendedConversation> conversations = new ConcurrentHashMap<Object, ExtendedConversation>(); + + /** + * the default max age. this is set to 1 hour + */ + private static final long DEFAULT_MAX_AGE = 60 * 60 * 1000; ; + + /** + * the default max idle time. this is set to 1 hour + */ + private static final long DEFAULT_MAX_IDLE_TIME = 60 * 60 * 1000; + + /** + * the globally used max age + */ + private final long maxAge; + + /** + * the globally used max idle time + */ + private final long maxIdleTime; + + /** + * the reaper thread + */ + private final ScheduledExecutorService scheduler; + + /** + * constructor + */ + public ConversationManagerImpl() { + long mit = DEFAULT_MAX_IDLE_TIME; + long ma = DEFAULT_MAX_AGE; + + scheduler = Executors.newSingleThreadScheduledExecutor(); + + // Allow privileged access to read system property. Requires PropertyPermission in security + // policy. + String aProperty = AccessController.doPrivileged(new PrivilegedAction<String>() { + public String run() { + return System.getProperty("org.apache.tuscany.sca.core.scope.ConversationalScopeContainer.MaxIdleTime"); + } + }); + if (aProperty != null) { + try { + mit = (new Long(aProperty) * 1000); + } catch (NumberFormatException nfe) { + // Ignore + } + } + + // Allow privileged access to read system property. Requires PropertyPermission in security + // policy. + aProperty = AccessController.doPrivileged(new PrivilegedAction<String>() { + public String run() { + return System.getProperty("org.apache.tuscany.sca.core.scope.ConversationalScopeContainer.MaxAge"); + } + }); + if (aProperty != null) { + try { + ma = (new Long(aProperty) * 1000); + } catch (NumberFormatException nfe) { + // Ignore + } + } + + maxAge = ma; + maxIdleTime = mit; + } + + /** + * @see org.apache.tuscany.sca.core.conversation.ConversationManager#addListener(org.apache.tuscany.sca.core.conversation.ConversationListener) + */ + public void addListener(ConversationListener listener) { + listeners.add(listener); + } + + /** + * @see org.apache.tuscany.sca.core.conversation.ConversationManager#endConversation(org.apache.tuscany.sca.core.conversation.ExtendedConversation) + */ + public void endConversation(Object conversationID) { + ExtendedConversation conv = getConversation(conversationID); + if (conv != null) { + conv.setState(ConversationState.ENDED); + for (ConversationListener listener : listeners) { + listener.conversationEnded(conv); + } + conv.setConversationID(null); + conversations.remove(conversationID); + } else { + throw new IllegalStateException("Conversation " + conversationID + " doesn't exist."); + } + } + + public void expireConversation(Object conversationID) { + ExtendedConversation conv = getConversation(conversationID); + if (conv != null) { + for (ConversationListener listener : listeners) { + listener.conversationExpired(conv); + } + conversations.remove(conversationID); + } else { + throw new IllegalStateException("Conversation " + conversationID + " doesn't exist."); + } + + } + + /** + * @see org.apache.tuscany.sca.core.conversation.ConversationManager#getConversation(java.lang.Object) + */ + public ExtendedConversation getConversation(Object conversationID) { + // ConcurrentHashMap cannot take null key + return conversationID == null ? null : conversations.get(conversationID); + } + + /** + * @see org.apache.tuscany.sca.core.conversation.ConversationManager#removeListener(org.apache.tuscany.sca.core.conversation.ConversationListener) + */ + public void removeListener(ConversationListener listener) { + listeners.remove(listener); + } + + /** + * starts the reaper thread + */ + public void scheduleConversation(ExtendedConversationImpl aConversation, long time) + { + this.scheduler.schedule(aConversation, time, TimeUnit.MILLISECONDS); + } + + /** + * stops the reaper thread + */ + public synchronized void stopReaper() { + + // Prevent the scheduler from submitting any additional reapers, + // initiate an orderly shutdown if a reaper task is in progress. + this.scheduler.shutdown(); + } + + + /** + * @see org.apache.tuscany.sca.core.conversation.ConversationManager#startConversation(java.lang.Object) + */ + public ExtendedConversation startConversation(Object conversationID) { + + if (conversationID == null) { + conversationID = UUID.randomUUID().toString(); + } + ExtendedConversation conversation = getConversation(conversationID); + if (conversation != null && conversation.getState() != ConversationState.ENDED) { + throw new IllegalStateException(conversation + " already exists."); + } + + conversation = new ExtendedConversationImpl( + this, conversationID, ConversationState.STARTED); + conversations.put(conversationID, conversation); + for (ConversationListener listener : listeners) { + listener.conversationStarted(conversation); + } + return conversation; + } + + /** + * return the default max idle time + * @param impProvider the implementation Provider to extract any ConversationAttribute details + */ + public long getMaxIdleTime() { + return maxIdleTime; + } + + /** + * returns the default max age + * @param impProvider the implementation Provider to extract any ConversationAttribute details + */ + public long getMaxAge(){ + return maxAge; + } + + public void destroy() { + // REVIEW: A more graceful way? + scheduler.shutdownNow(); + this.listeners.clear(); + this.conversations.clear(); + } +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/conversation/ConversationState.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/conversation/ConversationState.java new file mode 100644 index 0000000000..692d6861ba --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/conversation/ConversationState.java @@ -0,0 +1,29 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core.conversation; + +/** + * The states of a conversation + * + * @version $Rev$ $Date$ + */ +public enum ConversationState { + STARTED, ENDED, EXPIRED +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/conversation/ExtendedConversation.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/conversation/ExtendedConversation.java new file mode 100644 index 0000000000..03c18c26b8 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/conversation/ExtendedConversation.java @@ -0,0 +1,66 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core.conversation; + +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.osoa.sca.Conversation; + +/** + * An extended interface over org.osoa.Conversation + * + * @version $Rev$ $Date$ + */ +public interface ExtendedConversation extends Conversation { + /** + * Get the state of a conversation + * @return The state + */ + ConversationState getState(); + + /** + * @param state the state to set + */ + void setState(ConversationState state); + + /** + * @param conversationID the conversationID to set + */ + void setConversationID(Object conversationID); + + + /** + * will check whether this conversation has expired and update state if it has + * @return true if it has expired + */ + boolean isExpired(); + + /** + * updates the last time this conversation was referenced + */ + void updateLastReferencedTime(); + + void initializeConversationAttributes(RuntimeComponent targetComponent); + + + /** + * @return true if the conversational attributes have been initialized + */ + boolean conversationalAttributesInitialized(); +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/conversation/ExtendedConversationImpl.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/conversation/ExtendedConversationImpl.java new file mode 100644 index 0000000000..0bf66b2817 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/conversation/ExtendedConversationImpl.java @@ -0,0 +1,265 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.conversation; + +import org.apache.tuscany.sca.core.scope.ScopedImplementationProvider; +import org.apache.tuscany.sca.provider.ImplementationProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponent; + + +/** + * + * @version $Rev$ $Date$ + */ +public class ExtendedConversationImpl implements ExtendedConversation, Runnable { + + private final ConversationManagerImpl manager; + private volatile Object conversationID; + private ConversationState state; + + /** + * syncs access to the state + */ + private final Object stateSync = new Object(); + + /** + * the maximum time a conversation can exist + */ + private long expirationTime = 0; + + /** + * the maximum time this conversation can be idle + */ + private long maxIdleTime = 0; + + /** + * the maximum age of this conversation + */ + private long maxAge = 0; + + /** + * the time that this object was created + */ + private long creationTime; + + /** + * the time that this object was last referenced + */ + private long lastReferencedTime; + + /** + * boolean to ensure expiry only occurs once + */ + private boolean expired = false; + + /** + * boolean to indicate if the conversation attributes have + * been set. In the case where a remote binding is used + * within a composite the JDKInvocationHandler can create the + * conversation but the conversationAttributes are not available + * until the conversation is retrieved by the RuntimeWireInvoker + */ + private boolean conversationAttributesInitialized = false; + + /** + * Constructor + * @param manager the conversation manager + * @param conversationID the conversation id associated with this conversation + * @param state the initial state of this conversation + * @param aMaxAge the maximum age of the conversation + * @param aMaxIdleTime the maximum idle time + */ + public ExtendedConversationImpl(ConversationManagerImpl manager, + Object conversationID, ConversationState state) { + super(); + + this.creationTime = System.currentTimeMillis(); + this.lastReferencedTime = creationTime; + this.manager = manager; + this.conversationID = conversationID; + this.state = state; + } + + /** + * will check whether this conversation has expired and update state if it has + * @return true if it has expired + */ + public boolean isExpired() { + long currentTime; + synchronized (stateSync) { + + // if the attributes haven't been initialized then + // this conversation object can't expire + if (conversationAttributesInitialized == false) { + return false; + } + + // check state first + if (state == ConversationState.EXPIRED) { + return true; + } + + // check whether the time is finished + currentTime = System.currentTimeMillis(); + if (((this.lastReferencedTime + this.maxIdleTime) <= currentTime) + || (this.expirationTime <= currentTime)) { + setState(ConversationState.EXPIRED); + return true; + } + } + scheduleNextExpiryTime(currentTime); + return false; + } + + /** + * schedule next expiry time + */ + public void scheduleNextExpiryTime(long currentTime) { + if ((lastReferencedTime + maxIdleTime) < expirationTime){ + manager.scheduleConversation(this, (lastReferencedTime + maxIdleTime) - currentTime); + } else { + manager.scheduleConversation(this, expirationTime - currentTime); + } + } + /** + * updates the last time this conversation was referenced + */ + public void updateLastReferencedTime() { + this.lastReferencedTime = System.currentTimeMillis(); + if (conversationAttributesInitialized == true){ + scheduleNextExpiryTime(lastReferencedTime); + } + } + + public ConversationState getState() { + synchronized (stateSync){ + return state; + } + } + + public void end() { + manager.endConversation(conversationID); + } + + public Object getConversationID() { + return conversationID; + } + + /** + * @param state the state to set + */ + public void setState(ConversationState state) { + synchronized (stateSync){ + this.state = state; + } + } + + /** + * @param conversationID the conversationID to set + */ + public void setConversationID(Object conversationID) { + synchronized (stateSync){ + if (state != ConversationState.ENDED) { + throw new IllegalStateException("The state of conversation " + conversationID + " " + state); + } + } + this.conversationID = conversationID; + } + + /** + * @param maxAge the maximum age of this conversation + */ + public void initializeConversationAttributes(RuntimeComponent targetComponent){ + if (targetComponent != null){ + this.maxAge = getMaxIdleTime(targetComponent.getImplementationProvider()); + this.maxIdleTime = getMaxAge(targetComponent.getImplementationProvider()); + this.expirationTime = creationTime + maxAge; + this.conversationAttributesInitialized = true; + } + } + + /** + * @return true if the conversational attributes have been initialized + */ + public boolean conversationalAttributesInitialized(){ + return this.conversationAttributesInitialized; + } + + /** + * return the max idle time + * @param impProvider the implementation Provider to extract any ConversationAttribute details + */ + private long getMaxIdleTime(ImplementationProvider impProvider) { + // Check to see if the maxIdleTime has been specified using @ConversationAttributes. + // Implementation annotated attributes are honoured first. + if ((impProvider != null) && + (impProvider instanceof ScopedImplementationProvider)) { + ScopedImplementationProvider aScopedImpl = + (ScopedImplementationProvider) impProvider; + + long maxIdleTime = aScopedImpl.getMaxIdleTime(); + if (maxIdleTime > 0) { + return maxIdleTime; + } + } + return manager.getMaxIdleTime(); + } + + /** + * returns the max age + * @param impProvider the implementation Provider to extract any ConversationAttribute details + */ + private long getMaxAge(ImplementationProvider impProvider){ + + // Check to see if the maxAge has been specified using @ConversationAttributes. + // Implementation annotated attributes are honoured first. + if ((impProvider != null) && + (impProvider instanceof ScopedImplementationProvider)) { + ScopedImplementationProvider aScopedImpl = + (ScopedImplementationProvider) impProvider; + + long maxAge = aScopedImpl.getMaxAge(); + if (maxAge > 0) { + return maxAge; + } + } + return manager.getMaxAge(); + } + + /** + * called when expiring + */ + public void run() { + synchronized (stateSync){ + if (!expired){ + if (isExpired()) { + expired = true; + try { + manager.expireConversation(getConversationID()); + } catch (IllegalStateException ise) { + // ignore this.. this can occur if another thread has subsequently ended + // the conversation + } + } + } + } + + } + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/event/BaseEventPublisher.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/event/BaseEventPublisher.java new file mode 100644 index 0000000000..517e5579a4 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/event/BaseEventPublisher.java @@ -0,0 +1,89 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.event; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; + +import org.apache.tuscany.sca.event.Event; +import org.apache.tuscany.sca.event.EventFilter; +import org.apache.tuscany.sca.event.EventPublisher; +import org.apache.tuscany.sca.event.RuntimeEventListener; +import org.apache.tuscany.sca.event.TrueFilter; + +/** + * Base implementation of an <code>EventPublisher</code> + * + * @version $Rev$ $Date$ + */ +public abstract class BaseEventPublisher implements EventPublisher { + protected static final EventFilter TRUE_FILTER = new TrueFilter(); + protected Map<EventFilter, List<RuntimeEventListener>> listeners; + + public void addListener(RuntimeEventListener listener) { + addListener(TRUE_FILTER, listener); + } + + public void removeListener(RuntimeEventListener listener) { + assert listener != null : "Listener cannot be null"; + synchronized (getListeners()) { + for (List<RuntimeEventListener> currentList : getListeners().values()) { + for (RuntimeEventListener current : currentList) { + if (current == listener) { + currentList.remove(current); + return; + } + } + } + } + } + + public void addListener(EventFilter filter, RuntimeEventListener listener) { + assert listener != null : "Listener cannot be null"; + synchronized (getListeners()) { + List<RuntimeEventListener> list = getListeners().get(filter); + if (list == null) { + list = new CopyOnWriteArrayList<RuntimeEventListener>(); + listeners.put(filter, list); + } + list.add(listener); + } + } + + public void publish(Event event) { + assert event != null : "Event object was null"; + for (Map.Entry<EventFilter, List<RuntimeEventListener>> entry : getListeners().entrySet()) { + if (entry.getKey().match(event)) { + for (RuntimeEventListener listener : entry.getValue()) { + listener.onEvent(event); + } + } + } + } + + protected Map<EventFilter, List<RuntimeEventListener>> getListeners() { + if (listeners == null) { + listeners = new ConcurrentHashMap<EventFilter, List<RuntimeEventListener>>(); + } + return listeners; + } + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/event/ComponentStart.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/event/ComponentStart.java new file mode 100644 index 0000000000..45eab7da1b --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/event/ComponentStart.java @@ -0,0 +1,54 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.event; + +import java.net.URI; + +import org.apache.tuscany.sca.event.Event; + +/** + * Propagated when a component starts + * + * @version $Rev$ $Date$ + */ +public class ComponentStart implements Event { + + private Object source; + private URI uri; + + /** + * Creates a component start event + * + * @param source the source of the event + * @param componentURI the URI of the component being started + */ + public ComponentStart(Object source, URI componentURI) { + this.source = source; + this.uri = componentURI; + } + + public URI getComponentURI() { + return uri; + } + + public Object getSource() { + return source; + } + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/event/ComponentStop.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/event/ComponentStop.java new file mode 100644 index 0000000000..4dc79c3844 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/event/ComponentStop.java @@ -0,0 +1,53 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.event; + +import java.net.URI; + +import org.apache.tuscany.sca.event.Event; + +/** + * Propagated when a component stops + * + * @version $Rev$ $Date$ + */ +public class ComponentStop implements Event { + + private Object source; + private URI uri; + + /** + * Creates a component stop event + * + * @param source the source of the event + * @param componentUri the composite component associated the component being stopped + */ + public ComponentStop(Object source, URI componentUri) { + this.source = source; + this.uri = componentUri; + } + + public URI getComponentURI() { + return uri; + } + + public Object getSource() { + return source; + } +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/event/ConversationEnd.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/event/ConversationEnd.java new file mode 100644 index 0000000000..d3106c7052 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/event/ConversationEnd.java @@ -0,0 +1,53 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.event; + +import org.apache.tuscany.sca.event.Event; + + + +/** + * Propagated when a conversation is expired + * + * @version $Rev$ $Date$ + */ +public class ConversationEnd implements Event { + + private Object source; + private Object id; + + /** + * Creates a new event + * + * @param source the source of the event + * @param id the id of the conversation being ended + */ + public ConversationEnd(Object source, Object id) { + this.source = source; + this.id = id; + } + + public Object getSource() { + return source; + } + + public Object getConversationID() { + return id; + } +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/event/ConversationStart.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/event/ConversationStart.java new file mode 100644 index 0000000000..123400fbdd --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/event/ConversationStart.java @@ -0,0 +1,52 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.event; + +import org.apache.tuscany.sca.event.Event; + + +/** + * Propagated when a conversation has started + * + * @version $Rev$ $Date$ + */ +public class ConversationStart implements Event { + + private Object source; + private Object id; + + /** + * Creates a new event + * + * @param source the source of the event + * @param id the id of the conversation being started + */ + public ConversationStart(Object source, Object id) { + this.source = source; + this.id = id; + } + + public Object getSource() { + return source; + } + + public Object getConversationID() { + return id; + } +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/event/HttpSessionEnd.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/event/HttpSessionEnd.java new file mode 100644 index 0000000000..68cb5c2966 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/event/HttpSessionEnd.java @@ -0,0 +1,53 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.event; + +import org.apache.tuscany.sca.event.Event; + + + +/** + * Propagated when an HTTP-based session is expired + * + * @version $Rev$ $Date$ + */ +public class HttpSessionEnd implements Event { + + private Object source; + private Object id; + + /** + * Creates a new event + * + * @param source the source of the event + * @param id the id of the HTTP session being ended + */ + public HttpSessionEnd(Object source, Object id) { + this.source = source; + this.id = id; + } + + public Object getSource() { + return source; + } + + public Object getSessionID() { + return id; + } +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/event/HttpSessionStart.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/event/HttpSessionStart.java new file mode 100644 index 0000000000..38a4fb10d6 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/event/HttpSessionStart.java @@ -0,0 +1,52 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.event; + +import org.apache.tuscany.sca.event.Event; + + +/** + * Propagated when an HTTP-based session has started + * + * @version $Rev$ $Date$ + */ +public class HttpSessionStart implements Event { + + private Object source; + private Object id; + + /** + * Creates a new event + * + * @param source the source of the event + * @param id the id of the HTTP session being started + */ + public HttpSessionStart(Object source, Object id) { + this.source = source; + this.id = id; + } + + public Object getSource() { + return source; + } + + public Object getSessionID() { + return id; + } +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/event/RequestEnd.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/event/RequestEnd.java new file mode 100644 index 0000000000..d7e797bbb9 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/event/RequestEnd.java @@ -0,0 +1,45 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.event; + +import org.apache.tuscany.sca.event.Event; + +/** + * Propagated when a request completes or is ended + * + * @version $Rev$ $Date$ + */ +public class RequestEnd implements Event { + + private Object source; + + /** + * Creates a new event + * + * @param source the source of the event + */ + public RequestEnd(Object source) { + this.source = source; + } + + public Object getSource() { + return source; + } + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/event/RequestStart.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/event/RequestStart.java new file mode 100644 index 0000000000..7530156b11 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/event/RequestStart.java @@ -0,0 +1,45 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.event; + +import org.apache.tuscany.sca.event.Event; + +/** + * Propagated when a request is started in the runtime + * + * @version $Rev$ $Date$ + */ +public class RequestStart implements Event { + + private Object source; + + /** + * Creates a new event + * + * @param source the source of the event + */ + public RequestStart(Object source) { + this.source = source; + } + + public Object getSource() { + return source; + } + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/factory/ObjectCreationException.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/factory/ObjectCreationException.java new file mode 100644 index 0000000000..d35b27fd24 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/factory/ObjectCreationException.java @@ -0,0 +1,47 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.factory; + + +/** + * Denotes an error creating a new object instance + * + * @version $Rev$ $Date$ + */ +public class ObjectCreationException extends RuntimeException { + private static final long serialVersionUID = -6423113430265944499L; + + public ObjectCreationException() { + super(); + } + + public ObjectCreationException(String message, Throwable cause) { + super(message, cause); + } + + public ObjectCreationException(String message) { + super(message); + } + + public ObjectCreationException(Throwable cause) { + super(cause); + } + +} + diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/factory/ObjectFactory.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/factory/ObjectFactory.java new file mode 100644 index 0000000000..3f64d2405b --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/factory/ObjectFactory.java @@ -0,0 +1,35 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.factory; + +/** + * Implementations create new instances of a particular type + * + * @version $Rev$ $Date$ + */ +public interface ObjectFactory<T> { + + /** + * Return a instance of the type that this factory creates. + * + * @return a instance from this factory + */ + T getInstance() throws ObjectCreationException; + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/CallableReferenceObjectFactory.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/CallableReferenceObjectFactory.java new file mode 100644 index 0000000000..588c43b8b1 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/CallableReferenceObjectFactory.java @@ -0,0 +1,63 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.invocation; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.core.factory.ObjectCreationException; +import org.apache.tuscany.sca.core.factory.ObjectFactory; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.osoa.sca.CallableReference; + +/** + * Uses a wire to return a CallableReference + * + * @version $Rev$ $Date$ + */ +public class CallableReferenceObjectFactory implements ObjectFactory<CallableReference<?>> { + private Class<?> businessInterface; + private RuntimeComponent component; + private RuntimeComponentReference reference; + private Binding binding; + + /** + * Constructor. + * + * To support the @Reference protected CallableReference<MyService> ref; + * + * @param businessInterface the interface to inject + * @param component the component defining the reference to be injected + * @param reference the reference to be injected + * @param binding the binding for the reference + */ + public CallableReferenceObjectFactory(Class<?> businessInterface, + RuntimeComponent component, + RuntimeComponentReference reference, + Binding binding) { + this.businessInterface = businessInterface; + this.component = component; + this.reference = reference; + this.binding = binding; + } + + public CallableReference<?> getInstance() throws ObjectCreationException { + return component.getComponentContext().getServiceReference(businessInterface, reference, binding); + } + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/CallbackInterfaceInterceptor.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/CallbackInterfaceInterceptor.java new file mode 100644 index 0000000000..d19aa237cd --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/CallbackInterfaceInterceptor.java @@ -0,0 +1,57 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.invocation; + +import org.apache.tuscany.sca.invocation.Interceptor; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.Message; +import org.apache.tuscany.sca.runtime.ReferenceParameters; +import org.osoa.sca.NoRegisteredCallbackException; + +/** + * An interceptor applied to the forward direction of a wire that ensures the callback target implements the required + * service contract. This is required as callback targets may be set dynamically by service implementations. + * + * @version $Rev$ $Date$ + */ +public class CallbackInterfaceInterceptor implements Interceptor { + private Invoker next; + + public CallbackInterfaceInterceptor() { + } + + public Message invoke(Message msg) { + ReferenceParameters parameters = msg.getFrom().getReferenceParameters(); + if (parameters.getCallbackObjectID() != null || parameters.getCallbackReference() != msg.getFrom() + .getCallbackEndpoint()) { + return next.invoke(msg); + } else { + throw new NoRegisteredCallbackException("Callback target does not implement the callback interface"); + } + } + + public void setNext(Invoker next) { + this.next = next; + } + + public Invoker getNext() { + return next; + } + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/CallbackReferenceImpl.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/CallbackReferenceImpl.java new file mode 100644 index 0000000000..97c69c33cb --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/CallbackReferenceImpl.java @@ -0,0 +1,268 @@ +/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tuscany.sca.core.invocation;
+
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+import java.util.List;
+
+import org.apache.tuscany.sca.assembly.Binding;
+import org.apache.tuscany.sca.assembly.Component;
+import org.apache.tuscany.sca.assembly.ComponentService;
+import org.apache.tuscany.sca.assembly.Contract;
+import org.apache.tuscany.sca.assembly.OptimizableBinding;
+import org.apache.tuscany.sca.core.assembly.EndpointReferenceImpl;
+import org.apache.tuscany.sca.core.assembly.RuntimeComponentReferenceImpl;
+import org.apache.tuscany.sca.core.assembly.RuntimeWireImpl;
+import org.apache.tuscany.sca.core.context.CallableReferenceImpl;
+import org.apache.tuscany.sca.core.context.ComponentContextHelper;
+import org.apache.tuscany.sca.interfacedef.InterfaceContract;
+import org.apache.tuscany.sca.interfacedef.java.JavaInterface;
+import org.apache.tuscany.sca.invocation.Message;
+import org.apache.tuscany.sca.runtime.EndpointReference;
+import org.apache.tuscany.sca.runtime.RuntimeComponent;
+import org.apache.tuscany.sca.runtime.RuntimeComponentReference;
+import org.apache.tuscany.sca.runtime.RuntimeComponentService;
+import org.apache.tuscany.sca.runtime.RuntimeWire;
+
+/**
+ * Returns proxy instance for a wire callback
+ *
+ * @version $Rev: 576055 $ $Date: 2007-09-16 08:11:45 +0100 (Sun, 16 Sep 2007) $
+ */
+public class CallbackReferenceImpl<B> extends CallableReferenceImpl<B> {
+ private RuntimeWire wire;
+ private List<RuntimeWire> wires;
+ private EndpointReference resolvedEndpoint;
+ private Object convID;
+
+ public static CallbackReferenceImpl newInstance(Class interfaze,
+ ProxyFactory proxyFactory,
+ List<RuntimeWire> wires) {
+ if (getCallbackEndpoint(ThreadMessageContext.getMessageContext()) != null) {
+ return new CallbackReferenceImpl(interfaze, proxyFactory, wires);
+ } else {
+ return null;
+ }
+ }
+
+ /**
+ * Public constructor for Externalizable serialization/deserialization.
+ */
+ public CallbackReferenceImpl() {
+ super();
+ }
+
+ private CallbackReferenceImpl(Class<B> interfaze, ProxyFactory proxyFactory, List<RuntimeWire> wires) {
+ super(interfaze, null, proxyFactory);
+ this.wires = wires;
+ init();
+ }
+
+ public void init() {
+ Message msgContext = ThreadMessageContext.getMessageContext();
+ wire = selectCallbackWire(msgContext);
+ if (wire == null) {
+ //FIXME: need better exception
+ throw new RuntimeException("No callback binding found for " + msgContext.getTo().getURI());
+ }
+ resolvedEndpoint = getCallbackEndpoint(msgContext);
+ convID = msgContext.getFrom().getReferenceParameters().getConversationID();
+ callbackID = msgContext.getFrom().getReferenceParameters().getCallbackID();
+ }
+
+ @Override
+ protected Object createProxy() throws Exception {
+ return proxyFactory.createCallbackProxy(this);
+ }
+
+ protected RuntimeWire getCallbackWire() {
+ if (resolvedEndpoint == null) {
+ return null;
+ } else {
+ return cloneAndBind(wire);
+ }
+ }
+
+ protected Object getConvID() {
+ return convID;
+ }
+
+ protected EndpointReference getResolvedEndpoint() {
+ return resolvedEndpoint;
+ }
+
+ private RuntimeWire selectCallbackWire(Message msgContext) {
+ // look for callback binding with same name as service binding
+ EndpointReference to = msgContext.getTo();
+ if (to == null) {
+ //FIXME: need better exception
+ throw new RuntimeException("Destination for forward call is not available");
+ }
+ for (RuntimeWire wire : wires) {
+ if (wire.getSource().getBinding().getName().equals(to.getBinding().getName())) {
+ return wire;
+ }
+ }
+
+ // if no match, look for callback binding with same type as service binding
+ for (RuntimeWire wire : wires) {
+ if (wire.getSource().getBinding().getClass() == to.getBinding().getClass()) {
+ return wire;
+ }
+ }
+
+ // no suitable callback wire was found
+ return null;
+ }
+
+ /**
+ * @param msgContext
+ */
+ private static EndpointReference getCallbackEndpoint(Message msgContext) {
+ EndpointReference from = msgContext.getFrom();
+ if (from == null) {
+ return null;
+ }
+ return from.getReferenceParameters().getCallbackReference();
+ }
+
+ private RuntimeWire cloneAndBind(RuntimeWire wire) {
+ RuntimeWire boundWire = null;
+ if (resolvedEndpoint != null) {
+ boundWire = ((RuntimeWireImpl)wire).lookupCache(resolvedEndpoint);
+ if (boundWire != null) {
+ return boundWire;
+ }
+ try {
+ Contract contract = resolvedEndpoint.getContract();
+ RuntimeComponentReference ref = null;
+ if (contract == null) {
+ boundWire = (RuntimeWire)wire.clone();
+
+ } else if (contract instanceof RuntimeComponentReference) {
+ ref = (RuntimeComponentReference)contract;
+ boundWire = ref.getRuntimeWire(resolvedEndpoint.getBinding());
+
+ } else { // contract instanceof RuntimeComponentService
+ ref = bind((RuntimeComponentReference)wire.getSource().getContract(),
+ resolvedEndpoint.getComponent(),
+ (RuntimeComponentService)contract);
+ boundWire = ref.getRuntimeWires().get(0);
+ }
+ configureWire(boundWire);
+ ((RuntimeWireImpl)wire).addToCache(resolvedEndpoint, boundWire);
+ } catch (CloneNotSupportedException e) {
+ // will not happen
+ }
+ }
+ return boundWire;
+ }
+
+ private static RuntimeComponentReference bind(RuntimeComponentReference reference,
+ RuntimeComponent component,
+ RuntimeComponentService service) throws CloneNotSupportedException {
+ RuntimeComponentReference ref = (RuntimeComponentReference)reference.clone();
+ ref.getTargets().add(service);
+ ref.getBindings().clear();
+ for (Binding binding : service.getBindings()) {
+ if (binding instanceof OptimizableBinding) {
+ OptimizableBinding optimizableBinding = (OptimizableBinding)((OptimizableBinding)binding).clone();
+ optimizableBinding.setTargetBinding(binding);
+ optimizableBinding.setTargetComponent(component);
+ optimizableBinding.setTargetComponentService(service);
+ ref.getBindings().add(optimizableBinding);
+ } else {
+ ref.getBindings().add(binding);
+ }
+ }
+ return ref;
+ }
+
+ private void configureWire(RuntimeWire wire) {
+ // need to set the endpoint on the binding also so that when the chains are created next
+ // the sca binding can decide whether to provide local or remote invokers.
+ // TODO - there is a problem here though in that I'm setting a target on a
+ // binding that may possibly be trying to point at two things in the multi threaded
+ // case. Need to confirm the general model here and how the clone and bind part
+ // is intended to work
+ Binding binding = wire.getSource().getBinding();
+ binding.setURI(resolvedEndpoint.getURI());
+
+ // also need to set the target contract as it varies for the sca binding depending on
+ // whether it is local or remote
+ RuntimeComponentReference ref = (RuntimeComponentReference)wire.getSource().getContract();
+ wire.getTarget().setInterfaceContract(ref.getBindingProvider(binding).getBindingInterfaceContract());
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
+ super.readExternal(in);
+ this.callbackID = in.readObject();
+ this.convID = in.readObject();
+
+ this.compositeActivator = ComponentContextHelper.getCurrentCompositeActivator();
+
+ // Get the target Component and Service from the URI
+ final String uri = in.readUTF();
+ final Component targetComponent = super.resolveComponentURI(uri);
+ final ComponentService targetService = super.resolveServiceURI(uri, targetComponent);
+ final InterfaceContract targetServiceIfaceContract = targetService.getInterfaceContract();
+
+ // Re-create the resolved Endpoint
+ this.resolvedEndpoint = new EndpointReferenceImpl(
+ (RuntimeComponent) targetComponent, targetService, null,
+ targetServiceIfaceContract);
+
+ // Copy the Java Interface from the Service
+ final JavaInterface ji = (JavaInterface) targetServiceIfaceContract.getInterface();
+ this.businessInterface = (Class<B>) ji.getJavaClass();
+
+ // We need to re-create the callback wire. We need to do this on a clone of the Service
+ // wire since we need to change some details on it.
+ // FIXME: Is this the best way to do this?
+ final RuntimeWire cbWire = ((RuntimeComponentService) targetService).getRuntimeWires().get(0);
+ try {
+ this.wire = (RuntimeWireImpl) cbWire.clone();
+ } catch (CloneNotSupportedException e) {
+ throw new IOException(e.toString());
+ }
+
+ // Setup the reference on the cloned wire
+ final RuntimeComponentReference ref = new RuntimeComponentReferenceImpl();
+ ref.setComponent((RuntimeComponent) targetComponent);
+ ref.setInterfaceContract(targetServiceIfaceContract);
+ ((EndpointReferenceImpl) this.wire.getSource()).setContract(ref);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void writeExternal(ObjectOutput out) throws IOException {
+ super.writeExternal(out);
+ out.writeObject(this.callbackID);
+ out.writeObject(this.convID);
+ out.writeUTF(this.resolvedEndpoint.getURI());
+ }
+}
diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/CallbackReferenceObjectFactory.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/CallbackReferenceObjectFactory.java new file mode 100644 index 0000000000..b5b40811ad --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/CallbackReferenceObjectFactory.java @@ -0,0 +1,48 @@ +/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tuscany.sca.core.invocation;
+
+import java.util.List;
+
+import org.apache.tuscany.sca.core.factory.ObjectCreationException;
+import org.apache.tuscany.sca.core.factory.ObjectFactory;
+import org.apache.tuscany.sca.runtime.RuntimeWire;
+import org.osoa.sca.CallableReference;
+
+/**
+ * Uses a wire to return a CallableReference
+ *
+ * @version $Rev: 574648 $ $Date: 2007-09-11 18:45:36 +0100 (Tue, 11 Sep 2007) $
+ */
+public class CallbackReferenceObjectFactory implements ObjectFactory<CallableReference<?>> {
+ private Class<?> businessInterface;
+ private ProxyFactory proxyFactory;
+ private List<RuntimeWire> wires;
+
+ public CallbackReferenceObjectFactory(Class<?> interfaze, ProxyFactory proxyFactory, List<RuntimeWire> wires) {
+ this.businessInterface = interfaze;
+ this.proxyFactory = proxyFactory;
+ this.wires = wires;
+ }
+
+ public CallableReference<?> getInstance() throws ObjectCreationException {
+ return CallbackReferenceImpl.newInstance(businessInterface, proxyFactory, wires);
+ }
+
+}
diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/CallbackWireObjectFactory.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/CallbackWireObjectFactory.java new file mode 100644 index 0000000000..2b37c30451 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/CallbackWireObjectFactory.java @@ -0,0 +1,47 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.invocation; + +import java.util.List; + +import org.apache.tuscany.sca.core.factory.ObjectCreationException; +import org.apache.tuscany.sca.core.factory.ObjectFactory; +import org.apache.tuscany.sca.runtime.RuntimeWire; + +/** + * Returns proxy instance for a wire callback + * + * @version $Rev$ $Date$ + */ +public class CallbackWireObjectFactory<B> implements ObjectFactory<B> { + private Class<B> businessInterface; + private ProxyFactory proxyFactory; + private List<RuntimeWire> wires; + + public CallbackWireObjectFactory(Class<B> interfaze, ProxyFactory proxyFactory, List<RuntimeWire> wires) { + this.businessInterface = interfaze; + this.proxyFactory = proxyFactory; + this.wires = wires; + } + + public B getInstance() throws ObjectCreationException { + return proxyFactory.createCallbackProxy(businessInterface, wires); + } + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/CglibProxyFactory.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/CglibProxyFactory.java new file mode 100644 index 0000000000..0fa1d27d2a --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/CglibProxyFactory.java @@ -0,0 +1,151 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core.invocation; + +import java.lang.reflect.Method; +import java.util.List; + +import net.sf.cglib.proxy.Callback; +import net.sf.cglib.proxy.Enhancer; +import net.sf.cglib.proxy.Factory; +import net.sf.cglib.proxy.MethodInterceptor; +import net.sf.cglib.proxy.MethodProxy; + +import org.apache.tuscany.sca.core.context.CallableReferenceImpl; +import org.apache.tuscany.sca.core.context.ServiceReferenceImpl; +import org.apache.tuscany.sca.interfacedef.InterfaceContractMapper; +import org.apache.tuscany.sca.interfacedef.impl.InterfaceContractMapperImpl; +import org.apache.tuscany.sca.invocation.MessageFactory; +import org.apache.tuscany.sca.runtime.RuntimeWire; +import org.osoa.sca.CallableReference; +import org.osoa.sca.ServiceReference; + +/** + * The implementation of a wire service that uses cglib dynamic proxies + * + * @version $Rev$ $Date$ + */ +@SuppressWarnings("unused") +public class CglibProxyFactory implements ProxyFactory { + private MessageFactory messageFactory; + + public CglibProxyFactory(MessageFactory messageFactory, InterfaceContractMapper mapper) { + this.messageFactory = messageFactory; + + } + + public <T> T createProxy(Class<T> interfaze, RuntimeWire wire) throws ProxyCreationException { + ServiceReference<T> serviceReference = new ServiceReferenceImpl(interfaze, wire, this); + return createProxy(serviceReference); + } + + /** + * create the proxy with cglib. use the same JDKInvocationHandler as + * JDKProxyService. + */ + public <T> T createProxy(CallableReference<T> callableReference) throws ProxyCreationException { + Enhancer enhancer = new Enhancer(); + Class<T> interfaze = callableReference.getBusinessInterface(); + enhancer.setSuperclass(interfaze); + enhancer.setCallback(new CglibMethodInterceptor<T>(callableReference)); + Object proxy = enhancer.create(); + ((CallableReferenceImpl)callableReference).setProxy(proxy); + return interfaze.cast(proxy); + } + + /** + * create the callback proxy with cglib. use the same + * JDKCallbackInvocationHandler as JDKProxyService. + */ + public <T> T createCallbackProxy(Class<T> interfaze, final List<RuntimeWire> wires) throws ProxyCreationException { + CallbackReferenceImpl<T> callbackReference = CallbackReferenceImpl.newInstance(interfaze, this, wires); + return callbackReference != null ? createCallbackProxy(callbackReference) : null; + } + + /** + * create the callback proxy with cglib. use the same + * JDKCallbackInvocationHandler as JDKProxyService. + */ + public <T> T createCallbackProxy(CallbackReferenceImpl<T> callbackReference) throws ProxyCreationException { + Enhancer enhancer = new Enhancer(); + Class<T> interfaze = callbackReference.getBusinessInterface(); + enhancer.setSuperclass(interfaze); + enhancer.setCallback(new CglibMethodInterceptor<T>(callbackReference)); + Object proxy = enhancer.create(); + callbackReference.setProxy(proxy); + return interfaze.cast(proxy); + } + + @SuppressWarnings("unchecked") + public <B, R extends CallableReference<B>> R cast(B target) throws IllegalArgumentException { + if (isProxyClass(target.getClass())) { + Factory factory = (Factory)target; + Callback[] callbacks = factory.getCallbacks(); + if (callbacks.length != 1 || !(callbacks[0] instanceof CglibMethodInterceptor)) { + throw new IllegalArgumentException("The object is not a known proxy."); + } + CglibMethodInterceptor interceptor = (CglibMethodInterceptor)callbacks[0]; + return (R)interceptor.invocationHandler.getCallableReference(); + } else { + throw new IllegalArgumentException("The object is not a known proxy."); + } + } + + /** + * @see org.apache.tuscany.sca.core.invocation.ProxyFactory#isProxyClass(java.lang.Class) + */ + public boolean isProxyClass(Class<?> clazz) { + return Factory.class.isAssignableFrom(clazz); + } + + private class CglibMethodInterceptor<T> implements MethodInterceptor { + private JDKInvocationHandler invocationHandler; + + public CglibMethodInterceptor(CallableReference<T> callableReference) { + invocationHandler = new JDKInvocationHandler(messageFactory, callableReference); + } + + public CglibMethodInterceptor(CallbackReferenceImpl<T> callbackReference) { + invocationHandler = new JDKCallbackInvocationHandler(messageFactory, callbackReference); + } + + /* + public CglibMethodInterceptor(Class<T> interfaze, RuntimeWire wire) { + ServiceReference<T> serviceRef = new ServiceReferenceImpl<T>(interfaze, wire, CglibProxyFactory.this); + invocationHandler = new JDKInvocationHandler(messageFactory, serviceRef); + } + + public CglibMethodInterceptor(Class<T> interfaze, List<RuntimeWire> wires) { + CallbackReferenceImpl ref = new CallbackReferenceImpl(interfaze, CglibProxyFactory.this, wires); + invocationHandler = new JDKCallbackInvocationHandler(messageFactory, ref); + } + */ + + /** + * @see net.sf.cglib.proxy.MethodInterceptor#intercept(java.lang.Object, java.lang.reflect.Method, java.lang.Object[], net.sf.cglib.proxy.MethodProxy) + */ + public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { + Object result = invocationHandler.invoke(proxy, method, args); + return result; + } + + } + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/DefaultProxyFactoryExtensionPoint.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/DefaultProxyFactoryExtensionPoint.java new file mode 100644 index 0000000000..9acb4be6f8 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/DefaultProxyFactoryExtensionPoint.java @@ -0,0 +1,74 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core.invocation; + +import org.apache.tuscany.sca.contribution.ModelFactoryExtensionPoint; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.core.UtilityExtensionPoint; +import org.apache.tuscany.sca.interfacedef.InterfaceContractMapper; +import org.apache.tuscany.sca.invocation.MessageFactory; + +/** + * Default implementation of a ProxyFactoryExtensionPoint. + * + * @version $Rev$ $Date$ + */ +public class DefaultProxyFactoryExtensionPoint implements ProxyFactoryExtensionPoint { + private InterfaceContractMapper interfaceContractMapper; + private MessageFactory messageFactory; + + private ProxyFactory interfaceFactory; + private ProxyFactory classFactory; + + public DefaultProxyFactoryExtensionPoint(ExtensionPointRegistry extensionPoints) { + UtilityExtensionPoint utilities = extensionPoints.getExtensionPoint(UtilityExtensionPoint.class); + this.interfaceContractMapper = utilities.getUtility(InterfaceContractMapper.class); + + ModelFactoryExtensionPoint modelFactories = extensionPoints.getExtensionPoint(ModelFactoryExtensionPoint.class); + this.messageFactory = modelFactories.getFactory(MessageFactory.class); + + interfaceFactory = new JDKProxyFactory(messageFactory, interfaceContractMapper); + } + + public DefaultProxyFactoryExtensionPoint(MessageFactory messageFactory, InterfaceContractMapper mapper) { + this.interfaceContractMapper = mapper; + this.messageFactory = messageFactory; + interfaceFactory = new JDKProxyFactory(messageFactory, mapper); + } + + public ProxyFactory getClassProxyFactory() { + return classFactory; + } + + public ProxyFactory getInterfaceProxyFactory() { + return interfaceFactory; + } + + public void setClassProxyFactory(ProxyFactory factory) { + this.classFactory = factory; + + } + + public void setInterfaceProxyFactory(ProxyFactory factory) { + this.interfaceFactory = factory; + + } + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/ExtensibleProxyFactory.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/ExtensibleProxyFactory.java new file mode 100644 index 0000000000..fcb48259b9 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/ExtensibleProxyFactory.java @@ -0,0 +1,113 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core.invocation; + +import java.util.List; + +import org.apache.tuscany.sca.runtime.RuntimeWire; +import org.osoa.sca.CallableReference; + +/** + * An extensible proxy factory. + * + * @version $Rev: $ $Date: $ + */ +public class ExtensibleProxyFactory implements ProxyFactory { + + private ProxyFactoryExtensionPoint proxyFactories; + + public ExtensibleProxyFactory(ProxyFactoryExtensionPoint proxyFactories) { + this.proxyFactories = proxyFactories; + } + + /** + * @see org.apache.tuscany.sca.core.invocation.ProxyFactory#cast(java.lang.Object) + */ + @SuppressWarnings("unchecked") + public <B, R extends CallableReference<B>> R cast(B target) throws IllegalArgumentException { + ProxyFactory interfaceFactory = proxyFactories.getInterfaceProxyFactory(); + ProxyFactory classFactory = proxyFactories.getClassProxyFactory(); + if (interfaceFactory.isProxyClass(target.getClass())) { + return (R)interfaceFactory.cast(target); + } else if (classFactory != null && classFactory.isProxyClass(target.getClass())) { + return (R)classFactory.cast(target); + } else { + throw new IllegalArgumentException("The target is not a callable proxy"); + } + } + + /** + * @see org.apache.tuscany.sca.core.invocation.ProxyFactory#createCallbackProxy(java.lang.Class, + * java.util.List) + */ + public <T> T createCallbackProxy(Class<T> interfaze, List<RuntimeWire> wires) throws ProxyCreationException { + ProxyFactory interfaceFactory = proxyFactories.getInterfaceProxyFactory(); + ProxyFactory classFactory = proxyFactories.getClassProxyFactory(); + if (interfaze.isInterface()) { + return interfaceFactory.createCallbackProxy(interfaze, wires); + } else { + return classFactory.createCallbackProxy(interfaze, wires); + } + } + + public <T> T createProxy(CallableReference<T> callableReference) throws ProxyCreationException { + ProxyFactory interfaceFactory = proxyFactories.getInterfaceProxyFactory(); + ProxyFactory classFactory = proxyFactories.getClassProxyFactory(); + if (callableReference.getBusinessInterface().isInterface()) { + return interfaceFactory.createProxy(callableReference); + } else { + return classFactory.createProxy(callableReference); + } + } + + public <T> T createCallbackProxy(CallbackReferenceImpl<T> callbackReference) throws ProxyCreationException { + ProxyFactory interfaceFactory = proxyFactories.getInterfaceProxyFactory(); + ProxyFactory classFactory = proxyFactories.getClassProxyFactory(); + if (callbackReference.getBusinessInterface().isInterface()) { + return interfaceFactory.createCallbackProxy(callbackReference); + } else { + return classFactory.createCallbackProxy(callbackReference); + } + } + + /** + * @see org.apache.tuscany.sca.core.invocation.ProxyFactory#createProxy(java.lang.Class, + * org.apache.tuscany.sca.runtime.RuntimeWire) + */ + public <T> T createProxy(Class<T> interfaze, RuntimeWire wire) throws ProxyCreationException { + ProxyFactory interfaceFactory = proxyFactories.getInterfaceProxyFactory(); + ProxyFactory classFactory = proxyFactories.getClassProxyFactory(); + if (interfaze.isInterface()) { + return interfaceFactory.createProxy(interfaze, wire); + } else { + return classFactory.createProxy(interfaze, wire); + } + } + + /** + * @see org.apache.tuscany.sca.core.invocation.ProxyFactory#isProxyClass(java.lang.Class) + */ + public boolean isProxyClass(Class<?> clazz) { + ProxyFactory interfaceFactory = proxyFactories.getInterfaceProxyFactory(); + ProxyFactory classFactory = proxyFactories.getClassProxyFactory(); + return interfaceFactory.isProxyClass(clazz) || (classFactory != null && classFactory.isProxyClass(clazz)); + } + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/ExtensibleWireProcessor.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/ExtensibleWireProcessor.java new file mode 100644 index 0000000000..934f2f7aa0 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/ExtensibleWireProcessor.java @@ -0,0 +1,44 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.invocation; + +import org.apache.tuscany.sca.runtime.RuntimeWire; +import org.apache.tuscany.sca.runtime.RuntimeWireProcessor; +import org.apache.tuscany.sca.runtime.RuntimeWireProcessorExtensionPoint; + +/** + * The default implementation of an extensible <code>WireProcessor</code> + * + * @version $Rev$ $Date$ + */ +public class ExtensibleWireProcessor implements RuntimeWireProcessor { + + private RuntimeWireProcessorExtensionPoint processors; + + public ExtensibleWireProcessor(RuntimeWireProcessorExtensionPoint processors) { + this.processors = processors; + } + + public void process(RuntimeWire wire) { + for (RuntimeWireProcessor processor : processors.getWireProcessors()) { + processor.process(wire); + } + } + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/InvocationChainImpl.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/InvocationChainImpl.java new file mode 100644 index 0000000000..c559a42bdc --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/InvocationChainImpl.java @@ -0,0 +1,191 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.invocation; + +import java.util.ArrayList; +import java.util.List; +import java.util.ListIterator; + +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.DataExchangeSemantics; +import org.apache.tuscany.sca.invocation.Interceptor; +import org.apache.tuscany.sca.invocation.InvocationChain; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.Phase; + +/** + * Default implementation of an invocation chain + * + * @version $Rev$ $Date$ + */ +public class InvocationChainImpl implements InvocationChain { + private Operation sourceOperation; + private Operation targetOperation; + private List<Node> nodes = new ArrayList<Node>(); + + // FIXME: Not a good practice to use static reference + private static final PhaseManager phaseManager = new PhaseManager(); + private boolean forReference; + private boolean allowsPassByReference; + + public InvocationChainImpl(Operation sourceOperation, Operation targetOperation, boolean forReference) { + // TODO - binding invocation chain doesn't provide operations + //assert sourceOperation != null; + //assert targetOperation != null; + this.targetOperation = targetOperation; + this.sourceOperation = sourceOperation; + this.forReference = forReference; + } + + public Operation getTargetOperation() { + return targetOperation; + } + + public void setTargetOperation(Operation operation) { + this.targetOperation = operation; + } + + public void addInterceptor(Interceptor interceptor) { + String phase = forReference ? Phase.REFERENCE : Phase.SERVICE; + addInterceptor(phase, interceptor); + } + + public void addInvoker(Invoker invoker) { + String phase = forReference ? Phase.REFERENCE_BINDING : Phase.IMPLEMENTATION; + addInvoker(phase, invoker); + } + + public Invoker getHeadInvoker() { + return nodes.isEmpty() ? null : nodes.get(0).getInvoker(); + } + + public Invoker getTailInvoker() { + return nodes.isEmpty() ? null : nodes.get(nodes.size() - 1).getInvoker(); + } + + /** + * @return the sourceOperation + */ + public Operation getSourceOperation() { + return sourceOperation; + } + + /** + * @param sourceOperation the sourceOperation to set + */ + public void setSourceOperation(Operation sourceOperation) { + this.sourceOperation = sourceOperation; + } + + public void addInterceptor(int index, Interceptor interceptor) { + addInterceptor(interceptor); + } + + public void addInterceptor(String phase, Interceptor interceptor) { + addInvoker(phase, interceptor); + } + + private void addInvoker(String phase, Invoker invoker) { + int index = phaseManager.getAllPhases().indexOf(phase); + if (index == -1) { + throw new IllegalArgumentException("Invalid phase name: " + phase); + } + Node node = new Node(index, invoker); + ListIterator<Node> li = nodes.listIterator(); + Node before = null, after = null; + boolean found = false; + while (li.hasNext()) { + before = after; + after = li.next(); + if (after.getPhaseIndex() > index) { + // Move back + li.previous(); + li.add(node); + found = true; + break; + } + } + if (!found) { + // Add to the end + nodes.add(node); + before = after; + after = null; + } + + // Relink the interceptors + if (before != null) { + if (before.getInvoker() instanceof Interceptor) { + ((Interceptor)before.getInvoker()).setNext(invoker); + } + } + if (after != null) { + if (invoker instanceof Interceptor) { + ((Interceptor)invoker).setNext(after.getInvoker()); + } + } + + } + + public boolean allowsPassByReference() { + if (allowsPassByReference) { + // No need to check the invokers + return true; + } + // Check if any of the invokers allows pass-by-reference + boolean allowsPBR = false; + for (Node i : nodes) { + if (i.getInvoker() instanceof DataExchangeSemantics) { + if (((DataExchangeSemantics)i.getInvoker()).allowsPassByReference()) { + allowsPBR = true; + break; + } + } + } + return allowsPBR; + } + + public void setAllowsPassByReference(boolean allowsPBR) { + this.allowsPassByReference = allowsPBR; + } + + private static class Node { + private int phaseIndex; + private Invoker invoker; + + public Node(int phaseIndex, Invoker invoker) { + super(); + this.phaseIndex = phaseIndex; + this.invoker = invoker; + } + + public int getPhaseIndex() { + return phaseIndex; + } + + public Invoker getInvoker() { + return invoker; + } + + @Override + public String toString() { + return "(" + phaseIndex + ")" + invoker; + } + } + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/JDKCallbackInvocationHandler.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/JDKCallbackInvocationHandler.java new file mode 100644 index 0000000000..cade0499d3 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/JDKCallbackInvocationHandler.java @@ -0,0 +1,110 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.invocation; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +import org.apache.tuscany.sca.core.assembly.RuntimeWireImpl; +import org.apache.tuscany.sca.core.context.CallableReferenceImpl; +import org.apache.tuscany.sca.core.conversation.ConversationState; +import org.apache.tuscany.sca.invocation.InvocationChain; +import org.apache.tuscany.sca.invocation.MessageFactory; +import org.apache.tuscany.sca.runtime.RuntimeWire; +import org.osoa.sca.NoRegisteredCallbackException; +import org.osoa.sca.ServiceRuntimeException; + +/** + * Responsible for dispatching to a callback through a wire. <p/> TODO cache + * target invoker + * + * @version $Rev$ $Date$ + */ +public class JDKCallbackInvocationHandler extends JDKInvocationHandler { + private static final long serialVersionUID = -3350283555825935609L; + + public JDKCallbackInvocationHandler(MessageFactory messageFactory, CallbackReferenceImpl ref) { + super(messageFactory, ref); + this.fixedWire = false; + } + + @Override + @SuppressWarnings( {"unchecked"}) + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + if (Object.class == method.getDeclaringClass()) { + return invokeObjectMethod(method, args); + } + + // obtain a dedicated wire to be used for this callback invocation + RuntimeWire wire = ((CallbackReferenceImpl)callableReference).getCallbackWire(); + if (wire == null) { + //FIXME: need better exception + throw new ServiceRuntimeException("No callback wire found"); + } + + // set the conversational state based on the interface that + // is specified for the reference that this wire belongs to + initConversational(wire); + + // set the conversation id into the conversation object. This is + // a special case for callbacks as, unless otherwise set manually, + // the callback should use the same conversation id as was received + // on the incoming call to this component + if (conversational) { + + if (conversation == null || conversation.getState() == ConversationState.ENDED) { + conversation = null; + } + Object convID = conversation == null ? null : conversation.getConversationID(); + + // create a conversation id if one doesn't exist + // already, i.e. the conversation is just starting + if (convID == null) { + convID = ((CallbackReferenceImpl)callableReference).getConvID(); + if (convID != null) { + conversation = ((RuntimeWireImpl)wire).getConversationManager().getConversation(convID); + if (callableReference != null) { + ((CallableReferenceImpl)callableReference).attachConversation(conversation); + } + } + } + } + + setEndpoint(((CallbackReferenceImpl)callableReference).getResolvedEndpoint()); + + InvocationChain chain = getInvocationChain(method, wire); + if (chain == null) { + throw new IllegalArgumentException("No matching operation is found: " + method); + } + + try { + return invoke(chain, args, wire, wire.getSource()); + } catch (InvocationTargetException e) { + Throwable t = e.getCause(); + if (t instanceof NoRegisteredCallbackException) { + throw t; + } + throw e; + } finally { + // allow the cloned wire to be reused by subsequent callbacks + ((RuntimeWireImpl)wire).releaseWire(); + } + } + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/JDKInvocationHandler.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/JDKInvocationHandler.java new file mode 100644 index 0000000000..b2b30db558 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/JDKInvocationHandler.java @@ -0,0 +1,573 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core.invocation; + +import java.io.Serializable; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import javax.xml.ws.Holder; + +import org.apache.tuscany.sca.core.assembly.RuntimeWireImpl; +import org.apache.tuscany.sca.core.context.CallableReferenceImpl; +import org.apache.tuscany.sca.core.context.InstanceWrapper; +import org.apache.tuscany.sca.core.conversation.ConversationManager; +import org.apache.tuscany.sca.core.conversation.ConversationState; +import org.apache.tuscany.sca.core.conversation.ExtendedConversation; +import org.apache.tuscany.sca.core.scope.Scope; +import org.apache.tuscany.sca.core.scope.ScopeContainer; +import org.apache.tuscany.sca.core.scope.ScopedRuntimeComponent; +import org.apache.tuscany.sca.core.scope.TargetDestructionException; +import org.apache.tuscany.sca.core.scope.TargetResolutionException; +import org.apache.tuscany.sca.interfacedef.ConversationSequence; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.Interface; +import org.apache.tuscany.sca.interfacedef.InterfaceContract; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.interfacedef.ParameterMode; +import org.apache.tuscany.sca.interfacedef.java.JavaOperation; +import org.apache.tuscany.sca.invocation.InvocationChain; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.Message; +import org.apache.tuscany.sca.invocation.MessageFactory; +import org.apache.tuscany.sca.runtime.EndpointReference; +import org.apache.tuscany.sca.runtime.ReferenceParameters; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeWire; +import org.osoa.sca.CallableReference; +import org.osoa.sca.ConversationEndedException; +import org.osoa.sca.ServiceReference; +import org.osoa.sca.ServiceRuntimeException; + +/** + * @version $Rev$ $Date$ + */ +public class JDKInvocationHandler implements InvocationHandler, Serializable { + private static final long serialVersionUID = -3366410500152201371L; + + protected boolean conversational; + protected ExtendedConversation conversation; + protected MessageFactory messageFactory; + protected EndpointReference source; + protected EndpointReference target; + protected RuntimeWire wire; + protected CallableReference<?> callableReference; + protected Class<?> businessInterface; + + protected boolean fixedWire = true; + + protected transient Map<Method, InvocationChain> chains = new HashMap<Method, InvocationChain>(); + + public JDKInvocationHandler(MessageFactory messageFactory, Class<?> businessInterface, RuntimeWire wire) { + this.messageFactory = messageFactory; + this.wire = wire; + this.businessInterface = businessInterface; + init(this.wire); + } + + public JDKInvocationHandler(MessageFactory messageFactory, CallableReference<?> callableReference) { + this.messageFactory = messageFactory; + this.callableReference = callableReference; + if (callableReference != null) { + this.businessInterface = callableReference.getBusinessInterface(); + this.conversation = (ExtendedConversation)callableReference.getConversation(); + this.wire = ((CallableReferenceImpl<?>)callableReference).getRuntimeWire(); + if (wire != null) { + init(wire); + } + } + } + + protected void init(RuntimeWire wire) { + if (wire != null) { + try { + // Clone the endpoint reference so that reference parameters can be changed + source = (EndpointReference)wire.getSource().clone(); + } catch (CloneNotSupportedException e) { + throw new ServiceRuntimeException(e); + } + initConversational(wire); + } + } + + protected void initConversational(RuntimeWire wire) { + InterfaceContract contract = wire.getSource().getInterfaceContract(); + this.conversational = contract.getInterface().isConversational(); + } + + protected Object getCallbackID() { + if (callableReference != null) { + return callableReference.getCallbackID(); + } else { + return null; + } + } + + protected Object getConversationID() { + if (callableReference != null && callableReference instanceof ServiceReference) { + return ((ServiceReference)callableReference).getConversationID(); + } else { + return null; + } + } + + protected Object getCallbackObject() { + if (callableReference != null && callableReference instanceof ServiceReference) { + return ((ServiceReference)callableReference).getCallback(); + } else { + return null; + } + } + + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + if (Object.class == method.getDeclaringClass()) { + return invokeObjectMethod(method, args); + } + if (wire == null) { + throw new ServiceRuntimeException("No runtime wire is available"); + } + InvocationChain chain = getInvocationChain(method, wire); + if (chain == null) { + throw new IllegalArgumentException("No matching operation is found: " + method); + } + + Object result = invoke(chain, args, wire, source); + + Operation operation = chain.getSourceOperation(); + if (operation != null && operation.getInterface().isRemotable()) { + List<DataType> inputTypes = operation.getInputType().getLogical(); + // Returned Holder data <T> are placed back in Holder<T>. + for (int i = 0, size = inputTypes.size(); i < size; i++) { + if (operation.getParameterModes().get(i) != ParameterMode.IN) { + // Pop results and place in holder (demote). + Holder holder = (Holder)args[i]; + holder.value = result; + } + } + } + + return result; + } + + /** + * Handle the methods on the Object.class + * @param method + * @param args + */ + protected Object invokeObjectMethod(Method method, Object[] args) throws Throwable { + String name = method.getName(); + if ("toString".equals(name)) { + return "[Proxy - " + toString() + "]"; + } else if ("equals".equals(name)) { + Object obj = args[0]; + if (obj == null) { + return false; + } + if (!Proxy.isProxyClass(obj.getClass())) { + return false; + } + return equals(Proxy.getInvocationHandler(obj)); + } else if ("hashCode".equals(name)) { + return hashCode(); + } else { + return method.invoke(this); + } + } + + /** + * Determines if the given operation matches the given method + * + * @return true if the operation matches, false if does not + */ + // FIXME: Should it be in the InterfaceContractMapper? + @SuppressWarnings("unchecked") + private static boolean match(Operation operation, Method method) { + if (operation instanceof JavaOperation) { + JavaOperation javaOp = (JavaOperation)operation; + Method m = javaOp.getJavaMethod(); + if (!method.getName().equals(m.getName())) { + return false; + } + if (method.equals(m)) { + return true; + } + } else { + if (!method.getName().equals(operation.getName())) { + return false; + } + } + + // For remotable interface, operation is not overloaded. + if (operation.getInterface().isRemotable()) { + return true; + } + + Class<?>[] params = method.getParameterTypes(); + + DataType<List<DataType>> inputType = null; + if (operation.isInputWrapperStyle()) { + inputType = operation.getInputWrapper().getUnwrappedInputType(); + } else { + inputType = operation.getInputType(); + } + List<DataType> types = inputType.getLogical(); + boolean matched = true; + if (types.size() == params.length && method.getName().equals(operation.getName())) { + for (int i = 0; i < params.length; i++) { + Class<?> clazz = params[i]; + Class<?> type = types.get(i).getPhysical(); + // Object.class.isAssignableFrom(int.class) returns false + if (type != Object.class && (!type.isAssignableFrom(clazz))) { + matched = false; + } + } + } else { + matched = false; + } + return matched; + + } + + protected synchronized InvocationChain getInvocationChain(Method method, RuntimeWire wire) { + if (fixedWire && chains.containsKey(method)) { + return chains.get(method); + } + InvocationChain found = null; + for (InvocationChain chain : wire.getInvocationChains()) { + Operation operation = chain.getSourceOperation(); + if (operation.isDynamic()) { + operation.setName(method.getName()); + found = chain; + break; + } else if (match(operation, method)) { + found = chain; + break; + } + } + if (fixedWire) { + chains.put(method, found); + } + return found; + } + + protected void setEndpoint(EndpointReference endpoint) { + this.target = endpoint; + } + + protected Object invoke(InvocationChain chain, Object[] args, RuntimeWire wire, EndpointReference source) + throws Throwable { + Message msg = messageFactory.createMessage(); + msg.setFrom(source); + if (target != null) { + msg.setTo(target); + } else { + msg.setTo(wire.getTarget()); + } + Invoker headInvoker = chain.getHeadInvoker(); + Operation operation = chain.getTargetOperation(); + + msg.setOperation(operation); + + // Holder pattern. Items stored in a Holder<T> are promoted to T. + // After the invoke, the returned data <T> are placed back in Holder<T>. + if (operation != null && operation.getInterface().isRemotable()) { + args = promoteHolderArgs(chain.getSourceOperation(), args); + } + msg.setBody(args); + + Message msgContext = ThreadMessageContext.getMessageContext(); + Object currentConversationID = msgContext.getFrom().getReferenceParameters().getConversationID(); + + conversationPreinvoke(msg, wire); + handleCallback(msg, wire, currentConversationID); + ThreadMessageContext.setMessageContext(msg); + boolean abnormalEndConversation = false; + try { + // dispatch the wire down the chain and get the response + Message resp = headInvoker.invoke(msg); + Object body = resp.getBody(); + if (resp.isFault()) { + // mark the conversation as ended if the exception is not a business exception + if (currentConversationID != null) { + try { + boolean businessException = false; + + for (DataType dataType : operation.getFaultTypes()) { + if (dataType.getPhysical() == ((Throwable)body).getClass()) { + businessException = true; + break; + } + } + + if (businessException == false) { + abnormalEndConversation = true; + } + } catch (Exception ex) { + // TODO - sure what the best course of action is here. We have + // a system exception in the middle of a business exception + } + } + throw (Throwable)body; + } + return body; + } finally { + conversationPostInvoke(msg, wire, abnormalEndConversation); + ThreadMessageContext.setMessageContext(msgContext); + } + } + + /** + * @param msg + * @param wire + * @param interfaze + * @throws TargetResolutionException + */ + private void handleCallback(Message msg, RuntimeWire wire, Object currentConversationID) + throws TargetResolutionException { + ReferenceParameters parameters = msg.getFrom().getReferenceParameters(); + parameters.setCallbackID(getCallbackID()); + if (msg.getFrom() == null || msg.getFrom().getCallbackEndpoint() == null) { + return; + } + + parameters.setCallbackReference(msg.getFrom().getCallbackEndpoint()); + + // If we are passing out a callback target + // register the calling component instance against this + // new conversation id so that stateful callbacks will be + // able to find it + Object callbackObject = getCallbackObject(); + if (conversational && callbackObject == null) { + // the component instance is already registered + // so add another registration + ScopeContainer<Object> scopeContainer = getConversationalScopeContainer(wire); + + if (scopeContainer != null && currentConversationID != null) { + scopeContainer.addWrapperReference(currentConversationID, conversation.getConversationID()); + } + } + + Interface interfaze = msg.getFrom().getCallbackEndpoint().getInterfaceContract().getInterface(); + if (callbackObject != null) { + if (callbackObject instanceof ServiceReference) { + EndpointReference callbackRef = ((CallableReferenceImpl)callbackObject).getEndpointReference(); + parameters.setCallbackReference(callbackRef); + } else { + if (interfaze != null) { + if (!interfaze.isConversational()) { + throw new IllegalArgumentException( + "Callback object for stateless callback is not a ServiceReference"); + } else { + if (!(callbackObject instanceof Serializable)) { + throw new IllegalArgumentException( + "Callback object for stateful callback is not Serializable"); + } + ScopeContainer scopeContainer = getConversationalScopeContainer(wire); + if (scopeContainer != null) { + InstanceWrapper wrapper = new CallbackObjectWrapper(callbackObject); + scopeContainer.registerWrapper(wrapper, conversation.getConversationID()); + } + parameters.setCallbackObjectID(callbackObject); + } + } + } + } + } + + /** + * Pre-invoke for the conversation handling + * @param msg + * @throws TargetResolutionException + */ + private void conversationPreinvoke(Message msg, RuntimeWire wire) { + if (!conversational) { + // Not conversational or the conversation has been started + return; + } + + ConversationManager conversationManager = ((RuntimeWireImpl)wire).getConversationManager(); + + if (conversation == null || conversation.getState() == ConversationState.ENDED) { + + conversation = conversationManager.startConversation(getConversationID()); + + // if this is a local wire then set up the conversation timeouts here based on the + // parameters from the component + if (wire.getTarget().getComponent() != null) { + conversation.initializeConversationAttributes(wire.getTarget().getComponent()); + } + + // connect the conversation to the CallableReference so it can be retrieve in the future + if (callableReference != null) { + ((CallableReferenceImpl)callableReference).attachConversation(conversation); + } + } else if (conversation.isExpired()) { + throw new ConversationEndedException("Conversation " + conversation.getConversationID() + " has expired."); + } + + // if this is a local wire then schedule conversation timeouts based on the timeout + // parameters from the service implementation. If this isn't a local wire then + // the RuntimeWireInvoker will take care of this + if (wire.getTarget().getComponent() != null) { + conversation.updateLastReferencedTime(); + } + + msg.getFrom().getReferenceParameters().setConversationID(conversation.getConversationID()); + + } + + /** + * Post-invoke for the conversation handling + * @param wire + * @param operation + * @throws TargetDestructionException + */ + @SuppressWarnings("unchecked") + private void conversationPostInvoke(Message msg, RuntimeWire wire, boolean abnormalEndConversation) + throws TargetDestructionException { + Operation operation = msg.getOperation(); + ConversationSequence sequence = operation.getConversationSequence(); + // We check that conversation has not already ended as there is only one + // conversation manager in the runtime and so, in the case of remote bindings, + // the conversation will already have been stopped when we get back to the client + if ((sequence == ConversationSequence.CONVERSATION_END || abnormalEndConversation) && (conversation.getState() != ConversationState.ENDED)) { + + // remove conversation id from scope container + ScopeContainer scopeContainer = getConversationalScopeContainer(wire); + + if (scopeContainer != null) { + scopeContainer.remove(conversation.getConversationID()); + } + + conversation.end(); + } + } + + private ScopeContainer<Object> getConversationalScopeContainer(RuntimeWire wire) { + ScopeContainer<Object> scopeContainer = null; + + RuntimeComponent runtimeComponent = wire.getSource().getComponent(); + + if (runtimeComponent instanceof ScopedRuntimeComponent) { + ScopedRuntimeComponent scopedRuntimeComponent = (ScopedRuntimeComponent)runtimeComponent; + ScopeContainer<Object> tmpScopeContainer = scopedRuntimeComponent.getScopeContainer(); + + if ((tmpScopeContainer != null) && (tmpScopeContainer.getScope() == Scope.CONVERSATION)) { + scopeContainer = tmpScopeContainer; + } + } + + return scopeContainer; + } + + /** + * Creates a new conversation id + * + * @return the conversation id + */ + private Object createConversationID() { + if (getConversationID() != null) { + return getConversationID(); + } else { + return UUID.randomUUID().toString(); + } + } + + /** + * @return the callableReference + */ + public CallableReference<?> getCallableReference() { + return callableReference; + } + + /** + * @param callableReference the callableReference to set + */ + public void setCallableReference(CallableReference<?> callableReference) { + this.callableReference = callableReference; + } + + /** + * Minimal wrapper for a callback object contained in a ServiceReference + */ + private static class CallbackObjectWrapper<T> implements InstanceWrapper<T> { + + private T instance; + + private CallbackObjectWrapper(T instance) { + this.instance = instance; + } + + public T getInstance() { + return instance; + } + + public void start() { + // do nothing + } + + public void stop() { + // do nothing + } + + } + + /** + * Creates a copy of arguments. Holder<T> values are promoted to T. + * Note. It is essential that arg Holders not be destroyed here. + * PromotedArgs should not destroy holders. They are used on response return. + * @param args containing Holders and other objects. + * @return Object [] + */ + protected static Object[] promoteHolderArgs(Operation operation, Object[] args) { + if (args == null) + return args; + + Object[] promotedArgs = new Object[args.length]; + List<ParameterMode> modes = operation.getParameterModes(); + for (int i = 0; i < args.length; i++) { + Object argument = args[i]; + if (argument != null) { + if (modes.get(i) != ParameterMode.IN) { + promotedArgs[i] = ((Holder)argument).value; + } else { + promotedArgs[i] = args[i]; + } + + } + } + return promotedArgs; + } + + /** + * Given an Object, tells if it is a Holder by comparing to "javax.xml.ws.Holder" + * @param testClass + * @return boolean stating whether Object is a Holder type. + */ + protected static boolean isHolder(Object object) { + return Holder.class.isInstance(object); + } + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/JDKProxyFactory.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/JDKProxyFactory.java new file mode 100644 index 0000000000..a2cbd1365b --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/JDKProxyFactory.java @@ -0,0 +1,104 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.invocation; + +import java.lang.reflect.InvocationHandler; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.List; +import java.util.HashMap; + +import org.apache.tuscany.sca.core.invocation.SCAProxy; +import org.apache.tuscany.sca.core.context.CallableReferenceImpl; +import org.apache.tuscany.sca.core.context.ServiceReferenceImpl; +import org.apache.tuscany.sca.interfacedef.InterfaceContractMapper; +import org.apache.tuscany.sca.invocation.MessageFactory; +import org.apache.tuscany.sca.runtime.RuntimeWire; +import org.osoa.sca.CallableReference; +import org.osoa.sca.ServiceReference; + +/** + * the default implementation of a wire service that uses JDK dynamic proxies + * + * @version $Rev$ $Date$ + */ +public class JDKProxyFactory implements ProxyFactory { + protected InterfaceContractMapper contractMapper; + private MessageFactory messageFactory; + + public JDKProxyFactory(MessageFactory messageFactory, InterfaceContractMapper mapper) { + this.contractMapper = mapper; + this.messageFactory = messageFactory; + } + + /** + * The original createProxy method assumes that the proxy doesn't want to + * share conversation state so sets the conversation object to null + */ + public <T> T createProxy(Class<T> interfaze, RuntimeWire wire) throws ProxyCreationException { + ServiceReference<T> serviceReference = new ServiceReferenceImpl(interfaze, wire, this); + return createProxy(serviceReference); + } + + public <T> T createProxy(CallableReference<T> callableReference) throws ProxyCreationException { + assert callableReference != null; + final Class<T> interfaze = callableReference.getBusinessInterface(); + InvocationHandler handler = new JDKInvocationHandler(messageFactory, callableReference); + // Allow privileged access to class loader. Requires RuntimePermission in security policy. + ClassLoader cl = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() { + public ClassLoader run() { + return interfaze.getClassLoader(); + } + }); + Object proxy = SCAProxy.newProxyInstance(cl, new Class[] {interfaze}, handler); + ((CallableReferenceImpl)callableReference).setProxy(proxy); + return interfaze.cast(proxy); + } + + public <T> T createCallbackProxy(Class<T> interfaze, List<RuntimeWire> wires) throws ProxyCreationException { + CallbackReferenceImpl<T> callbackReference = CallbackReferenceImpl.newInstance(interfaze, this, wires); + return callbackReference != null ? createCallbackProxy(callbackReference) : null; + } + + public <T> T createCallbackProxy(CallbackReferenceImpl<T> callbackReference) throws ProxyCreationException { + assert callbackReference != null; + Class<T> interfaze = callbackReference.getBusinessInterface(); + InvocationHandler handler = new JDKCallbackInvocationHandler(messageFactory, callbackReference); + ClassLoader cl = interfaze.getClassLoader(); + Object proxy = SCAProxy.newProxyInstance(cl, new Class[] {interfaze}, handler); + callbackReference.setProxy(proxy); + return interfaze.cast(proxy); + } + + public <B, R extends CallableReference<B>> R cast(B target) throws IllegalArgumentException { + InvocationHandler handler = SCAProxy.getInvocationHandler(target); + if (handler instanceof JDKInvocationHandler) { + return (R)((JDKInvocationHandler)handler).getCallableReference(); + } else { + throw new IllegalArgumentException("The object is not a known proxy."); + } + } + + /** + * @see org.apache.tuscany.sca.core.invocation.ProxyFactory#isProxyClass(java.lang.Class) + */ + public boolean isProxyClass(Class<?> clazz) { + return SCAProxy.isProxyClass(clazz); + } +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/MessageFactoryImpl.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/MessageFactoryImpl.java new file mode 100644 index 0000000000..6e182a6a14 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/MessageFactoryImpl.java @@ -0,0 +1,36 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core.invocation; + +import org.apache.tuscany.sca.invocation.Message; +import org.apache.tuscany.sca.invocation.MessageFactory; + +/** + * Implementation of MessageFactory. + * + * @version $Rev$ $Date$ + */ +public class MessageFactoryImpl implements MessageFactory { + + public Message createMessage() { + return new MessageImpl(); + } + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/MessageImpl.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/MessageImpl.java new file mode 100644 index 0000000000..ca2bf051c8 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/MessageImpl.java @@ -0,0 +1,113 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.invocation; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.tuscany.sca.core.assembly.EndpointReferenceImpl; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.Message; +import org.apache.tuscany.sca.runtime.EndpointReference; + +/** + * The default implementation of a message flowed through a wire during an invocation + * + * @version $Rev $Date$ + */ +public class MessageImpl implements Message { + private Object bindingContext; + private List<Object> headers = new ArrayList<Object>(); + private Object body; + private Object messageID; + private boolean isFault; + private Operation operation; + + private EndpointReference from; + private EndpointReference to; + + public MessageImpl() { + this.from = new EndpointReferenceImpl("/"); + this.to = new EndpointReferenceImpl("/"); + } + + @SuppressWarnings("unchecked") + public <T> T getBody() { + return (T)body; + } + + public <T> void setBody(T body) { + this.isFault = false; + this.body = body; + } + + public Object getMessageID() { + return messageID; + } + + public void setMessageID(Object messageId) { + this.messageID = messageId; + } + + public boolean isFault() { + return isFault; + } + + public void setFaultBody(Object fault) { + this.isFault = true; + this.body = fault; + } + + public EndpointReference getFrom() { + return from; + } + + public void setFrom(EndpointReference from) { + this.from = from; + } + + public EndpointReference getTo() { + return to; + } + + public void setTo(EndpointReference to) { + this.to = to; + } + + public Operation getOperation() { + return operation; + } + + public void setOperation(Operation op) { + this.operation = op; + } + + public List<Object> getHeaders() { + return headers; + } + + @SuppressWarnings("unchecked") + public <T> T getBindingContext() { + return (T)bindingContext; + } + + public <T> void setBindingContext(T bindingContext) { + this.bindingContext = bindingContext; + } +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/NoMethodForOperationException.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/NoMethodForOperationException.java new file mode 100644 index 0000000000..733544d387 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/NoMethodForOperationException.java @@ -0,0 +1,43 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.invocation; + + +/** + * Thrown when an {@link org.apache.tuscany.sca.core.factory.model.Operation} cannot be mapped to a method on an interface + * @version $Rev$ $Date$ + */ +public class NoMethodForOperationException extends ProxyCreationException { + private static final long serialVersionUID = 5116536602309483679L; + + public NoMethodForOperationException() { + } + + public NoMethodForOperationException(String message) { + super(message); + } + + public NoMethodForOperationException(String message, Throwable cause) { + super(message, cause); + } + + public NoMethodForOperationException(Throwable cause) { + super(cause); + } +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/NonBlockingInterceptor.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/NonBlockingInterceptor.java new file mode 100644 index 0000000000..d6911281c8 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/NonBlockingInterceptor.java @@ -0,0 +1,202 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.invocation; + +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.Interceptor; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.Message; +import org.apache.tuscany.sca.runtime.EndpointReference; +import org.apache.tuscany.sca.runtime.RuntimeWire; +import org.apache.tuscany.sca.work.WorkScheduler; +import org.osoa.sca.ServiceRuntimeException; + +/** + * Adds non-blocking behavior to an invocation chain + * + * @version $Rev$ $Date$ + */ +public class NonBlockingInterceptor implements Interceptor { + + private static final Message RESPONSE = new ImmutableMessage(); + + /** + * The JDK logger that will be used to log messages. + */ + private static final Logger LOGGER = Logger.getLogger(NonBlockingInterceptor.class.getName()); + + private WorkScheduler workScheduler; + private Invoker next; + + public NonBlockingInterceptor(WorkScheduler workScheduler) { + this.workScheduler = workScheduler; + } + + public NonBlockingInterceptor(WorkScheduler workScheduler, Interceptor next) { + this.workScheduler = workScheduler; + this.next = next; + } + + /** + * Sets desired workScheduler to NonBlockingInterceptor. This is a useful function for the extension framework + * to set desired workmanager on the InvocationChain, other than default workmanager which is set per Tuscany runtime. + * Using this function, extension framework can set desired workmanager on InvocationChain during post wire processing. + * @param workScheduler workScheduler which contains workmanager + */ + public void setWorkScheduler(WorkScheduler workScheduler){ + this.workScheduler = workScheduler; + } + + public Message invoke(final Message msg) { + // Schedule the invocation of the next interceptor in a new Work instance + try { + workScheduler.scheduleWork(new Runnable() { + public void run() { + Message context = ThreadMessageContext.setMessageContext(msg); + try { + Message response = null; + + Throwable ex = null; + try { + response = next.invoke(msg); + } catch (Throwable t) { + ex = t; + } + + // Tuscany-2225 - Did the @OneWay method complete successfully? + // (i.e. no exceptions) + if (response != null && response.isFault()) { + // The @OneWay method threw an Exception. Lets log it and + // then pass it on to the WorkScheduler so it can notify any + // listeners + ex = (Throwable)response.getBody(); + } + if (ex != null) { + LOGGER.log(Level.SEVERE, "Exception from @OneWay invocation", ex); + throw new ServiceRuntimeException("Exception from @OneWay invocation", ex); + } + } finally { + ThreadMessageContext.setMessageContext(context); + } + } + }); + } catch (Exception e) { + throw new ServiceRuntimeException(e); + } + return RESPONSE; + } + + public Invoker getNext() { + return next; + } + + public void setNext(Invoker next) { + this.next = next; + } + + /** + * A dummy message passed back on an invocation + */ + private static class ImmutableMessage implements Message { + + @SuppressWarnings("unchecked") + public Object getBody() { + return null; + } + + public void setBody(Object body) { + if (body != null) { + throw new UnsupportedOperationException(); + } + } + + public void setCallbackWires(LinkedList<RuntimeWire> wires) { + + } + + public Object getMessageID() { + return null; + } + + public void setMessageID(Object messageId) { + throw new UnsupportedOperationException(); + } + + public boolean isFault() { + return false; + } + + public void setFaultBody(Object fault) { + throw new UnsupportedOperationException(); + } + + public EndpointReference getFrom() { + return null; + } + + public EndpointReference getTo() { + return null; + } + + public void setFrom(EndpointReference from) { + throw new UnsupportedOperationException(); + } + + public void setTo(EndpointReference to) { + throw new UnsupportedOperationException(); + } + + public Operation getOperation() { + return null; + } + + public void setOperation(Operation op) { + throw new UnsupportedOperationException(); + } + + /** + * @see org.apache.tuscany.sca.invocation.Message#getReplyTo() + */ + public EndpointReference getReplyTo() { + return null; + } + + public Map<String, Object> getQoSContext() { + return null; + } + + public List<Object> getHeaders() { + return null; + } + + public <T> T getBindingContext() { + return null; + } + + public <T> void setBindingContext(T bindingContext) { + } + } + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/PhaseManager.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/PhaseManager.java new file mode 100644 index 0000000000..a3c8429c7b --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/PhaseManager.java @@ -0,0 +1,298 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core.invocation; + +import static org.apache.tuscany.sca.invocation.Phase.IMPLEMENTATION; +import static org.apache.tuscany.sca.invocation.Phase.IMPLEMENTATION_POLICY; +import static org.apache.tuscany.sca.invocation.Phase.REFERENCE; +import static org.apache.tuscany.sca.invocation.Phase.REFERENCE_BINDING; +import static org.apache.tuscany.sca.invocation.Phase.REFERENCE_BINDING_POLICY; +import static org.apache.tuscany.sca.invocation.Phase.REFERENCE_BINDING_TRANSPORT; +import static org.apache.tuscany.sca.invocation.Phase.REFERENCE_BINDING_WIREFORMAT; +import static org.apache.tuscany.sca.invocation.Phase.REFERENCE_INTERFACE; +import static org.apache.tuscany.sca.invocation.Phase.REFERENCE_POLICY; +import static org.apache.tuscany.sca.invocation.Phase.SERVICE; +import static org.apache.tuscany.sca.invocation.Phase.SERVICE_BINDING; +import static org.apache.tuscany.sca.invocation.Phase.SERVICE_BINDING_OPERATION_SELECTOR; +import static org.apache.tuscany.sca.invocation.Phase.SERVICE_BINDING_POLICY; +import static org.apache.tuscany.sca.invocation.Phase.SERVICE_BINDING_TRANSPORT; +import static org.apache.tuscany.sca.invocation.Phase.SERVICE_BINDING_WIREFORMAT; +import static org.apache.tuscany.sca.invocation.Phase.SERVICE_INTERFACE; +import static org.apache.tuscany.sca.invocation.Phase.SERVICE_POLICY; + +import java.io.IOException; +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 java.util.StringTokenizer; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.apache.tuscany.sca.extensibility.ServiceDeclaration; +import org.apache.tuscany.sca.extensibility.ServiceDiscovery; +import org.apache.tuscany.sca.invocation.Phase; +import org.osoa.sca.ServiceRuntimeException; + +/** + * @version $Rev$ $Date$ + */ +public class PhaseManager { + private static final Logger log = Logger.getLogger(PhaseManager.class.getName()); + + public static final String STAGE_REFERENCE = "reference"; + public static final String STAGE_REFERENCE_BINDING = "reference.binding"; + public static final String STAGE_SERVICE_BINDING = "service.binding"; + public static final String STAGE_SERVICE = "service"; + public static final String STAGE_IMPLEMENTATION = "implementation"; + + private static final String[] SYSTEM_REFERENCE_PHASES = + {REFERENCE, REFERENCE_INTERFACE, REFERENCE_POLICY, REFERENCE_BINDING}; + + private static final String[] SYSTEM_REFERENCE_BINDING_PHASES = + {REFERENCE_BINDING_WIREFORMAT, REFERENCE_BINDING_POLICY, REFERENCE_BINDING_TRANSPORT}; + + private static final String[] SYSTEM_SERVICE_BINDING_PHASES = + {SERVICE_BINDING_TRANSPORT, SERVICE_BINDING_OPERATION_SELECTOR, SERVICE_BINDING_WIREFORMAT, SERVICE_BINDING_POLICY}; + + private static final String[] SYSTEM_SERVICE_PHASES = + {SERVICE_BINDING, SERVICE_POLICY, SERVICE_INTERFACE, SERVICE}; + + private static final String[] SYSTEM_IMPLEMENTATION_PHASES = {IMPLEMENTATION_POLICY, IMPLEMENTATION}; + + private String pattern = Phase.class.getName(); + private Map<String, Stage> stages; + private List<String> phases; + + public class Stage { + private String name; + private PhaseSorter<String> sorter = new PhaseSorter<String>(); + private Set<String> firstSet = new HashSet<String>(); + private Set<String> lastSet = new HashSet<String>(); + private List<String> phases = new ArrayList<String>(); + + public Stage(String name) { + super(); + this.name = name; + } + + public String getName() { + return name; + } + + public PhaseSorter<String> getSorter() { + return sorter; + } + + public Set<String> getFirstSet() { + return firstSet; + } + + public Set<String> getLastSet() { + return lastSet; + } + + public List<String> getPhases() { + return phases; + } + + @Override + public String toString() { + return name + phases; + } + } + + // For unit test purpose + PhaseManager(String pattern) { + super(); + this.pattern = pattern; + } + + public PhaseManager() { + } + + private List<String> getPhases(String stage) { + Stage s = getStages().get(stage); + return s == null ? null : s.getPhases(); + } + + public List<String> getReferencePhases() { + return getPhases(STAGE_REFERENCE); + } + + public List<String> getServicePhases() { + return getPhases(STAGE_SERVICE); + } + + public List<String> getReferenceBindingPhases() { + return getPhases(STAGE_REFERENCE_BINDING); + } + + public List<String> getServiceBindingPhases() { + return getPhases(STAGE_SERVICE_BINDING); + } + + public List<String> getImplementationPhases() { + return getPhases(STAGE_IMPLEMENTATION); + } + + public synchronized List<String> getAllPhases() { + if (phases == null) { + phases = new ArrayList<String>(); + phases.addAll(getReferencePhases()); + phases.addAll(getReferenceBindingPhases()); + phases.addAll(getServiceBindingPhases()); + phases.addAll(getServicePhases()); + phases.addAll(getImplementationPhases()); + } + return phases; + } + + public synchronized Map<String, Stage> getStages() { + if (stages != null) { + return stages; + } + init(); + + Set<ServiceDeclaration> services; + try { + services = ServiceDiscovery.getInstance().getServiceDeclarations(pattern); + } catch (IOException e) { + throw new ServiceRuntimeException(e); + } + + for (ServiceDeclaration d : services) { + if (log.isLoggable(Level.FINE)) { + log.fine(d.getLocation() + ": " + d.getAttributes()); + } + String name = d.getAttributes().get("name"); + if (name == null) { + throw new ServiceRuntimeException("Required attribute 'name' is missing."); + } + String stageName = d.getAttributes().get("stage"); + if (stageName == null) { + throw new ServiceRuntimeException("Required attribute 'stage' is missing."); + } + Stage stage = stages.get(stageName); + if (stage == null) { + throw new ServiceRuntimeException("Invalid stage: " + stage); + } + PhaseSorter<String> graph = stage.getSorter(); + Set<String> firstSet = stage.getFirstSet(), lastSet = stage.getLastSet(); + + String before = d.getAttributes().get("before"); + String after = d.getAttributes().get("after"); + if (before != null) { + StringTokenizer tokenizer = new StringTokenizer(before); + while (tokenizer.hasMoreTokens()) { + String p = tokenizer.nextToken(); + if (!"*".equals(p)) { + graph.addEdge(name, p); + } else { + firstSet.add(name); + } + } + } + if (after != null) { + StringTokenizer tokenizer = new StringTokenizer(after); + while (tokenizer.hasMoreTokens()) { + String p = tokenizer.nextToken(); + if (!"*".equals(p)) { + graph.addEdge(p, name); + } else { + lastSet.add(name); + } + } + } + graph.addVertext(name); + if(firstSet.size()>1) { + log.warning("More than one phases are declared to be first: "+firstSet); + } + for (String s : firstSet) { + for (String v : new HashSet<String>(graph.getVertices().keySet())) { + if (!firstSet.contains(v)) { + graph.addEdge(s, v); + } + } + } + if(lastSet.size()>1) { + log.warning("More than one phases are declared to be the last: "+lastSet); + } + for (String s : lastSet) { + for (String v : new HashSet<String>(graph.getVertices().keySet())) { + if (!lastSet.contains(v)) { + graph.addEdge(v, s); + } + } + } + + } + + for (Stage s : stages.values()) { + List<String> phases = s.getSorter().topologicalSort(false); + s.getPhases().clear(); + s.getPhases().addAll(phases); + } + if (log.isLoggable(Level.FINE)) { + log.fine("Stages: " + stages); + } + return stages; + } + + private void init() { + stages = new HashMap<String, Stage>(); + + Stage referenceStage = new Stage(STAGE_REFERENCE); + for (int i = 1; i < SYSTEM_REFERENCE_PHASES.length; i++) { + referenceStage.getSorter().addEdge(SYSTEM_REFERENCE_PHASES[i - 1], SYSTEM_REFERENCE_PHASES[i]); + } + referenceStage.getLastSet().add(REFERENCE_BINDING); + stages.put(referenceStage.getName(), referenceStage); + + Stage referenceBindingStage = new Stage(STAGE_REFERENCE_BINDING); + for (int i = 1; i < SYSTEM_REFERENCE_BINDING_PHASES.length; i++) { + referenceBindingStage.getSorter().addEdge(SYSTEM_REFERENCE_BINDING_PHASES[i - 1], SYSTEM_REFERENCE_BINDING_PHASES[i]); + } + stages.put(referenceBindingStage.getName(), referenceBindingStage); + + Stage serviceBindingStage = new Stage(STAGE_SERVICE_BINDING); + for (int i = 1; i < SYSTEM_SERVICE_BINDING_PHASES.length; i++) { + serviceBindingStage.getSorter().addEdge(SYSTEM_SERVICE_BINDING_PHASES[i - 1], SYSTEM_SERVICE_BINDING_PHASES[i]); + } + stages.put(serviceBindingStage.getName(), serviceBindingStage); + + + Stage serviceStage = new Stage(STAGE_SERVICE); + for (int i = 1; i < SYSTEM_SERVICE_PHASES.length; i++) { + serviceStage.getSorter().addEdge(SYSTEM_SERVICE_PHASES[i - 1], SYSTEM_SERVICE_PHASES[i]); + } + stages.put(serviceStage.getName(), serviceStage); + + Stage implementationStage = new Stage(STAGE_IMPLEMENTATION); + for (int i = 1; i < SYSTEM_IMPLEMENTATION_PHASES.length; i++) { + implementationStage.getSorter().addEdge(SYSTEM_IMPLEMENTATION_PHASES[i - 1], + SYSTEM_IMPLEMENTATION_PHASES[i]); + } + implementationStage.getLastSet().add(IMPLEMENTATION); + stages.put(implementationStage.getName(), implementationStage); + } +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/PhaseSorter.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/PhaseSorter.java new file mode 100644 index 0000000000..fc4bea3d9f --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/PhaseSorter.java @@ -0,0 +1,236 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.invocation; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Directed, weighted graph + * + * @param <V> The type of vertex object + * @param <E> The type of edge object + * + * @version $Rev$ $Date$ + */ +public class PhaseSorter<V> implements Cloneable { + private final Map<V, Vertex> vertices = new HashMap<V, Vertex>(); + + /** + * Vertex of a graph + */ + public final class Vertex { + private V value; + + // TODO: Do we want to support multiple edges for a vertex pair? If so, + // we should use a List instead of Map + private Map<Vertex, Edge> outEdges = new HashMap<Vertex, Edge>(); + private Map<Vertex, Edge> inEdges = new HashMap<Vertex, Edge>(); + + private Vertex(V value) { + this.value = value; + } + + @Override + public String toString() { + return "(" + value + ")"; + } + + public V getValue() { + return value; + } + + public Map<Vertex, Edge> getOutEdges() { + return outEdges; + } + + public Map<Vertex, Edge> getInEdges() { + return inEdges; + } + + } + + /** + * An Edge connects two vertices in one direction + */ + public final class Edge { + private Vertex sourceVertex; + + private Vertex targetVertex; + + public Edge(Vertex source, Vertex target) { + this.sourceVertex = source; + this.targetVertex = target; + } + + @Override + public String toString() { + return sourceVertex + "->" + targetVertex; + } + + public Vertex getTargetVertex() { + return targetVertex; + } + + public void setTargetVertex(Vertex vertex) { + this.targetVertex = vertex; + } + + public Vertex getSourceVertex() { + return sourceVertex; + } + + public void setSourceVertex(Vertex sourceVertex) { + this.sourceVertex = sourceVertex; + } + } + + public void addEdge(V source, V target) { + Vertex s = getVertex(source); + if (s == null) { + s = new Vertex(source); + vertices.put(source, s); + } + Vertex t = getVertex(target); + if (t == null) { + t = new Vertex(target); + vertices.put(target, t); + } + Edge edge = new Edge(s, t); + s.outEdges.put(t, edge); + t.inEdges.put(s, edge); + } + + public void addVertext(V source) { + Vertex s = getVertex(source); + if (s == null) { + s = new Vertex(source); + vertices.put(source, s); + } + } + + public Vertex getVertex(V source) { + Vertex s = vertices.get(source); + return s; + } + + public boolean removeEdge(V source, V target) { + Vertex s = getVertex(source); + if (s == null) { + return false; + } + + Vertex t = getVertex(target); + if (t == null) { + return false; + } + + return s.outEdges.remove(t) != null && t.inEdges.remove(s) != null; + + } + + public void removeEdge(Edge edge) { + edge.sourceVertex.outEdges.remove(edge.targetVertex); + edge.targetVertex.inEdges.remove(edge.sourceVertex); + } + + public void removeVertex(Vertex vertex) { + vertices.remove(vertex.getValue()); + for (Edge e : new ArrayList<Edge>(vertex.outEdges.values())) { + removeEdge(e); + } + for (Edge e : new ArrayList<Edge>(vertex.inEdges.values())) { + removeEdge(e); + } + } + + public Edge getEdge(Vertex source, Vertex target) { + return source.outEdges.get(target); + } + + public Edge getEdge(V source, V target) { + Vertex sv = getVertex(source); + if (sv == null) { + return null; + } + Vertex tv = getVertex(target); + if (tv == null) { + return null; + } + return getEdge(getVertex(source), getVertex(target)); + } + + @Override + public String toString() { + StringBuffer sb = new StringBuffer(); + for (Vertex v : vertices.values()) { + sb.append(v.outEdges.values()).append("\n"); + } + return sb.toString(); + } + + public Map<V, Vertex> getVertices() { + return vertices; + } + + public void addGraph(PhaseSorter<V> otherGraph) { + for (Vertex v : otherGraph.vertices.values()) { + for (Edge e : v.outEdges.values()) { + addEdge(e.sourceVertex.value, e.targetVertex.value); + } + } + } + + private Vertex getFirst() { + for (Vertex v : vertices.values()) { + if (v.inEdges.isEmpty()) { + return v; + } + } + if (!vertices.isEmpty()) { + throw new IllegalArgumentException("Circular ordering has been detected: " + toString()); + } else { + return null; + } + } + + public List<V> topologicalSort(boolean readOnly) { + PhaseSorter<V> graph = (!readOnly) ? this : (PhaseSorter<V>)clone(); + List<V> list = new ArrayList<V>(); + while (true) { + Vertex v = graph.getFirst(); + if (v == null) { + break; + } + list.add(v.getValue()); + graph.removeVertex(v); + } + + return list; + } + + @Override + public Object clone() { + PhaseSorter<V> copy = new PhaseSorter<V>(); + copy.addGraph(this); + return copy; + } +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/ProxyCreationException.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/ProxyCreationException.java new file mode 100644 index 0000000000..0b36b178f3 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/ProxyCreationException.java @@ -0,0 +1,48 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.invocation; + +import org.apache.tuscany.sca.core.factory.ObjectCreationException; + + +/** + * Denotes an error creating a proxy + * + * @version $Rev$ $Date$ + */ +public class ProxyCreationException extends ObjectCreationException { + private static final long serialVersionUID = 8002454344828513781L; + + public ProxyCreationException() { + super(); + } + + public ProxyCreationException(String message, Throwable cause) { + super(message, cause); + } + + public ProxyCreationException(String message) { + super(message); + } + + public ProxyCreationException(Throwable cause) { + super(cause); + } + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/ProxyFactory.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/ProxyFactory.java new file mode 100644 index 0000000000..cb836e42c1 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/ProxyFactory.java @@ -0,0 +1,87 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.invocation; + +import java.util.List; + +import org.apache.tuscany.sca.runtime.RuntimeWire; +import org.osoa.sca.CallableReference; + +/** + * Creates proxies that implement Java interfaces and invocation handlers for fronting wires + * + * @version $Rev$ $Date$ + */ + +public interface ProxyFactory { + + /** + * Creates a Java proxy for the given wire + * + * @param interfaze the interface the proxy implements + * @param wire the wire to proxy + * @return the proxy + * @throws ProxyCreationException + */ + <T> T createProxy(Class<T> interfaze, RuntimeWire wire) throws ProxyCreationException; + + /** + * Creates a Java proxy for the given CallableReference + * + * @param callableReference The CallableReference + * @return the proxy + * @throws ProxyCreationException + */ + <T> T createProxy(CallableReference<T> callableReference) throws ProxyCreationException; + + /** + * Creates a Java proxy for the service contract callback + * + * @param interfaze the interface the proxy should implement + * @return the proxy + * @throws ProxyCreationException + */ + <T> T createCallbackProxy(Class<T> interfaze, List<RuntimeWire> wires) throws ProxyCreationException; + + /** + * Creates a Java proxy for the given callback reference + * + * @param callableReference The CallableReference + * @return the proxy + * @throws ProxyCreationException + */ + <T> T createCallbackProxy(CallbackReferenceImpl<T> callbackReference) throws ProxyCreationException; + + /** + * Cast a proxy to a CallableReference. + * + * @param target a proxy generated by this implementation + * @return a CallableReference (or subclass) equivalent to this proxy + * @throws IllegalArgumentException if the object supplied is not a proxy + */ + <B, R extends CallableReference<B>> R cast(B target) throws IllegalArgumentException; + + /** + * Test if a given class is a generated proxy class by this factory + * @param clazz A java class or interface + * @return true if the class is a generated proxy class by this factory + */ + boolean isProxyClass(Class<?> clazz); + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/ProxyFactoryExtensionPoint.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/ProxyFactoryExtensionPoint.java new file mode 100644 index 0000000000..875a252798 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/ProxyFactoryExtensionPoint.java @@ -0,0 +1,53 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core.invocation; + + +/** + * The extension point to plug in proxy factories + * @version $Rev$ $Date$ + */ +public interface ProxyFactoryExtensionPoint { + + /** + * Get the proxy factory for java interfaces + * @return + */ + ProxyFactory getInterfaceProxyFactory(); + + /** + * Get the proxy factory for java classes + * @return + */ + ProxyFactory getClassProxyFactory(); + + /** + * Set the proxy factory for java interfaces + * @param factory + */ + void setInterfaceProxyFactory(ProxyFactory factory); + + /** + * Set the proxy factory for java classes + * @param factory + */ + void setClassProxyFactory(ProxyFactory factory); + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/RuntimeWireInvoker.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/RuntimeWireInvoker.java new file mode 100644 index 0000000000..906628ee32 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/RuntimeWireInvoker.java @@ -0,0 +1,264 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core.invocation; + +import java.lang.reflect.InvocationTargetException; + +import org.apache.tuscany.sca.core.context.InstanceWrapper; +import org.apache.tuscany.sca.core.conversation.ConversationManager; +import org.apache.tuscany.sca.core.conversation.ConversationState; +import org.apache.tuscany.sca.core.conversation.ExtendedConversation; +import org.apache.tuscany.sca.core.scope.Scope; +import org.apache.tuscany.sca.core.scope.ScopeContainer; +import org.apache.tuscany.sca.core.scope.ScopedRuntimeComponent; +import org.apache.tuscany.sca.core.scope.TargetDestructionException; +import org.apache.tuscany.sca.core.scope.TargetResolutionException; +import org.apache.tuscany.sca.interfacedef.ConversationSequence; +import org.apache.tuscany.sca.interfacedef.InterfaceContract; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.InvocationChain; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.Message; +import org.apache.tuscany.sca.invocation.MessageFactory; +import org.apache.tuscany.sca.runtime.EndpointReference; +import org.apache.tuscany.sca.runtime.ReferenceParameters; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeWire; +import org.osoa.sca.ConversationEndedException; +import org.osoa.sca.ServiceRuntimeException; + +/** + * @version $Rev$ $Date$ + */ +public class RuntimeWireInvoker implements Invoker{ + protected ConversationManager conversationManager; + protected boolean conversational; + protected ExtendedConversation conversation; + protected MessageFactory messageFactory; + protected Object conversationID; + protected Object callbackID; + protected Object callbackObject; + protected RuntimeWire wire; + + public RuntimeWireInvoker(MessageFactory messageFactory, ConversationManager conversationManager, RuntimeWire wire) { + this.messageFactory = messageFactory; + this.wire = wire; + this.conversationManager = conversationManager; + init(wire); + } + + protected void init(RuntimeWire wire) { + if (wire != null) { + ReferenceParameters parameters = wire.getSource().getReferenceParameters(); + this.callbackID = parameters.getCallbackID(); + this.callbackObject = parameters.getCallbackReference(); + this.conversationID = parameters.getConversationID(); + InterfaceContract contract = wire.getSource().getInterfaceContract(); + this.conversational = contract.getInterface().isConversational(); + } + } + + /* + * TODO - Introduced to allow the RuntimeWireInvoker to sit on the end of the + * service binding chain. Runtime wire invoke needs splitting up into + * separate conversation, callback interceptors etc. + */ + public Message invoke(Message msg) { + + try { + Object response = invoke(msg.getOperation(),msg); + // Hack to put the response back in a message. + // shouldn't take it out of the response message in the first place + msg.setBody(response); + } catch (InvocationTargetException e) { +// throw new ServiceRuntimeException(e); + } + + return msg; + } + + public Object invoke(Operation operation, Message msg) throws InvocationTargetException { + return invoke(wire, operation, msg); + } + + public Object invoke(RuntimeWire wire, Operation operation, Message msg) throws InvocationTargetException { + RuntimeWire runtimeWire = wire == null ? this.wire : wire; + InvocationChain chain = runtimeWire.getInvocationChain(operation); + return invoke(chain, msg, runtimeWire); + } + + protected Object invoke(InvocationChain chain, Message msg, RuntimeWire wire) throws InvocationTargetException { + EndpointReference from = msg.getFrom(); + EndpointReference epFrom = wire.getSource(); + if (from != null) { + from.mergeEndpoint(epFrom); + } else { + msg.setFrom(epFrom); + } + msg.setTo(wire.getTarget()); + + Invoker headInvoker = chain.getHeadInvoker(); + Operation operation = chain.getTargetOperation(); + msg.setOperation(operation); + + Message msgContext = ThreadMessageContext.getMessageContext(); + Object currentConversationID = msgContext.getFrom().getReferenceParameters().getConversationID(); + + ThreadMessageContext.setMessageContext(msg); + try { + conversationPreinvoke(msg); + // handleCallback(msg, currentConversationID); + // dispatch the wire down the chain and get the response + Message resp = headInvoker.invoke(msg); + Object body = resp.getBody(); + if (resp.isFault()) { + throw new InvocationTargetException((Throwable)body); + } + return body; + } catch (InvocationTargetException e) { + throw e; + } catch (Throwable e) { + throw new ServiceRuntimeException(e); + } finally { + try { + conversationPostInvoke(msg); + } catch (TargetDestructionException e) { + throw new ServiceRuntimeException(e); + } finally { + ThreadMessageContext.setMessageContext(msgContext); + } + } + } + + /** + * @param msgContext + */ + protected EndpointReference getCallbackEndpoint(Message msgContext) { + EndpointReference from = msgContext.getFrom(); + return from == null ? null : from.getReferenceParameters().getCallbackReference(); + } + + /** + * Pre-invoke for the conversation handling + * @param msg + * @throws TargetResolutionException + */ + private void conversationPreinvoke(Message msg) { + if (conversational) { + ReferenceParameters parameters = msg.getFrom().getReferenceParameters(); + // in some cases the ConversationID that should be used comes in with the + // message, e.g. when ws binding is in use. + Object convID = parameters.getConversationID(); + if (convID != null) { + conversationID = convID; + } + conversation = conversationManager.getConversation(conversationID); + + if (conversation == null || conversation.getState() == ConversationState.ENDED) { + conversation = conversationManager.startConversation(conversationID); + conversation.initializeConversationAttributes(wire.getTarget().getComponent()); + } else if (conversation.conversationalAttributesInitialized() == false) { + conversation.initializeConversationAttributes(wire.getTarget().getComponent()); + } else if (conversation.isExpired()){ + throw new ConversationEndedException("Conversation has expired."); + } + + conversation.updateLastReferencedTime(); + + parameters.setConversationID(conversation.getConversationID()); + } + } + + /** + * Post-invoke for the conversation handling + * @param wire + * @param operation + * @throws TargetDestructionException + */ + @SuppressWarnings("unchecked") + private void conversationPostInvoke(Message msg) throws TargetDestructionException { + if (conversational) { + Operation operation = msg.getOperation(); + ConversationSequence sequence = operation.getConversationSequence(); + if (sequence == ConversationSequence.CONVERSATION_END) { + // in some cases the ConversationID that should be used comes in with the + // message, e.g. when ws binding is in use. + Object convID = msg.getFrom().getReferenceParameters().getConversationID(); + if (convID != null) { + conversationID = convID; + } + conversation = conversationManager.getConversation(conversationID); + + // remove conversation id from scope container + ScopeContainer scopeContainer = getConversationalScopeContainer(msg); + + if (scopeContainer != null) { + scopeContainer.remove(conversation.getConversationID()); + } + + conversation.end(); + } + } + } + + @SuppressWarnings("unchecked") + private ScopeContainer getConversationalScopeContainer(Message msg) { + ScopeContainer scopeContainer = null; + + RuntimeComponent component = msg.getTo().getComponent(); + + if (component instanceof ScopedRuntimeComponent) { + ScopedRuntimeComponent scopedRuntimeComponent = (ScopedRuntimeComponent)component; + ScopeContainer container = scopedRuntimeComponent.getScopeContainer(); + + if ((container != null) && (container.getScope() == Scope.CONVERSATION)) { + scopeContainer = container; + } + } + + return scopeContainer; + } + + + /** + * Minimal wrapper for a callback object contained in a ServiceReference + */ + private static class CallbackObjectWrapper<T> implements InstanceWrapper<T> { + + private T instance; + + private CallbackObjectWrapper(T instance) { + this.instance = instance; + } + + public T getInstance() { + return instance; + } + + public void start() { + // do nothing + } + + public void stop() { + // do nothing + } + } + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/SCAProxy.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/SCAProxy.java new file mode 100644 index 0000000000..1112d02b7e --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/SCAProxy.java @@ -0,0 +1,74 @@ +/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tuscany.sca.core.invocation;
+
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Proxy;
+import java.lang.reflect.Constructor;
+import java.util.WeakHashMap;
+
+public class SCAProxy extends Proxy
+{
+ protected SCAProxy (InvocationHandler handler) {
+ super(handler);
+ }
+
+ // This is a cache containing the proxy class constructor for each business interface.
+ // This improves performance compared to calling Proxy.newProxyInstance()
+ // every time that a proxy is needed.
+ private static WeakHashMap cache = new WeakHashMap<Class, Object>();
+
+ public static Object newProxyInstance(ClassLoader classloader, Class aclass[], InvocationHandler invocationhandler)
+ throws IllegalArgumentException
+ {
+ try {
+ if(invocationhandler == null)
+ throw new NullPointerException();
+ // Lookup cached constructor. aclass[0] is the reference's business interface.
+ Constructor proxyCTOR;
+ synchronized(cache) {
+ proxyCTOR = (Constructor) cache.get(aclass[0]);
+ }
+ if(proxyCTOR == null) {
+ Class proxyClass = getProxyClass(classloader, aclass);
+ proxyCTOR = proxyClass.getConstructor(constructorParams);
+ synchronized(cache){
+ cache.put(aclass[0],proxyCTOR);
+ }
+ }
+ return proxyCTOR.newInstance(new Object[] { invocationhandler });
+ }
+ catch(NoSuchMethodException e) {
+ throw new InternalError(e.toString());
+ }
+ catch(IllegalAccessException e) {
+ throw new InternalError(e.toString());
+ }
+ catch (InstantiationException e) {
+ throw new InternalError(e.toString());
+ }
+ catch (InvocationTargetException e) {
+ throw new InternalError(e.toString());
+ }
+ }
+
+ private static final Class constructorParams[] = { InvocationHandler.class };
+
+}
\ No newline at end of file diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/TargetInvocationException.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/TargetInvocationException.java new file mode 100644 index 0000000000..2c4d657882 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/TargetInvocationException.java @@ -0,0 +1,45 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.invocation; + +/** + * Raised when an error is encountered during a target invocation + * + * @version $Rev$ $Date$ + */ +public class TargetInvocationException extends Exception { + + private static final long serialVersionUID = -6553427708442761743L; + + public TargetInvocationException() { + super(); + } + + public TargetInvocationException(String message, Throwable cause) { + super(message, cause); + } + + public TargetInvocationException(String message) { + super(message); + } + + public TargetInvocationException(Throwable cause) { + super(cause); + } +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/ThreadMessageContext.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/ThreadMessageContext.java new file mode 100644 index 0000000000..504bd9b036 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/ThreadMessageContext.java @@ -0,0 +1,72 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.invocation; + +import org.apache.tuscany.sca.core.assembly.EndpointReferenceImpl; +import org.apache.tuscany.sca.invocation.Message; + +/** + * Class for tunnelling a WorkContext through the invocation of a user class. + * + * @version $Rev$ $Date$ + */ +public final class ThreadMessageContext { + + private static final ThreadLocal<Message> CONTEXT = new ThreadLocal<Message>() { + @Override + protected synchronized Message initialValue() { + Message msg = new MessageImpl(); + msg.setFrom(new EndpointReferenceImpl("/")); + return msg; + } + }; + + private ThreadMessageContext() { + } + + /** + * Set the WorkContext for the current thread. + * The current work context is returned and must be restored after the invocation is complete. + * Typical usage would be: + * <pre> + * WorkContext old = PojoWorkContextTunnel.setThreadWorkContext(newContext); + * try { + * ... invoke user code ... + * } finally { + * PojoWorkContextTunnel.setThreadWorkContext(old); + * } + * </pre> + * @param context + * @return the current work context for the thread; this must be restored after the invocation is made + */ + public static Message setMessageContext(Message context) { + Message old = CONTEXT.get(); + CONTEXT.set(context); + return old; + } + + /** + * Returns the WorkContext for the current thread. + * + * @return the WorkContext for the current thread + */ + public static Message getMessageContext() { + return CONTEXT.get(); + } +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/WireObjectFactory.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/WireObjectFactory.java new file mode 100644 index 0000000000..246f9c45d6 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/WireObjectFactory.java @@ -0,0 +1,54 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.invocation; + +import org.apache.tuscany.sca.core.context.ServiceReferenceImpl; +import org.apache.tuscany.sca.core.factory.ObjectCreationException; +import org.apache.tuscany.sca.core.factory.ObjectFactory; +import org.apache.tuscany.sca.runtime.RuntimeWire; + +/** + * Uses a wire to return an object instance + * + * @version $Rev$ $Date$ + */ +public class WireObjectFactory<T> implements ObjectFactory<T> { + private Class<T> interfaze; + private RuntimeWire wire; + private ProxyFactory proxyService; + + /** + * Constructor. + * + * @param interfaze the interface to inject on the client + * @param wire the backing wire + * @param proxyService the wire service to create the proxy + * @throws NoMethodForOperationException + */ + public WireObjectFactory(Class<T> interfaze, RuntimeWire wire, ProxyFactory proxyService) { + this.interfaze = interfaze; + this.wire = wire; + this.proxyService = proxyService; + } + + public T getInstance() throws ObjectCreationException { + return new ServiceReferenceImpl<T>(interfaze, wire, proxyService).getProxy(); + } + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/AbstractScopeContainer.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/AbstractScopeContainer.java new file mode 100644 index 0000000000..1168d1d0dd --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/AbstractScopeContainer.java @@ -0,0 +1,200 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.scope; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.apache.tuscany.sca.core.context.InstanceWrapper; +import org.apache.tuscany.sca.event.Event; +import org.apache.tuscany.sca.provider.ImplementationProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponent; + +/** + * Implements functionality common to scope contexts. + * + * @version $Rev$ $Date$ + */ +public abstract class AbstractScopeContainer<KEY> implements ScopeContainer<KEY> { + protected Map<KEY, InstanceWrapper<?>> wrappers = new ConcurrentHashMap<KEY, InstanceWrapper<?>>(); + protected final Scope scope; + + protected RuntimeComponent component; + protected volatile int lifecycleState = UNINITIALIZED; + + + public AbstractScopeContainer(Scope scope, RuntimeComponent component) { + this.scope = scope; + this.component = component; + } + + protected void checkInit() { + if (getLifecycleState() != RUNNING) { + throw new IllegalStateException("Scope container not running [" + getLifecycleState() + "]"); + } + } + + /** + * Creates a new physical instance of a component, wrapped in an + * InstanceWrapper. + * + * @param component the component whose instance should be created + * @return a wrapped instance that has been injected but not yet started + * @throws TargetResolutionException if there was a problem creating the + * instance + */ + protected InstanceWrapper createInstanceWrapper() throws TargetResolutionException { + ImplementationProvider implementationProvider = component.getImplementationProvider(); + if (implementationProvider instanceof ScopedImplementationProvider) { + return ((ScopedImplementationProvider)implementationProvider).createInstanceWrapper(); + } + return null; + } + + public InstanceWrapper getAssociatedWrapper(KEY contextId) throws TargetResolutionException { + return getWrapper(contextId); // TODO: what is this method supposed to do diff than getWrapper? + } + + public Scope getScope() { + return scope; + } + + public InstanceWrapper getWrapper(KEY contextId) throws TargetResolutionException { + return wrappers.get(contextId); + } + + public void addWrapperReference(KEY existingContextId, KEY newContextId) + throws TargetResolutionException { + // do nothing here. the conversational scope container implements this + } + + public void registerWrapper(InstanceWrapper wrapper, KEY contextId) throws TargetResolutionException { + // do nothing here. the conversational scope container implements this + } + + public void onEvent(Event event) { + } + + protected boolean isEagerInit() { + ImplementationProvider implementationProvider = ((RuntimeComponent)component).getImplementationProvider(); + if (implementationProvider instanceof ScopedImplementationProvider) { + return ((ScopedImplementationProvider)implementationProvider).isEagerInit(); + } + return false; + } + + public void returnWrapper(InstanceWrapper wrapper, KEY contextId) throws TargetDestructionException { + } + + /** + * Default implementation of remove which does nothing + * + * @param contextId the identifier of the context to remove. + */ + public void remove(KEY contextId) + throws TargetDestructionException { + } + + public synchronized void start() { + int lifecycleState = getLifecycleState(); + if (lifecycleState != UNINITIALIZED && lifecycleState != STOPPED) { + throw new IllegalStateException("Scope must be in UNINITIALIZED or STOPPED state [" + lifecycleState + "]"); + } + setLifecycleState(RUNNING); + } + + public void startContext(KEY contextId) { + if(isEagerInit()) { + try { + getWrapper(contextId); + } catch (TargetResolutionException e) { + // + } + } + } + + public synchronized void stop() { + int lifecycleState = getLifecycleState(); + if (lifecycleState != RUNNING) { + throw new IllegalStateException("Scope in wrong state [" + lifecycleState + "]"); + } + setLifecycleState(STOPPED); + } + + public void stopContext(KEY contextId) { + wrappers.remove(contextId); + } + + @Override + public String toString() { + String s; + switch (lifecycleState) { + case ScopeContainer.CONFIG_ERROR: + s = "CONFIG_ERROR"; + break; + case ScopeContainer.ERROR: + s = "ERROR"; + break; + case ScopeContainer.INITIALIZING: + s = "INITIALIZING"; + break; + case ScopeContainer.INITIALIZED: + s = "INITIALIZED"; + break; + case ScopeContainer.RUNNING: + s = "RUNNING"; + break; + case ScopeContainer.STOPPING: + s = "STOPPING"; + break; + case ScopeContainer.STOPPED: + s = "STOPPED"; + break; + case ScopeContainer.UNINITIALIZED: + s = "UNINITIALIZED"; + break; + default: + s = "UNKNOWN"; + break; + } + return "In state [" + s + ']'; + } + + public RuntimeComponent getComponent() { + return component; + } + + public void setComponent(RuntimeComponent component) { + this.component = component; + } + + public int getLifecycleState() { + return lifecycleState; + } + + /** + * Set the current state of the Lifecycle. + * + * @param lifecycleState the new state + */ + protected void setLifecycleState(int lifecycleState) { + this.lifecycleState = lifecycleState; + } + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/CompositeScopeContainer.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/CompositeScopeContainer.java new file mode 100644 index 0000000000..7a1965198a --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/CompositeScopeContainer.java @@ -0,0 +1,90 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.scope; + +import org.apache.tuscany.sca.core.context.InstanceWrapper; +import org.apache.tuscany.sca.runtime.RuntimeComponent; + +/** + * A scope context which manages atomic component instances keyed by composite + * + * @version $Rev$ $Date$ + */ +public class CompositeScopeContainer<KEY> extends AbstractScopeContainer<KEY> { + private InstanceWrapper<?> wrapper; + + public CompositeScopeContainer(RuntimeComponent component) { + super(Scope.COMPOSITE, component); + } + + @Override + public synchronized void stop() { + super.stop(); + if (wrapper != null) { + try { + wrapper.stop(); + } catch (TargetDestructionException e) { + throw new IllegalStateException(e); + } + } + wrapper = null; + } + + @Override + public synchronized InstanceWrapper getWrapper(KEY contextId) throws TargetResolutionException { + if (wrapper == null) { + wrapper = createInstanceWrapper(); + try { + wrapper.start(); + } catch (ThreadDeath td) { + throw td; + } catch (Throwable e) { + try { + wrapper.stop(); + } catch (ThreadDeath td) { + throw td; + } catch (Throwable e2) { + } + wrapper = null; + throw new TargetInitializationException(e); + } + } + return wrapper; + } + + @Override + public InstanceWrapper getAssociatedWrapper(KEY contextId) throws TargetResolutionException { + if (wrapper == null) { + throw new TargetNotFoundException(component.getURI()); + } + return wrapper; + } + + @Override + public synchronized void start() { + super.start(); + if (isEagerInit()) { + try { + getWrapper(null); + } catch (TargetResolutionException e) { + throw new IllegalStateException(e); + } + } + } +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/CompositeScopeContainerFactory.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/CompositeScopeContainerFactory.java new file mode 100644 index 0000000000..786988613b --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/CompositeScopeContainerFactory.java @@ -0,0 +1,37 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core.scope; + +import org.apache.tuscany.sca.runtime.RuntimeComponent; + +/** + * @version $Rev$ $Date$ + */ +public class CompositeScopeContainerFactory implements ScopeContainerFactory { + + public ScopeContainer createScopeContainer(RuntimeComponent component) { + return new CompositeScopeContainer(component); + } + + public Scope getScope() { + return Scope.COMPOSITE; + } + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/ConversationalScopeContainer.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/ConversationalScopeContainer.java new file mode 100644 index 0000000000..3ae1ca51c5 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/ConversationalScopeContainer.java @@ -0,0 +1,290 @@ +/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.tuscany.sca.core.scope;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.apache.tuscany.sca.core.context.InstanceWrapper;
+import org.apache.tuscany.sca.core.conversation.ConversationListener;
+import org.apache.tuscany.sca.core.conversation.ConversationManager;
+import org.apache.tuscany.sca.core.conversation.ExtendedConversation;
+import org.apache.tuscany.sca.core.invocation.ThreadMessageContext;
+import org.apache.tuscany.sca.invocation.Message;
+import org.apache.tuscany.sca.runtime.RuntimeComponent;
+import org.apache.tuscany.sca.store.Store;
+
+/**
+ * A scope context which manages atomic component instances keyed on ConversationID
+ *
+ * @version $Rev$ $Date$
+ */
+public class ConversationalScopeContainer extends AbstractScopeContainer<Object> implements ConversationListener {
+ private ConversationManager conversationManager;
+ private Map<Object, InstanceLifeCycleWrapper> instanceLifecycleCollection =
+ new ConcurrentHashMap<Object, InstanceLifeCycleWrapper>();
+
+ public ConversationalScopeContainer(Store aStore, RuntimeComponent component) {
+ super(Scope.CONVERSATION, component);
+
+ // Note: aStore is here to preserve the original factory interface. It is not currently used in this
+ // implementation since we do not support instance persistence.
+
+ // Check System properties to see if timeout values have been specified. All timeout values
+ // will be specified in seconds.
+ //
+
+ }
+
+
+ protected InstanceWrapper getInstanceWrapper(boolean create, Object contextId) throws TargetResolutionException {
+
+ // we might get a null context if the target service has
+ // conversational scope but only its callback interface
+ // is conversational. In this case we need to invent a
+ // conversation Id here to store the service against
+ // and populate the thread context
+ if (contextId == null) {
+ contextId = UUID.randomUUID().toString();
+ Message msgContext = ThreadMessageContext.getMessageContext();
+
+ if (msgContext != null) {
+ msgContext.getFrom().getReferenceParameters().setConversationID(contextId);
+ }
+ }
+
+ InstanceLifeCycleWrapper anInstanceWrapper = this.instanceLifecycleCollection.get(contextId);
+
+ if (anInstanceWrapper == null && !create)
+ return null;
+
+ if (anInstanceWrapper == null) {
+ anInstanceWrapper = new InstanceLifeCycleWrapper(contextId);
+ this.instanceLifecycleCollection.put(contextId, anInstanceWrapper);
+ }
+
+ return anInstanceWrapper.getInstanceWrapper(contextId);
+
+ }
+
+ @Override
+ public InstanceWrapper getWrapper(Object contextId) throws TargetResolutionException {
+ return getInstanceWrapper(true, contextId);
+ }
+
+ /**
+ * This method allows a new context id to be registered alongside an existing one. This happens in
+ * one case, when a conversation includes a stateful callback. The client component instance
+ * must be registered against all outgoing conversation ids so that the component instance
+ * can be found when the callback arrives
+ *
+ * @param existingContextId the context id against which the component is already registered
+ * @param context this should be a conversation object so that the conversation can b stored
+ * and reset when the component instance is removed
+ */
+ @Override
+ public void addWrapperReference(Object existingContextId, Object contextId) throws TargetResolutionException {
+
+
+ // get the instance wrapper via the existing id
+ InstanceLifeCycleWrapper existingInstanceWrapper = this.instanceLifecycleCollection.get(existingContextId);
+ InstanceLifeCycleWrapper newInstanceWrapper = this.instanceLifecycleCollection.get(contextId);
+
+ // only add the extra reference once
+ if (newInstanceWrapper == null) {
+ // add the id to the list of ids that the wrapper holds. Used for reference
+ // counting and conversation resetting on destruction.
+ existingInstanceWrapper.addCallbackConversation(contextId);
+
+ // add the reference to the collection
+ this.instanceLifecycleCollection.put(contextId, existingInstanceWrapper);
+ }
+ }
+
+ @Override
+ public void registerWrapper(InstanceWrapper wrapper, Object contextId) throws TargetResolutionException {
+ // if a wrapper for a different instance is already registered for this contextId, remove it
+ InstanceLifeCycleWrapper anInstanceWrapper = this.instanceLifecycleCollection.get(contextId);
+ if (anInstanceWrapper != null) {
+ if (anInstanceWrapper.getInstanceWrapper(contextId).getInstance() != wrapper.getInstance()) {
+ remove(contextId);
+ } else {
+ return;
+ }
+ }
+
+ anInstanceWrapper = new InstanceLifeCycleWrapper(wrapper, contextId);
+ this.instanceLifecycleCollection.put(contextId, anInstanceWrapper);
+ }
+
+ // The remove is invoked when a conversation is explicitly ended. This can occur by using the @EndsConversation or API.
+ // In this case the instance is immediately removed. A new conversation will be started on the next operation
+ // associated with this conversationId's service reference.
+ //
+ @Override
+ public void remove(Object contextId) throws TargetDestructionException {
+ if (contextId != null) {
+ if (this.instanceLifecycleCollection.containsKey(contextId)) {
+ InstanceLifeCycleWrapper anInstanceLifeCycleWrapper = this.instanceLifecycleCollection.get(contextId);
+ this.instanceLifecycleCollection.remove(contextId);
+ anInstanceLifeCycleWrapper.removeInstanceWrapper(contextId);
+ }
+ }
+ }
+
+ /*
+ * This is an inner class that keeps track of the lifecycle of a conversation scoped
+ * implementation instance.
+ *
+ */
+
+ private class InstanceLifeCycleWrapper {
+ private Object clientConversationId;
+ private List<Object> callbackConversations = new ArrayList<Object>();
+
+ private InstanceLifeCycleWrapper(Object contextId) throws TargetResolutionException {
+ this.clientConversationId = contextId;
+ this.createInstance(contextId);
+ }
+
+ private InstanceLifeCycleWrapper(InstanceWrapper wrapper, Object contextId) throws TargetResolutionException {
+ this.clientConversationId = contextId;
+ wrappers.put(contextId, wrapper);
+ }
+
+
+ // Associates a callback conversation with this instance. Each time the scope container
+ // is asked to remove an object given a ontextId an associated conversation object will
+ // have its conversationId reset to null. When the list of ids is empty the component instance
+ // will be removed from the scope container
+ private void addCallbackConversation(Object conversationID) {
+ InstanceWrapper ctx = getInstanceWrapper(clientConversationId);
+ callbackConversations.add(conversationID);
+ wrappers.put(conversationID, ctx);
+ }
+
+ //
+ // Return the backing implementation instance
+ //
+ private InstanceWrapper getInstanceWrapper(Object contextId) {
+ InstanceWrapper ctx = wrappers.get(contextId);
+ return ctx;
+ }
+
+ private void removeInstanceWrapper(Object contextId) throws TargetDestructionException {
+ InstanceWrapper ctx = getInstanceWrapper(contextId);
+ wrappers.remove(contextId);
+
+ // find out if we are dealing with the original client conversation id
+ // and reset accordingly
+ if ( ( clientConversationId != null ) && ( clientConversationId.equals(contextId)) ) {
+ clientConversationId = null;
+ } else {
+ // reset the conversationId in the conversation object if present
+ // so that and ending callback causes the conversation in the originating
+ // service reference in the client to be reset
+ callbackConversations.remove(contextId);
+ }
+
+ // stop the component if this removes the last reference
+ if (clientConversationId == null && callbackConversations.isEmpty()) {
+ ctx.stop();
+ }
+ }
+
+ private void createInstance(Object contextId) throws TargetResolutionException {
+ InstanceWrapper instanceWrapper = createInstanceWrapper();
+ instanceWrapper.start();
+ wrappers.put(contextId, instanceWrapper);
+ }
+
+ }
+
+ /**
+ * @see org.apache.tuscany.sca.core.conversation.ConversationListener#conversationEnded(org.apache.tuscany.sca.core.conversation.ExtendedConversation)
+ */
+ public void conversationEnded(ExtendedConversation conversation) {
+ try {
+ remove(conversation.getConversationID());
+ } catch (Exception ex) {
+
+ }
+ }
+
+ /**
+ * @see org.apache.tuscany.sca.core.conversation.ConversationListener#conversationExpired(org.apache.tuscany.sca.core.conversation.ExtendedConversation)
+ */
+ public void conversationExpired(ExtendedConversation conversation) {
+
+ Object conversationId = conversation.getConversationID();
+ InstanceLifeCycleWrapper ilcw = instanceLifecycleCollection.get(conversationId);
+ if (ilcw != null) {
+ // cycle through all the references to this instance and
+ // remove them from the underlying wrappers collection and
+ // from the lifecycle wrappers collection
+
+ for (Object conversationID : ilcw.callbackConversations) {
+ try{
+ ilcw.removeInstanceWrapper(conversationID);
+ remove(conversationID);
+ } catch(TargetDestructionException tde) {
+ System.out.println("Could not remove conversation id " + conversationID);
+ }
+ }
+
+
+ if (ilcw.clientConversationId != null) {
+ try{
+ ilcw.removeInstanceWrapper(ilcw.clientConversationId);
+ remove(ilcw.clientConversationId);
+ } catch(TargetDestructionException tde) {
+ System.out.println("Could not remove conversation id " + ilcw.clientConversationId);
+ }
+ }
+
+ }
+
+ }
+
+ /**
+ * @see org.apache.tuscany.sca.core.conversation.ConversationListener#conversationStarted(org.apache.tuscany.sca.core.conversation.ExtendedConversation)
+ */
+ public void conversationStarted(ExtendedConversation conversation) {
+ startContext(conversation.getConversationID());
+ }
+
+ /**
+ * @return the conversationManager
+ */
+ public ConversationManager getConversationManager() {
+ return conversationManager;
+ }
+
+ /**
+ * @param conversationManager the conversationManager to set
+ */
+ public void setConversationManager(ConversationManager conversationManager) {
+ this.conversationManager = conversationManager;
+ }
+
+}
diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/ConversationalScopeContainerFactory.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/ConversationalScopeContainerFactory.java new file mode 100644 index 0000000000..a6663aba09 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/ConversationalScopeContainerFactory.java @@ -0,0 +1,44 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core.scope; + +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.store.Store; + +/** + * @version $Rev$ $Date$ + */ +public class ConversationalScopeContainerFactory implements ScopeContainerFactory { + private Store store; + + public ConversationalScopeContainerFactory(Store store) { + super(); + this.store = store; + } + + public ScopeContainer createScopeContainer(RuntimeComponent component) { + return new ConversationalScopeContainer(store, component); + } + + public Scope getScope() { + return Scope.CONVERSATION; + } + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/HttpSessionScopeContainer.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/HttpSessionScopeContainer.java new file mode 100644 index 0000000000..5ae8b94647 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/HttpSessionScopeContainer.java @@ -0,0 +1,83 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.scope; + +import org.apache.tuscany.sca.core.context.InstanceWrapper; +import org.apache.tuscany.sca.core.event.HttpSessionEnd; +import org.apache.tuscany.sca.event.Event; +import org.apache.tuscany.sca.runtime.RuntimeComponent; + +/** + * A scope context which manages atomic component instances keyed on HTTP + * session + * + * @version $Rev$ $Date$ + */ +public class HttpSessionScopeContainer extends AbstractScopeContainer<Object> { + + public HttpSessionScopeContainer(RuntimeComponent component) { + super(Scope.SESSION, component); + } + + @Override + public void onEvent(Event event) { + checkInit(); + if (event instanceof HttpSessionEnd) { + //FIXME key is not used + //Object key = ((HttpSessionEnd)event).getSessionID(); + // FIXME: Remove the session id + } + } + + @Override + public synchronized void start() { + if (lifecycleState != UNINITIALIZED && lifecycleState != STOPPED) { + throw new IllegalStateException("Scope must be in UNINITIALIZED or STOPPED state [" + lifecycleState + "]"); + } + lifecycleState = RUNNING; + } + + @Override + public synchronized void stop() { + lifecycleState = STOPPED; + } + + protected InstanceWrapper getInstanceWrapper(boolean create) throws TargetResolutionException { +// Object key = workContext.getIdentifier(Scope.SESSION); + // FIXME: Need to fix this + Object key ="http-session-id"; + assert key != null : "HTTP session key not bound in work context"; + InstanceWrapper ctx = wrappers.get(key); + if (ctx == null && !create) { + return null; + } + if (ctx == null) { + ctx = super.createInstanceWrapper(); + ctx.start(); + wrappers.put(key, ctx); + } + return ctx; + } + + @Override + public InstanceWrapper getWrapper(Object contextId) throws TargetResolutionException { + return getInstanceWrapper(true); + } + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/HttpSessionScopeContainerFactory.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/HttpSessionScopeContainerFactory.java new file mode 100644 index 0000000000..49f89661b1 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/HttpSessionScopeContainerFactory.java @@ -0,0 +1,41 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core.scope; + +import org.apache.tuscany.sca.runtime.RuntimeComponent; + +/** + * @version $Rev$ $Date$ + */ +public class HttpSessionScopeContainerFactory implements ScopeContainerFactory { + + public HttpSessionScopeContainerFactory() { + super(); + } + + public ScopeContainer createScopeContainer(RuntimeComponent component) { + return new HttpSessionScopeContainer(component); + } + + public Scope getScope() { + return Scope.SESSION; + } + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/RequestScopeContainer.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/RequestScopeContainer.java new file mode 100644 index 0000000000..8fdfcc63c9 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/RequestScopeContainer.java @@ -0,0 +1,106 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.scope; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.apache.tuscany.sca.core.context.InstanceWrapper; +import org.apache.tuscany.sca.core.event.RequestEnd; +import org.apache.tuscany.sca.event.Event; +import org.apache.tuscany.sca.runtime.RuntimeComponent; + +/** + * A scope context which manages atomic component instances keyed on the current + * request context + * + * @version $Rev$ $Date$ + */ +public class RequestScopeContainer extends AbstractScopeContainer<Thread> { + private final Map<Thread, InstanceWrapper> contexts; + + public RequestScopeContainer(RuntimeComponent component) { + super(Scope.REQUEST, component); + contexts = new ConcurrentHashMap<Thread, InstanceWrapper>(); + } + + @Override + public void onEvent(Event event) { + checkInit(); + if (event instanceof RequestEnd) { + // shutdownInstances(Thread.currentThread()); + } + } + + @Override + public synchronized void start() { + if (lifecycleState != UNINITIALIZED && lifecycleState != STOPPED) { + throw new IllegalStateException("Scope must be in UNINITIALIZED or STOPPED state [" + lifecycleState + "]"); + } + lifecycleState = RUNNING; + } + + @Override + public synchronized void stop() { + contexts.clear(); + // synchronized (destroyQueues) { + // destroyQueues.clear(); + // } + for (InstanceWrapper ctx : wrappers.values()) { + try { + ctx.stop(); + } catch (ThreadDeath td) { + throw td; + } catch (Throwable e2) { + } + } + lifecycleState = STOPPED; + } + + protected InstanceWrapper getInstanceWrapper(boolean create) throws TargetResolutionException { + InstanceWrapper ctx = wrappers.get(Thread.currentThread()); + if (ctx == null && !create) { + return null; + } + if (ctx == null) { + ctx = super.createInstanceWrapper(); + try { + ctx.start(); + wrappers.put(Thread.currentThread(), ctx); + } catch (ThreadDeath td) { + throw td; + } catch (Throwable e) { + try { + ctx.stop(); + } catch (ThreadDeath td) { + throw td; + } catch (Throwable e2) { + } + throw new TargetInitializationException(e); + } + } + return ctx; + } + + @Override + public InstanceWrapper getWrapper(Thread contextId) throws TargetResolutionException { + return getInstanceWrapper(true); + } + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/RequestScopeContainerFactory.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/RequestScopeContainerFactory.java new file mode 100644 index 0000000000..1cfb6b06a4 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/RequestScopeContainerFactory.java @@ -0,0 +1,37 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core.scope; + +import org.apache.tuscany.sca.runtime.RuntimeComponent; + +/** + * @version $Rev$ $Date$ + */ +public class RequestScopeContainerFactory implements ScopeContainerFactory { + + public ScopeContainer createScopeContainer(RuntimeComponent component) { + return new RequestScopeContainer(component); + } + + public Scope getScope() { + return Scope.REQUEST; + } + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/Scope.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/Scope.java new file mode 100644 index 0000000000..0a20d793f7 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/Scope.java @@ -0,0 +1,66 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.scope; + +/** + * The default implementation scopes supported by assemblies. + * + * @version $Rev$ $Date$ + */ +public class Scope { + public static final Scope STATELESS = new Scope("STATELESS"); + public static final Scope REQUEST = new Scope("REQUEST"); + public static final Scope SESSION = new Scope("SESSION"); + public static final Scope CONVERSATION = new Scope("CONVERSATION"); + public static final Scope COMPOSITE = new Scope("COMPOSITE"); + public static final Scope SYSTEM = new Scope("SYSTEM"); + public static final Scope UNDEFINED = new Scope("UNDEFINED"); + + private String scope; + + public Scope(String scope) { + this.scope = scope.toUpperCase().intern(); + } + + public String getScope() { + return scope; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + final Scope scope1 = (Scope) o; + return !(scope != null ? scope != scope1.scope.intern() : scope1.scope != null); + } + + @Override + public int hashCode() { + return scope != null ? scope.hashCode() : 0; + } + + @Override + public String toString() { + return scope; + } +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/ScopeContainer.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/ScopeContainer.java new file mode 100644 index 0000000000..6b2980b989 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/ScopeContainer.java @@ -0,0 +1,159 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.scope; + +import org.apache.tuscany.sca.core.context.InstanceWrapper; +import org.apache.tuscany.sca.event.RuntimeEventListener; +import org.apache.tuscany.sca.runtime.RuntimeComponent; + + +/** + * Manages the lifecycle and visibility of instances associated with a an {@link RuntimeComponent}. + * + * @version $Rev$ $Date$ + * @param <KEY> the type of IDs that this container uses to identify its contexts. + * For example, for COMPOSITE scope this could be the URI of the composite component, + * or for HTTP Session scope it might be the HTTP session ID. + */ +public interface ScopeContainer<KEY> extends RuntimeEventListener { + + /** + * Returns the Scope that this container supports. + * + * @return the Scope that this container supports + */ + Scope getScope(); + + /** + * Start a new context with the supplied ID. + * + * @param contextId an ID that uniquely identifies the context. + */ + void startContext(KEY contextId); + + /** + * Stop the context with the supplied ID. + * + * @param contextId an ID that uniquely identifies the context. + */ + void stopContext(KEY contextId); + + /** + * Returns an instance wrapper associated with the current scope context, creating one if necessary + * @param contextId the id for the scope context + * + * @return the wrapper for the target instance + * @throws TargetResolutionException if there was a problem instantiating the target instance + */ + InstanceWrapper getWrapper(KEY contextId) throws TargetResolutionException; + + /** + * Allows a component to be registered against more than one context id. This is required in the + * case of stateful callbacks where we want to identify the originating client component instance + * as the callback target but we don't want to reuse the clients original conversation id + * + * @param existingContextId an id that identifies an existing component instance + * @param newContextId a new id against which this component will also be registered + * @throws TargetResolutionException + */ + void addWrapperReference(KEY existingContextId, KEY newContextId) + throws TargetResolutionException; + + /** + * Register an existing instance against a context id. This is needed + * for a stateful callback where the service reference for the forward call + * contains a callback object that is not a service reference. + * + * @param wrapper the instance wrapper for the instance to be registered + * @param contextId the id for the scope context + * @throws TargetResolutionException + */ + void registerWrapper(InstanceWrapper wrapper, KEY contextId) + throws TargetResolutionException; + + /** + * Returns an implementation instance associated with the current scope context. + * If no instance is found, a {@link TargetNotFoundException} is thrown. + * @param contextId the id for the scope context + * + * @return the wrapper for the target instance + * @throws TargetResolutionException if there was a problem instantiating the target instance + */ + InstanceWrapper getAssociatedWrapper(KEY contextId) + throws TargetResolutionException; + + /** + * Return a wrapper after use (for example, after invoking the instance). + * @param wrapper the wrapper for the target instance being returned + * @param contextId the id for the scope context + * + * @throws TargetDestructionException if there was a problem returning the target instance + */ + void returnWrapper(InstanceWrapper wrapper, KEY contextId) + throws TargetDestructionException; + + /** + * Removes an identified component implementation instance associated with the current + * context from persistent storage + * + * @param contextId the identifier of the context to remove. + */ + void remove(KEY contextId) + throws TargetDestructionException; + + /* A configuration error state */ + int CONFIG_ERROR = -1; + /* Has not been initialized */ + int UNINITIALIZED = 0; + /* In the process of being configured and initialized */ + int INITIALIZING = 1; + /* Instantiated and configured */ + int INITIALIZED = 2; + /* Configured and initialized */ + int RUNNING = 4; + /* In the process of being shutdown */ + int STOPPING = 5; + /* Has been shutdown and removed from the composite */ + int STOPPED = 6; + /* In an error state */ + int ERROR = 7; + + /** + * Returns the lifecycle state + * + * @see #UNINITIALIZED + * @see #INITIALIZING + * @see #INITIALIZED + * @see #RUNNING + * @see #STOPPING + * @see #STOPPED + */ + int getLifecycleState(); + + /** + * Starts the Lifecycle. + */ + void start(); + + /** + * Stops the Lifecycle. + */ + void stop(); + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/ScopeContainerFactory.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/ScopeContainerFactory.java new file mode 100644 index 0000000000..b19c14b3e0 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/ScopeContainerFactory.java @@ -0,0 +1,32 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core.scope; + +import org.apache.tuscany.sca.runtime.RuntimeComponent; + +/** + * Factory to create ScopeContainer for components + * + * @version $Rev$ $Date$ + */ +public interface ScopeContainerFactory { + ScopeContainer createScopeContainer(RuntimeComponent component); + Scope getScope(); +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/ScopeRegistry.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/ScopeRegistry.java new file mode 100644 index 0000000000..842ed4c547 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/ScopeRegistry.java @@ -0,0 +1,43 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.scope; + +import org.apache.tuscany.sca.runtime.RuntimeComponent; + + +/** + * Manages {@link ScopeContainer}s in the runtime + * + * @version $Rev$ $Date$ + */ +public interface ScopeRegistry { + + /** + * Returns the scope container for the given scope or null if one not found + * + * @param scope the scope + * @return the scope container for the given scope or null if one not found + */ + ScopeContainer getScopeContainer(RuntimeComponent component); + + /** + * @param factory + */ + void register(ScopeContainerFactory factory); +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/ScopeRegistryImpl.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/ScopeRegistryImpl.java new file mode 100644 index 0000000000..75261e11a8 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/ScopeRegistryImpl.java @@ -0,0 +1,62 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.scope; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.apache.tuscany.sca.provider.ImplementationProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponent; + +/** + * The default implementation of a scope registry + * + * @version $Rev$ $Date$ + */ +public class ScopeRegistryImpl implements ScopeRegistry { + private final Map<Scope, ScopeContainerFactory> scopeCache = new ConcurrentHashMap<Scope, ScopeContainerFactory>(); + + public void register(ScopeContainerFactory factory) { + scopeCache.put(factory.getScope(), factory); + } + + public ScopeContainer getScopeContainer(RuntimeComponent runtimeComponent) { + if (!(runtimeComponent instanceof ScopedRuntimeComponent)) { + return null; + } + ScopedRuntimeComponent component = (ScopedRuntimeComponent)runtimeComponent; + if (component.getScopeContainer() != null) { + return component.getScopeContainer(); + } + ImplementationProvider implementationProvider = component.getImplementationProvider(); + if (implementationProvider instanceof ScopedImplementationProvider) { + ScopedImplementationProvider provider = (ScopedImplementationProvider)implementationProvider; + Scope scope = provider.getScope(); + if (scope == null) { + scope = Scope.STATELESS; + } + ScopeContainerFactory factory = scopeCache.get(scope); + ScopeContainer container = factory.createScopeContainer(component); + component.setScopeContainer(container); + return container; + } + return null; + } + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/ScopedImplementationProvider.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/ScopedImplementationProvider.java new file mode 100644 index 0000000000..85a6626cdd --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/ScopedImplementationProvider.java @@ -0,0 +1,65 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core.scope; + +import org.apache.tuscany.sca.core.context.InstanceWrapper; +import org.apache.tuscany.sca.provider.ImplementationProvider; + +/** + * A component implementation can implement this interface to provide scope + * management for the components + * + * @version $Rev$ $Date$ + */ +public interface ScopedImplementationProvider extends ImplementationProvider { + /** + * Get the scope for the component implementation + * + * @return The scope for the component implementation, if null is returned, + * STATELESS will be used + */ + Scope getScope(); + + /** + * Indicate if the component needs to be eagerly initialized + * + * @return true if the component is marked to be eagerly initialized, false + * otherwise + */ + boolean isEagerInit(); + + /** + * @return the maxAge + */ + long getMaxAge(); + + /** + * @return the maxIdleTime + */ + long getMaxIdleTime(); + + /** + * Create a wrapper for the component instance for the scope management + * + * @return A wrapper for the component instance + */ + InstanceWrapper createInstanceWrapper(); + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/ScopedRuntimeComponent.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/ScopedRuntimeComponent.java new file mode 100644 index 0000000000..c27b112f8a --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/ScopedRuntimeComponent.java @@ -0,0 +1,40 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core.scope; + +import org.apache.tuscany.sca.runtime.RuntimeComponent; + +/** + * Scoped runtime component + * + * @version $Rev$ $Date$ + */ +public interface ScopedRuntimeComponent extends RuntimeComponent { + /** + * Set the associated scope container + * @param scopeContainer + */ + void setScopeContainer(ScopeContainer scopeContainer); + /** + * Get the assoicated scope container + * @return + */ + ScopeContainer getScopeContainer(); +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/StatelessScopeContainer.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/StatelessScopeContainer.java new file mode 100644 index 0000000000..24125b154c --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/StatelessScopeContainer.java @@ -0,0 +1,67 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.scope; + +import org.apache.tuscany.sca.core.context.InstanceWrapper; +import org.apache.tuscany.sca.runtime.RuntimeComponent; + +/** + * A scope context which manages stateless atomic component instances in a non-pooled fashion. + * + * @version $Rev$ $Date$ + */ +public class StatelessScopeContainer<KEY> extends AbstractScopeContainer<KEY> { + + public StatelessScopeContainer(RuntimeComponent component) { + super(Scope.STATELESS, component); + } + + @Override + public InstanceWrapper getWrapper(KEY contextId) + throws TargetResolutionException { + InstanceWrapper ctx = createInstanceWrapper(); + try { + ctx.start(); + } catch (ThreadDeath td) { + throw td; + } catch (Throwable e) { + try { + ctx.stop(); + } catch (ThreadDeath td) { + throw td; + } catch (Throwable e2) { + } + throw new TargetInitializationException(e); + } + return ctx; + } + + @Override + public InstanceWrapper getAssociatedWrapper(KEY contextId) + throws TargetResolutionException { + return getWrapper(contextId); + } + + @Override + public void returnWrapper(InstanceWrapper wrapper, KEY contextId) + throws TargetDestructionException { + wrapper.stop(); + } + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/StatelessScopeContainerFactory.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/StatelessScopeContainerFactory.java new file mode 100644 index 0000000000..0471b2c52e --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/StatelessScopeContainerFactory.java @@ -0,0 +1,37 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core.scope; + +import org.apache.tuscany.sca.runtime.RuntimeComponent; + +/** + * @version $Rev$ $Date$ + */ +public class StatelessScopeContainerFactory implements ScopeContainerFactory { + + public ScopeContainer createScopeContainer(RuntimeComponent component) { + return new StatelessScopeContainer(component); + } + + public Scope getScope() { + return Scope.STATELESS; + } + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/TargetDestructionException.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/TargetDestructionException.java new file mode 100644 index 0000000000..0f83dad97d --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/TargetDestructionException.java @@ -0,0 +1,44 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.scope; + +/** + * Denotes an error destroying a target + * + * @version $Rev$ $Date$ + */ +public class TargetDestructionException extends TargetResolutionException { + private static final long serialVersionUID = -6126684147851674709L; + + public TargetDestructionException() { + super(); + } + + public TargetDestructionException(String message, Throwable cause) { + super(message, cause); + } + + public TargetDestructionException(String message) { + super(message); + } + + public TargetDestructionException(Throwable cause) { + super(cause); + } +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/TargetInitializationException.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/TargetInitializationException.java new file mode 100644 index 0000000000..15959c0608 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/TargetInitializationException.java @@ -0,0 +1,44 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.scope; + +/** + * Denotes an error initializing a target + * + * @version $Rev$ $Date$ + */ +public class TargetInitializationException extends TargetResolutionException { + private static final long serialVersionUID = -6228778208649752698L; + + public TargetInitializationException() { + super(); + } + + public TargetInitializationException(String message, Throwable cause) { + super(message, cause); + } + + public TargetInitializationException(String message) { + super(message); + } + + public TargetInitializationException(Throwable cause) { + super(cause); + } +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/TargetNotFoundException.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/TargetNotFoundException.java new file mode 100644 index 0000000000..bb46a2499b --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/TargetNotFoundException.java @@ -0,0 +1,44 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.scope; + +/** + * Thrown when a target of an operation cannot be found + * + * @version $Rev$ $Date$ + */ +public class TargetNotFoundException extends TargetResolutionException { + private static final long serialVersionUID = 5541830480658471186L; + + public TargetNotFoundException() { + super(); + } + + public TargetNotFoundException(String message, Throwable cause) { + super(message, cause); + } + + public TargetNotFoundException(String message) { + super(message); + } + + public TargetNotFoundException(Throwable cause) { + super(cause); + } +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/TargetResolutionException.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/TargetResolutionException.java new file mode 100644 index 0000000000..ea8d0e876c --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/scope/TargetResolutionException.java @@ -0,0 +1,44 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.scope; + +/** + * Denotes an error retrieving a target instance + * + * @version $Rev$ $Date$ + */ +public class TargetResolutionException extends Exception { + private static final long serialVersionUID = 2912513650522019405L; + + public TargetResolutionException() { + super(); + } + + public TargetResolutionException(String message, Throwable cause) { + super(message, cause); + } + + public TargetResolutionException(String message) { + super(message); + } + + public TargetResolutionException(Throwable cause) { + super(cause); + } +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/store/MemoryStore.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/store/MemoryStore.java new file mode 100644 index 0000000000..5b838116c5 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/store/MemoryStore.java @@ -0,0 +1,195 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.store; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +import org.apache.tuscany.sca.core.event.BaseEventPublisher; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.store.DuplicateRecordException; +import org.apache.tuscany.sca.store.RecoveryListener; +import org.apache.tuscany.sca.store.Store; +import org.apache.tuscany.sca.store.StoreExpirationEvent; +import org.apache.tuscany.sca.store.StoreMonitor; +import org.apache.tuscany.sca.store.StoreWriteException; +import org.osoa.sca.annotations.Destroy; +import org.osoa.sca.annotations.EagerInit; +import org.osoa.sca.annotations.Init; +import org.osoa.sca.annotations.Property; +import org.osoa.sca.annotations.Service; + +/** + * Implements a non-durable, non-transactional store using a simple in-memory map + * + * @version $Rev$ $Date$ + */ +@Service(Store.class) +@EagerInit +public class MemoryStore extends BaseEventPublisher implements Store { + private Map<RuntimeComponent, Map<String, Record>> store; + // TODO integrate with a core threading scheme + private ScheduledExecutorService scheduler; + private long reaperInterval = 300000; + private StoreMonitor monitor; + private long defaultExpirationOffset = 600000; // 10 minutes + + public MemoryStore(StoreMonitor monitor) { + this.monitor = monitor; + this.store = new ConcurrentHashMap<RuntimeComponent, Map<String, Record>>(); + this.scheduler = Executors.newSingleThreadScheduledExecutor(); + } + + /** + * Returns the maximum default expiration offset for records in the store + * + * @return the maximum default expiration offset for records in the store + */ + public long getDefaultExpirationOffset() { + return defaultExpirationOffset; + } + + /** + * Sets the maximum default expiration offset for records in the store + */ + @Property + public void setDefaultExpirationOffset(long defaultExpirationOffset) { + this.defaultExpirationOffset = defaultExpirationOffset; + } + + /** + * Sets the interval for expired entry scanning to be performed + */ + @Property + public void setReaperInterval(long reaperInterval) { + this.reaperInterval = reaperInterval; + } + + public long getReaperInterval() { + return reaperInterval; + } + + @Init + public void init() { + scheduler.scheduleWithFixedDelay(new Reaper(), reaperInterval, reaperInterval, TimeUnit.MILLISECONDS); + monitor.start("In-memory store started"); + } + + @Destroy + public void destroy() { + scheduler.shutdown(); + monitor.stop("In-memory store stopped"); + } + + public void insertRecord(RuntimeComponent owner, String id, Object object, long expiration) throws StoreWriteException { + Map<String, Record> map = store.get(owner); + if (map == null) { + map = new ConcurrentHashMap<String, Record>(); + store.put(owner, map); + } + if (map.containsKey(id)) { + throw new DuplicateRecordException("Duplicate record: " + owner.getURI() +" : " + id); + } + map.put(id, new Record(object, expiration)); + } + + public void updateRecord(RuntimeComponent owner, String id, Object object, long expiration) throws StoreWriteException { + Map<String, Record> map = store.get(owner); + if (map == null) { + throw new StoreWriteException("Record not found: " + owner.getURI() +" : " + id); + } + Record record = map.get(id); + if (record == null) { + throw new StoreWriteException("Record not found: " + owner.getURI() +" : " + id); + } + record.data = object; + } + + public Object readRecord(RuntimeComponent owner, String id) { + Map<String, Record> map = store.get(owner); + if (map == null) { + return null; + } + Record record = map.get(id); + if (record != null) { + return record.data; + } + return null; + } + + public void removeRecords() { + store.clear(); + } + + public void removeRecord(RuntimeComponent owner, String id) throws StoreWriteException { + Map<String, Record> map = store.get(owner); + if (map == null) { + throw new StoreWriteException("Owner not found: " + owner.getURI() +" : " + id); + } + if (map.remove(id) == null) { + throw new StoreWriteException("Owner not found: " + owner.getURI() +" : " + id); + } + } + + public void recover(RecoveryListener listener) { + throw new UnsupportedOperationException(); + } + + private class Record { + private Object data; + private long expiration = NEVER; + + public Record(Object data, long expiration) { + this.data = data; + this.expiration = expiration; + } + + public Object getData() { + return data; + } + + public long getExpiration() { + return expiration; + } + } + + private class Reaper implements Runnable { + + public void run() { + long now = System.currentTimeMillis(); + for (Map.Entry<RuntimeComponent, Map<String, Record>> entries : store.entrySet()) { + for (Map.Entry<String, Record> entry : entries.getValue().entrySet()) { + final long expiration = entry.getValue().expiration; + if (expiration != NEVER && now >= expiration) { + RuntimeComponent owner = entries.getKey(); + Object instance = entry.getValue().getData(); + // notify listeners of the expiration + StoreExpirationEvent event = new StoreExpirationEvent(this, owner, instance); + publish(event); + entries.getValue().remove(entry.getKey()); + } + } + } + } + } + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/work/DefaultWorkScheduler.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/work/DefaultWorkScheduler.java new file mode 100644 index 0000000000..55b0acded9 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/work/DefaultWorkScheduler.java @@ -0,0 +1,191 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.work; + +import java.security.AccessController; +import java.security.PrivilegedAction; + +import org.apache.tuscany.sca.work.NotificationListener; +import org.apache.tuscany.sca.work.WorkScheduler; +import org.apache.tuscany.sca.work.WorkSchedulerException; + +/** + * A work scheduler implementation based on a JSR 237 work manager. + * <p/> + * <p/> + * This needs a JSR 237 work manager implementation available for scheduling work. Instances can be configured with a + * work manager implementation that is injected in. It is the responsibility of the runtime environment to make a work + * manager implementation available. For example, if the managed environment supports work manager the runtime can use + * the appropriate lookup mechanism to inject the work manager implementation. </p> + * + * @version $Rev$ $Date$ + */ +public class DefaultWorkScheduler implements WorkScheduler { + + /** + * Underlying JSR-237 work manager + */ + private ThreadPoolWorkManager jsr237WorkManager; + + /** + * Initializes the JSR 237 work manager. + * + * @param jsr237WorkManager JSR 237 work manager. + */ + public DefaultWorkScheduler() { + } + + private synchronized ThreadPoolWorkManager getWorkManager() { + if (jsr237WorkManager != null) { + return jsr237WorkManager; + } +// try { +// InitialContext ctx = new InitialContext(); +// jsr237WorkManager = (ThreadPoolWorkManager)ctx.lookup("java:comp/env/wm/TuscanyWorkManager"); +// } catch (Throwable e) { +// // ignore +// } + if (jsr237WorkManager == null) { + jsr237WorkManager = new ThreadPoolWorkManager(0); + } + return jsr237WorkManager; + } + + /** + * Schedules a unit of work for future execution. The notification listener is used to register interest in + * callbacks regarding the status of the work. + * + * @param work The unit of work that needs to be asynchronously executed. + */ + public <T extends Runnable> void scheduleWork(T work) { + scheduleWork(work, null); + } + + /** + * Schedules a unit of work for future execution. The notification listener is used to register interest in + * callbacks regarding the status of the work. + * + * @param work The unit of work that needs to be asynchronously executed. + * @param listener Notification listener for callbacks. + */ + public <T extends Runnable> void scheduleWork(T work, NotificationListener<T> listener) { + + if (work == null) { + throw new IllegalArgumentException("Work cannot be null"); + } + + Work<T> jsr237Work = new Work<T>(work); + try { + if (listener == null) { + getWorkManager().schedule(jsr237Work); + } else { + Jsr237WorkListener<T> jsr237WorkListener = new Jsr237WorkListener<T>(listener, work); + getWorkManager().schedule(jsr237Work, jsr237WorkListener); + } + } catch (IllegalArgumentException ex) { + if (listener != null) { + listener.workRejected(work); + } else { + throw new WorkSchedulerException(ex); + } + } catch (Exception ex) { + throw new WorkSchedulerException(ex); + } + + } + + public void destroy() { + if (jsr237WorkManager instanceof ThreadPoolWorkManager) { + // Allow privileged access to modify threads. Requires RuntimePermission in security + // policy. + AccessController.doPrivileged(new PrivilegedAction<Object>() { + public Object run() { + ((ThreadPoolWorkManager)jsr237WorkManager).destroy(); + return null; + } + }); + } + } + + /* + * WorkListener for keeping track of work status callbacks. + * + */ + private class Jsr237WorkListener<T extends Runnable> implements WorkListener { + + // Notification listener + private NotificationListener<T> listener; + + // Work + private T work; + + /* + * Initializes the notification listener. + */ + public Jsr237WorkListener(NotificationListener<T> listener, T work) { + this.listener = listener; + this.work = work; + } + + /* + * Callback when the work is accepted. + */ + public void workAccepted(WorkEvent workEvent) { + T work = getWork(); + listener.workAccepted(work); + } + + /* + * Callback when the work is rejected. + */ + public void workRejected(WorkEvent workEvent) { + T work = getWork(); + listener.workRejected(work); + } + + /* + * Callback when the work is started. + */ + public void workStarted(WorkEvent workEvent) { + T work = getWork(); + listener.workStarted(work); + } + + /* + * Callback when the work is completed. + */ + public void workCompleted(WorkEvent workEvent) { + T work = getWork(); + Exception exception = workEvent.getException(); + if (exception != null) { + listener.workFailed(work, exception); + } else { + listener.workCompleted(work); + } + } + + /* + * Gets the underlying work from the work event. + */ + private T getWork() { + return work; + } + + } +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/work/ThreadPoolWorkManager.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/work/ThreadPoolWorkManager.java new file mode 100644 index 0000000000..91d00a58d9 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/work/ThreadPoolWorkManager.java @@ -0,0 +1,229 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.work; + +import java.rmi.server.UID; +import java.util.Collection; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.ThreadFactory; + +import org.apache.tuscany.sca.work.WorkSchedulerException; +import org.osoa.sca.annotations.Destroy; + +/** + * A thread-pool based implementation for the JSR-237 work manager. + * <p/> + * <p/> + * This implementation supports only local work. + * <p/> + * TODO Elaborate the implementation. </p> + * + * @version $Rev$ $Date$ + */ +public class ThreadPoolWorkManager { + + // Map of work items currently handled by the work manager + private Map<WorkItem, WorkListener> workItems = new ConcurrentHashMap<WorkItem, WorkListener>(); + + // Thread-pool + private ExecutorService executor; + + /** + * Initializes the thread-pool. + * + * @param threadPoolSize Thread-pool size. If the size <1, then a cached pool is created + */ + public ThreadPoolWorkManager(int threadPoolSize) { + ThreadFactory factory = new ThreadFactory() { + public Thread newThread(Runnable r) { + Thread thread = new Thread(r); + thread.setDaemon(true); + return thread; + } + }; + if (threadPoolSize <= 1) { + + // Creates a new Executor, use a custom ThreadFactory that + // creates daemon threads. + executor = Executors.newCachedThreadPool(factory); + } else { + executor = Executors.newFixedThreadPool(threadPoolSize); + } + } + + /** + * Schedules a unit of work asynchronously. + * + * @param work Work that needs to be scheduled. + * @return Work Work item representing the asynchronous work + */ + public WorkItem schedule(Work work) throws IllegalArgumentException { + return schedule(work, null); + } + + /** + * Schedules a unit of work asynchronously. + * + * @param work Work that needs to be scheduled. + * @param workListener Work listener for callbacks. + * @return Work Work item representing the asynchronous work + */ + public WorkItem schedule(Work work, WorkListener workListener) throws IllegalArgumentException { + + WorkItem workItem = new WorkItem(new UID().toString(), work); + if (workListener != null) { + workItems.put(workItem, workListener); + } + workAccepted(workItem, work); + if (scheduleWork(work, workItem)) { + return workItem; + } else { + workItem.setStatus(WorkEvent.WORK_REJECTED); + if (workListener != null) { + workListener.workRejected(new WorkEvent(workItem)); + } + throw new IllegalArgumentException("Unable to schedule work"); + } + } + + /** + * Wait for all the specified units of work to finish. + * + * @param works Units of the work that need to finish. + * @param timeout Timeout for waiting for the units of work to finish. + */ + public boolean waitForAll(Collection works, long timeout) { + throw new UnsupportedOperationException("waitForAll not supported"); + } + + /** + * Wait for any of the specified units of work to finish. + * + * @param works Units of the work that need to finish. + * @param timeout Timeout for waiting for the units of work to finish. + */ + public Collection waitForAny(Collection works, long timeout) { + throw new UnsupportedOperationException("waitForAny not supported"); + } + + /** + * Method provided for subclasses to indicate a work acceptance. + * + * @param workItem Work item representing the work that was accepted. + * @param work Work that was accepted. + */ + private void workAccepted(final WorkItem workItem, final Work work) { + WorkListener listener = workItems.get(workItem); + if (listener != null) { + workItem.setStatus(WorkEvent.WORK_ACCEPTED); + WorkEvent event = new WorkEvent(workItem); + listener.workAccepted(event); + } + } + + /* + * Method to indicate a work start. + */ + private void workStarted(final WorkItem workItem, final Work work) { + WorkListener listener = workItems.get(workItem); + if (listener != null) { + workItem.setStatus(WorkEvent.WORK_STARTED); + WorkEvent event = new WorkEvent(workItem); + listener.workStarted(event); + } + } + + /* + * Method to indicate a work completion. + */ + private void workCompleted(final WorkItem workItem, final Work work) { + workCompleted(workItem, work, null); + } + + /* + * Method to indicate a work completion. + */ + private void workCompleted(final WorkItem workItem, final Work work, final WorkSchedulerException exception) { + WorkListener listener = workItems.get(workItem); + if (listener != null) { + workItem.setStatus(WorkEvent.WORK_COMPLETED); + workItem.setResult(work); + workItem.setException(exception); + WorkEvent event = new WorkEvent(workItem); + listener.workCompleted(event); + workItems.remove(workItem); + } + } + + /* + * Schedules the work using the ThreadPool. + */ + private boolean scheduleWork(final Work work, final WorkItem workItem) { + try { + executor.execute(new DecoratingWork(workItem, work)); + return true; + } catch (RejectedExecutionException ex) { + return false; + } + } + + /* + * Class that decorates the original worker so that it can get callbacks when work is done. + */ + private final class DecoratingWork implements Runnable { + + // Work item for this work. + private WorkItem workItem; + + // The original work. + private Work decoratedWork; + + /* + * Initializes the work item and underlying work. + */ + private DecoratingWork(final WorkItem workItem, final Work decoratedWork) { + this.workItem = workItem; + this.decoratedWork = decoratedWork; + } + + /* + * Overrides the run method. + */ + public void run() { + workStarted(workItem, decoratedWork); + try { + decoratedWork.run(); + workCompleted(workItem, decoratedWork); + } catch (Throwable th) { + workCompleted(workItem, decoratedWork, new WorkSchedulerException(th.getMessage(), th)); + } + } + + } + + @Destroy + public void destroy() { + executor.shutdown(); + } + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/work/Work.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/work/Work.java new file mode 100644 index 0000000000..c521c60f79 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/work/Work.java @@ -0,0 +1,65 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core.work; + +/** + * JCA work wrapper. + * + * @version $Rev$ $Date$ + */ +public class Work<T extends Runnable> { + + // Work that is being executed. + private T work; + + /* + * Initializes the work instance. + */ + public Work(T work) { + this.work = work; + } + + /* + * Returns the completed work. + */ + public T getWork() { + return work; + } + + /* + * Release the work. + */ + public void release() { + } + + /* + * Work attributes are not daemon. + */ + public boolean isDaemon() { + return false; + } + + /* + * Runs the work. + */ + public void run() { + work.run(); + } +}
\ No newline at end of file diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/work/WorkEvent.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/work/WorkEvent.java new file mode 100644 index 0000000000..8e9a3b4c53 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/work/WorkEvent.java @@ -0,0 +1,80 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.work; + +import org.apache.tuscany.sca.work.WorkSchedulerException; + + + +/** + * Default immutable implementation of the <code>WorkEvent</code> class. + * + * @version $Rev$ $Date$ + */ +class WorkEvent { + + public static final int WORK_ACCEPTED = 1; + public static final int WORK_REJECTED = 2; + public static final int WORK_STARTED = 3; + public static final int WORK_COMPLETED = 4; + + // Work item for this event + private WorkItem workItem; + + // Exception if something has gone wrong + private WorkSchedulerException exception; + + /** + * Instantiates the event. + * + * @param workItem Work item for this event. + */ + public WorkEvent(final WorkItem workItem) { + this.workItem = workItem; + this.exception = workItem.getException(); + } + + /** + * Returns the work type based on whether the work was accepted, started, + * rejected or completed. + * + * @return Work type. + */ + public int getType() { + return workItem.getStatus(); + } + + /** + * Returns the work item associated with this work type. + * + * @return Work item. + */ + public WorkItem getWorkItem() { + return workItem; + } + + /** + * Returns the exception if the work completed with an exception. + * + * @return Work exception. + */ + public WorkSchedulerException getException() { + return exception; + } +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/work/WorkItem.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/work/WorkItem.java new file mode 100644 index 0000000000..8320c7364f --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/work/WorkItem.java @@ -0,0 +1,167 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.work; + +import org.apache.tuscany.sca.work.WorkSchedulerException; + +/** + * An identity based immutable implementation of the <code>WorkItem</code> + * interface. + * + * @version $Rev$ $Date$ + */ +class WorkItem { + + // Id scoped for the VM + private String id; + + // Status + private int status = -1; + + // Result + private Work result; + + // Original work + private Work originalWork; + + // Exception + private WorkSchedulerException exception; + + /** + * Instantiates an id for this item. + * + * @param id of this work event. + */ + protected WorkItem(final String id, final Work orginalWork) { + this.id = id; + this.originalWork = orginalWork; + } + + /** + * Returns the id. + * + * @return Id of this item. + */ + public String getId() { + return id; + } + + /** + * Returns the original work. + * + * @return Original work. + */ + public Work getOriginalWork() { + return originalWork; + } + + /** + * Returns the work result if the work completed. + * + * @return Work. + * @throws WorkException If the work completed with an exception. + */ + public Work getResult() { + return result; + } + + /** + * Sets the result. + * + * @param result Result. + */ + protected void setResult(final Work result) { + this.result = result; + } + + /** + * Returns the exception if work completed with an exception. + * + * @return Work exception. + */ + protected WorkSchedulerException getException() { + return exception; + } + + /** + * Sets the exception. + * + * @param exception Exception. + */ + protected void setException(final WorkSchedulerException exception) { + this.exception = exception; + } + + /** + * Returns the work type based on whether the work was accepted, started, + * rejected or completed. + * + * @return Work status. + */ + public int getStatus() { + return status; + } + + /** + * Sets the status. + * + * @param status Status. + */ + protected void setStatus(final int status) { + this.status = status; + } + + /** + * @see Object#hashCode() + */ + @Override + public int hashCode() { + return id.hashCode(); + } + + /** + * Indicates whether some other object is "equal to" this one. + * + * @param obj Object to be compared. + * @return true if this object is the same as the obj argument; false + * otherwise.. + */ + @Override + public boolean equals(final Object obj) { + return (obj != null) && (obj.getClass() == WorkItem.class) && ((WorkItem) obj).id.equals(id); + } + + /** + * Compares this object with the specified object for order. Returns a + * negative integer, zero, or a positive integer as this object is less + * than, equal to, or greater than the specified object. + * + * @param o Object to be compared. + * @return A negative integer, zero, or a positive integer as this object + * is less than, equal to, or greater than the specified object. + * @throws ClassCastException needs better documentation. + */ + public int compareTo(final Object o) { + if (o.getClass() != WorkItem.class) { + throw new ClassCastException(o.getClass().getName()); + } else { + return ((WorkItem) o).getId().compareTo(getId()); + } + } +} diff --git a/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/work/WorkListener.java b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/work/WorkListener.java new file mode 100644 index 0000000000..19bfaaa560 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/java/org/apache/tuscany/sca/core/work/WorkListener.java @@ -0,0 +1,32 @@ +/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.tuscany.sca.core.work;
+
+public interface WorkListener {
+
+ static long IMMEDIATE = 0;
+ static long INDEFINITE = java.lang.Long.MAX_VALUE;
+
+ void workAccepted(WorkEvent event);
+ void workCompleted(WorkEvent event);
+ void workRejected(WorkEvent event);
+ void workStarted(WorkEvent event);
+
+}
diff --git a/branches/sca-java-1.5.1/modules/core/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor b/branches/sca-java-1.5.1/modules/core/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor new file mode 100644 index 0000000000..5f54178483 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor @@ -0,0 +1,19 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +# Implementation class for the artifact processor extension +org.apache.tuscany.sca.core.assembly.ReferenceParameterProcessor;qname=http://tuscany.apache.org/xmlns/sca/1.0#referenceParameters,model=org.apache.tuscany.sca.runtime.ReferenceParameters diff --git a/branches/sca-java-1.5.1/modules/core/src/main/resources/META-INF/services/org.apache.tuscany.sca.core.conversation.ConversationManager b/branches/sca-java-1.5.1/modules/core/src/main/resources/META-INF/services/org.apache.tuscany.sca.core.conversation.ConversationManager new file mode 100644 index 0000000000..898054509b --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/resources/META-INF/services/org.apache.tuscany.sca.core.conversation.ConversationManager @@ -0,0 +1,18 @@ +# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+org.apache.tuscany.sca.core.conversation.ConversationManagerImpl
diff --git a/branches/sca-java-1.5.1/modules/core/src/main/resources/META-INF/services/org.apache.tuscany.sca.core.invocation.ProxyFactoryExtensionPoint b/branches/sca-java-1.5.1/modules/core/src/main/resources/META-INF/services/org.apache.tuscany.sca.core.invocation.ProxyFactoryExtensionPoint new file mode 100644 index 0000000000..af281d8f4d --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/resources/META-INF/services/org.apache.tuscany.sca.core.invocation.ProxyFactoryExtensionPoint @@ -0,0 +1,18 @@ +# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+org.apache.tuscany.sca.core.invocation.DefaultProxyFactoryExtensionPoint
diff --git a/branches/sca-java-1.5.1/modules/core/src/main/resources/META-INF/services/org.apache.tuscany.sca.invocation.MessageFactory b/branches/sca-java-1.5.1/modules/core/src/main/resources/META-INF/services/org.apache.tuscany.sca.invocation.MessageFactory new file mode 100644 index 0000000000..bcbd5b0abf --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/resources/META-INF/services/org.apache.tuscany.sca.invocation.MessageFactory @@ -0,0 +1,18 @@ +# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+org.apache.tuscany.sca.core.invocation.MessageFactoryImpl
diff --git a/branches/sca-java-1.5.1/modules/core/src/main/resources/META-INF/services/org.apache.tuscany.sca.work.WorkScheduler b/branches/sca-java-1.5.1/modules/core/src/main/resources/META-INF/services/org.apache.tuscany.sca.work.WorkScheduler new file mode 100644 index 0000000000..93d93491a8 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/main/resources/META-INF/services/org.apache.tuscany.sca.work.WorkScheduler @@ -0,0 +1,18 @@ +# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+org.apache.tuscany.sca.core.work.DefaultWorkScheduler
diff --git a/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/DefaultExtensionPointRegistryTestCase.java b/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/DefaultExtensionPointRegistryTestCase.java new file mode 100644 index 0000000000..7b44736d4b --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/DefaultExtensionPointRegistryTestCase.java @@ -0,0 +1,52 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core; + +import junit.framework.TestCase; + +public class DefaultExtensionPointRegistryTestCase extends TestCase { + private ExtensionPointRegistry registry; + + @Override + protected void setUp() throws Exception { + super.setUp(); + registry = new DefaultExtensionPointRegistry(); + } + + public void testRegistry() { + MyRegistry service = new MyREgistryImpl(); + registry.addExtensionPoint(service); + assertSame(service, registry.getExtensionPoint(MyRegistry.class)); + registry.removeExtensionPoint(service); + assertNull(registry.getExtensionPoint(MyRegistry.class)); + } + + public static interface MyRegistry { + void doSomething(); + } + + private static class MyREgistryImpl implements MyRegistry { + + public void doSomething() { + } + + } + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/event/BaseEventPublisherTestCase.java b/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/event/BaseEventPublisherTestCase.java new file mode 100644 index 0000000000..2bc78c3d35 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/event/BaseEventPublisherTestCase.java @@ -0,0 +1,98 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.event; + + +import junit.framework.TestCase; + +import org.apache.tuscany.sca.event.Event; +import org.apache.tuscany.sca.event.EventFilter; +import org.apache.tuscany.sca.event.EventPublisher; +import org.apache.tuscany.sca.event.RuntimeEventListener; +import org.apache.tuscany.sca.event.TrueFilter; +import org.easymock.EasyMock; + +/** + * @version $Rev$ $Date$ + */ +public class BaseEventPublisherTestCase extends TestCase { + EventPublisher publisher; + + public void testFireListener() { + Event event = new TestEvent(); + RuntimeEventListener listener = EasyMock.createMock(RuntimeEventListener.class); + listener.onEvent(EasyMock.same(event)); + EasyMock.expectLastCall(); + EasyMock.replay(listener); + publisher.addListener(listener); + publisher.publish(event); + EasyMock.verify(listener); + } + + public void testRemoveListener() { + Event event = new TestEvent(); + RuntimeEventListener listener = EasyMock.createMock(RuntimeEventListener.class); + EasyMock.replay(listener); + publisher.addListener(listener); + publisher.removeListener(listener); + publisher.publish(event); + EasyMock.verify(listener); + } + + public void testFalseFilterListener() { + Event event = new TestEvent(); + RuntimeEventListener listener = EasyMock.createMock(RuntimeEventListener.class); + EasyMock.replay(listener); + publisher.addListener(new FalseFilter(), listener); + publisher.publish(event); + EasyMock.verify(listener); + } + + public void testTrueFilterListener() { + Event event = new TestEvent(); + RuntimeEventListener listener = EasyMock.createMock(RuntimeEventListener.class); + listener.onEvent(EasyMock.same(event)); + EasyMock.expectLastCall(); + EasyMock.replay(listener); + publisher.addListener(new TrueFilter(), listener); + publisher.publish(event); + EasyMock.verify(listener); + } + + @Override + protected void setUp() throws Exception { + publisher = new BaseEventPublisher() { + }; + } + + private class TestEvent implements Event { + public Object getSource() { + return null; + } + } + + private class FalseFilter implements EventFilter { + + public boolean match(Event event) { + return false; + } + } + + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/event/EventTestCase.java b/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/event/EventTestCase.java new file mode 100644 index 0000000000..48dcf8df07 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/event/EventTestCase.java @@ -0,0 +1,69 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.event; + +import java.net.URI; + +import junit.framework.TestCase; + +/** + * @version $Rev$ $Date$ + */ +public class EventTestCase extends TestCase { + private URI uri = URI.create("foo"); + + public void testCompositeStart() { + ComponentStart event = new ComponentStart(this, uri); + assertEquals(uri, event.getComponentURI()); + } + + public void testCompositeStop() { + ComponentStop event = new ComponentStop(this, uri); + assertEquals(uri, event.getComponentURI()); + } + + public void testHttpSessionStart() { + Object id = new Object(); + HttpSessionStart event = new HttpSessionStart(this, id); + assertEquals(this, event.getSource()); + assertEquals(id, event.getSessionID()); + } + + public void testHttpSessionEnd() { + Object id = new Object(); + HttpSessionEnd event = new HttpSessionEnd(this, id); + assertEquals(this, event.getSource()); + assertEquals(id, event.getSessionID()); + } + + public void testRequestStart() { + RequestStart event = new RequestStart(this); + assertEquals(this, event.getSource()); + } + + public void testReequestEnd() { + RequestEnd event = new RequestEnd(this); + assertEquals(this, event.getSource()); + } + + + @Override + protected void setUp() throws Exception { + } +} diff --git a/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/invocation/PhaseManagerTestCase.java b/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/invocation/PhaseManagerTestCase.java new file mode 100644 index 0000000000..99d5ec7bc9 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/invocation/PhaseManagerTestCase.java @@ -0,0 +1,51 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.core.invocation; + +import java.util.List; + +import junit.framework.Assert; + +import org.junit.Test; + +/** + * @version $Rev$ $Date$ + */ +public class PhaseManagerTestCase { + + @Test + public void testDiscovery() { + PhaseManager pm = new PhaseManager("org.apache.tuscany.sca.invocation.PhaseTest"); + List<String> phases = pm.getAllPhases(); + System.out.println(phases.size()); + System.out.println(phases); + // Assert.assertEquals(15, phases.size()); + Assert.assertEquals("reference.first", phases.get(0)); + + int rt = phases.indexOf("reference.transaction"); + Assert.assertTrue(rt > phases.indexOf("reference.interface")); + + int st = phases.indexOf("service.transaction"); + Assert.assertTrue(st > phases.indexOf("service.binding")); + + int it = phases.indexOf("implementation.transaction"); + Assert.assertTrue(it < phases.indexOf("implementation.policy")); + } +} diff --git a/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/invocation/PhaseSorterTestCase.java b/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/invocation/PhaseSorterTestCase.java new file mode 100644 index 0000000000..61164fa2de --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/invocation/PhaseSorterTestCase.java @@ -0,0 +1,63 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.invocation; + +import java.util.Arrays; +import java.util.List; + +import junit.framework.TestCase; + +public class PhaseSorterTestCase extends TestCase { + private PhaseSorter<String> graph; + + @Override + protected void setUp() throws Exception { + super.setUp(); + graph = new PhaseSorter<String>(); + } + + public void testSort() { + graph.addEdge("a", "b"); + graph.addEdge("a", "c"); + graph.addEdge("c", "d"); + graph.addEdge("b", "c"); + List<String> order = graph.topologicalSort(true); + assertEquals(Arrays.asList("a", "b", "c", "d"), order); + assertTrue(!graph.getVertices().isEmpty()); + + graph.addEdge("d", "a"); + try { + order = graph.topologicalSort(true); + assertTrue("Should have failed", false); + } catch (IllegalArgumentException e) { + assertTrue(true); + } + + graph.removeEdge("d", "a"); + order = graph.topologicalSort(false); + assertEquals(Arrays.asList("a", "b", "c", "d"), order); + assertTrue(graph.getVertices().isEmpty()); + } + + @Override + protected void tearDown() throws Exception { + super.tearDown(); + } + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/scope/AbstractScopeContainerTestCase.java b/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/scope/AbstractScopeContainerTestCase.java new file mode 100644 index 0000000000..64114f7fb2 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/scope/AbstractScopeContainerTestCase.java @@ -0,0 +1,69 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.scope; + +import java.net.URI; + +import junit.framework.TestCase; + +import org.apache.tuscany.sca.assembly.Implementation; +import org.apache.tuscany.sca.core.context.InstanceWrapper; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.easymock.EasyMock; +import org.easymock.IMocksControl; + +/** + * @version $Rev$ $Date$ + */ +public abstract class AbstractScopeContainerTestCase<T, KEY> extends TestCase { + protected IMocksControl control; + protected ScopeContainer<KEY> scopeContainer; + protected URI groupId; + protected KEY contextId; + protected RuntimeComponent component; + protected ScopedImplementation implementation; + protected InstanceWrapper<T> wrapper; + + @SuppressWarnings("unchecked") + @Override + protected void setUp() throws Exception { + super.setUp(); + control = EasyMock.createStrictControl(); + component = control.createMock(RuntimeComponent.class); + wrapper = control.createMock(InstanceWrapper.class); + implementation = control.createMock(ScopedImplementation.class); + EasyMock.expect(component.getImplementation()).andReturn(implementation).anyTimes(); + } + + protected void preRegisterComponent() throws Exception { + scopeContainer.start(); + EasyMock.expect(implementation.isEagerInit()).andStubReturn(false); + } + + protected void expectCreateWrapper() throws Exception { + EasyMock.expect(implementation.createInstanceWrapper()).andReturn(wrapper); + wrapper.start(); + } + + protected static interface ScopedImplementation extends ScopedImplementationProvider, Implementation { + + } + + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/store/MemoryStoreTestCase.java b/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/store/MemoryStoreTestCase.java new file mode 100644 index 0000000000..d46d77b4b8 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/store/MemoryStoreTestCase.java @@ -0,0 +1,165 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.store; + +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import junit.framework.TestCase; + +import org.apache.tuscany.sca.event.RuntimeEventListener; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.store.DuplicateRecordException; +import org.apache.tuscany.sca.store.Store; +import org.apache.tuscany.sca.store.StoreExpirationEvent; +import org.apache.tuscany.sca.store.StoreMonitor; +import org.easymock.EasyMock; +import org.easymock.IAnswer; + +/** + * @version $Rev$ $Date$ + */ +public class MemoryStoreTestCase extends TestCase { + private StoreMonitor monitor; + + public void testEviction() throws Exception { + MemoryStore store = new MemoryStore(monitor); + store.setReaperInterval(10); + store.init(); + RuntimeComponent component = EasyMock.createNiceMock(RuntimeComponent.class); + EasyMock.replay(component); + String id = UUID.randomUUID().toString(); + Object value = new Object(); + store.insertRecord(component, id, value, 1); + Thread.sleep(200); + assertNull(store.readRecord(component, id)); + store.destroy(); + } + + public void testNotifyOnEviction() throws Exception { + final CountDownLatch latch = new CountDownLatch(1); + RuntimeEventListener listener = EasyMock.createMock(RuntimeEventListener.class); + listener.onEvent(EasyMock.isA(StoreExpirationEvent.class)); + EasyMock.expectLastCall().andStubAnswer(new IAnswer<Object>() { + public Object answer() throws Throwable { + latch.countDown(); + return null; + } + }); + EasyMock.replay(listener); + MemoryStore store = new MemoryStore(monitor); + store.addListener(listener); + store.setReaperInterval(10); + store.init(); + RuntimeComponent component = EasyMock.createNiceMock(RuntimeComponent.class); + EasyMock.replay(component); + String id = UUID.randomUUID().toString(); + Object value = new Object(); + store.insertRecord(component, id, value, 1); + if (!latch.await(1000, TimeUnit.MILLISECONDS)) { + // failed to notify listener + fail(); + } + EasyMock.verify(listener); + } + + public void testNoEviction() throws Exception { + MemoryStore store = new MemoryStore(monitor); + store.setReaperInterval(10); + store.init(); + RuntimeComponent component = EasyMock.createNiceMock(RuntimeComponent.class); + EasyMock.replay(component); + String id = UUID.randomUUID().toString(); + Object value = new Object(); + store.insertRecord(component, id, value, Store.NEVER); + Thread.sleep(100); + assertNotNull(store.readRecord(component, id)); + store.destroy(); + } + + public void testInsertRecord() throws Exception { + MemoryStore store = new MemoryStore(monitor); + store.setReaperInterval(10); + store.init(); + RuntimeComponent component = EasyMock.createNiceMock(RuntimeComponent.class); + EasyMock.replay(component); + String id = UUID.randomUUID().toString(); + Object value = new Object(); + store.insertRecord(component, id, value, Store.NEVER); + store.destroy(); + } + + public void testInsertAlreadyExists() throws Exception { + MemoryStore store = new MemoryStore(monitor); + store.setReaperInterval(10); + store.init(); + RuntimeComponent component = EasyMock.createMock(RuntimeComponent.class); + EasyMock.expect(component.getURI()).andReturn("component"); + EasyMock.replay(component); + String id = UUID.randomUUID().toString(); + Object value = new Object(); + store.insertRecord(component, id, value, Store.NEVER); + try { + store.insertRecord(component, id, value, Store.NEVER); + fail(); + } catch (DuplicateRecordException e) { + //expected + } + store.destroy(); + } + + public void testUpdateRecord() throws Exception { + MemoryStore store = new MemoryStore(monitor); + store.setReaperInterval(10); + store.init(); + RuntimeComponent component = EasyMock.createNiceMock(RuntimeComponent.class); + EasyMock.replay(component); + String id = UUID.randomUUID().toString(); + Object value = new Object(); + Object newValue = new Object(); + + store.insertRecord(component, id, value, Store.NEVER); + store.updateRecord(component, id, newValue, 1L); + assertEquals(newValue, store.readRecord(component, id)); + store.destroy(); + } + + public void testDeleteRecord() throws Exception { + MemoryStore store = new MemoryStore(monitor); + store.setReaperInterval(10); + store.init(); + RuntimeComponent component = EasyMock.createNiceMock(RuntimeComponent.class); + EasyMock.replay(component); + String id = UUID.randomUUID().toString(); + Object value = new Object(); + + store.insertRecord(component, id, value, Store.NEVER); + store.removeRecord(component, id); + assertNull(store.readRecord(component, id)); + store.destroy(); + } + + @Override + protected void setUp() throws Exception { + monitor = EasyMock.createNiceMock(StoreMonitor.class); + EasyMock.replay(monitor); + } + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/wire/CallbackInterfaceInterceptorTestCase.java b/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/wire/CallbackInterfaceInterceptorTestCase.java new file mode 100644 index 0000000000..1aba9656d8 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/wire/CallbackInterfaceInterceptorTestCase.java @@ -0,0 +1,62 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.wire; + +import junit.framework.TestCase; + +import org.apache.tuscany.sca.core.assembly.EndpointReferenceImpl; +import org.apache.tuscany.sca.core.invocation.CallbackInterfaceInterceptor; +import org.apache.tuscany.sca.core.invocation.MessageFactoryImpl; +import org.apache.tuscany.sca.invocation.Interceptor; +import org.apache.tuscany.sca.invocation.Message; +import org.easymock.EasyMock; +import org.osoa.sca.NoRegisteredCallbackException; + +/** + * @version $Rev$ $Date$ + */ +public class CallbackInterfaceInterceptorTestCase extends TestCase { + + public void testHasCallbackObject() { + CallbackInterfaceInterceptor interceptor = new CallbackInterfaceInterceptor(); + Interceptor next = EasyMock.createMock(Interceptor.class); + EasyMock.expect(next.invoke(EasyMock.isA(Message.class))).andReturn(null); + EasyMock.replay(next); + interceptor.setNext(next); + Message msg = new MessageFactoryImpl().createMessage(); + msg.setFrom(new EndpointReferenceImpl("uri")); + msg.getFrom().getReferenceParameters().setCallbackObjectID("ABC"); + interceptor.invoke(msg); + EasyMock.verify(next); + } + + public void testNoCallbackObject() { + CallbackInterfaceInterceptor interceptor = new CallbackInterfaceInterceptor(); + Message msg = new MessageFactoryImpl().createMessage(); + msg.setFrom(new EndpointReferenceImpl("uri")); + msg.getFrom().getReferenceParameters().setCallbackObjectID(null); + try { + interceptor.invoke(msg); + fail(); + } catch (NoRegisteredCallbackException e) { + // expected + } + } + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/wire/InvocationChainImplTestCase.java b/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/wire/InvocationChainImplTestCase.java new file mode 100644 index 0000000000..1ad0927d16 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/wire/InvocationChainImplTestCase.java @@ -0,0 +1,93 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.wire; + +import junit.framework.TestCase; + +import org.apache.tuscany.sca.core.invocation.InvocationChainImpl; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.interfacedef.impl.OperationImpl; +import org.apache.tuscany.sca.invocation.Interceptor; +import org.apache.tuscany.sca.invocation.InvocationChain; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.Message; +import org.apache.tuscany.sca.invocation.Phase; + +/** + * @version $Rev$ $Date$ + */ +public class InvocationChainImplTestCase extends TestCase { + + public void testInsertAtEnd() throws Exception { + Operation op = newOperation("foo"); + InvocationChain chain = new InvocationChainImpl(op, op, true); + Interceptor inter2 = new MockInterceptor(); + Interceptor inter1 = new MockInterceptor(); + chain.addInterceptor(inter1); + chain.addInterceptor(inter2); + Interceptor head = (Interceptor)chain.getHeadInvoker(); + assertEquals(inter1, head); + assertEquals(inter2, head.getNext()); + assertEquals(inter2, chain.getTailInvoker()); + + } + + public void testAddByPhase() throws Exception { + Operation op = newOperation("foo"); + InvocationChain chain = new InvocationChainImpl(op, op, false); + Interceptor inter1 = new MockInterceptor(); + Interceptor inter2 = new MockInterceptor(); + Interceptor inter3 = new MockInterceptor(); + Interceptor inter4 = new MockInterceptor(); + chain.addInterceptor(inter3); // SERVICE + chain.addInterceptor(Phase.IMPLEMENTATION_POLICY, inter4); + chain.addInterceptor(Phase.SERVICE_POLICY, inter2); + chain.addInterceptor(Phase.SERVICE_BINDING, inter1); + Interceptor head = (Interceptor)chain.getHeadInvoker(); + assertEquals(inter1, head); + assertEquals(inter2, inter1.getNext()); + assertEquals(inter3, inter2.getNext()); + assertEquals(inter4, inter3.getNext()); + assertEquals(inter4, chain.getTailInvoker()); + } + + private class MockInterceptor implements Interceptor { + + private Invoker next; + + public Message invoke(Message msg) { + return null; + } + + public void setNext(Invoker next) { + this.next = next; + } + + public Invoker getNext() { + return next; + } + + } + + private static Operation newOperation(String name) { + Operation operation = new OperationImpl(); + operation.setName(name); + return operation; + } +} diff --git a/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/wire/NonBlockingInterceptorTestCase.java b/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/wire/NonBlockingInterceptorTestCase.java new file mode 100644 index 0000000000..b8150d4edc --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/wire/NonBlockingInterceptorTestCase.java @@ -0,0 +1,74 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.wire; + +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expectLastCall; +import static org.easymock.EasyMock.getCurrentArguments; +import static org.easymock.EasyMock.isA; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; +import junit.framework.TestCase; + +import org.apache.tuscany.sca.core.invocation.NonBlockingInterceptor; +import org.apache.tuscany.sca.core.invocation.ThreadMessageContext; +import org.apache.tuscany.sca.invocation.Interceptor; +import org.apache.tuscany.sca.invocation.Message; +import org.apache.tuscany.sca.work.WorkScheduler; +import org.easymock.EasyMock; +import org.easymock.IAnswer; + +/** + * @version $Rev$ $Date$ + */ +public class NonBlockingInterceptorTestCase extends TestCase { + + public void testInvoke() throws Exception { + WorkScheduler scheduler = createMock(WorkScheduler.class); + scheduler.scheduleWork(isA(Runnable.class)); + expectLastCall().andStubAnswer(new IAnswer<Object>() { + public Object answer() throws Throwable { + Runnable runnable = (Runnable) getCurrentArguments()[0]; + runnable.run(); + return null; + } + }); + replay(scheduler); + Message context = createMock(Message.class); + //String convID = "convID"; + //TODO port to the new way of dealing with conversation IDs later + //EasyMock.expect(context.getConversationID()).andReturn(convID); + EasyMock.replay(context); + ThreadMessageContext.setMessageContext(context); + Message msg = createMock(Message.class); + //TODO port to the new way of dealing with conversation IDs later + //msg.setConversationID(convID); + Interceptor next = EasyMock.createMock(Interceptor.class); + EasyMock.expect(next.invoke(EasyMock.eq(msg))).andReturn(msg); + EasyMock.expect(msg.isFault()).andReturn(false); + EasyMock.replay(next); + EasyMock.replay(msg); + Interceptor interceptor = new NonBlockingInterceptor(scheduler, next); + interceptor.invoke(msg); + verify(context); + verify(next); + verify(msg); + } + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/work/FailingWork.java b/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/work/FailingWork.java new file mode 100644 index 0000000000..c69a1908e8 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/work/FailingWork.java @@ -0,0 +1,53 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.work; + + +/** + * Simple Work item that will throw an exception + * + * @version $Rev$ $Date$ + */ +public class FailingWork extends Work { + + public FailingWork() { + super(null); + } + + /** + * {@inheritDoc} + */ + public boolean isDaemon() { + return false; + } + + /** + * {@inheritDoc} + */ + public void release() { + } + + /** + * Throws an IllegalArgumentException + */ + public void run() { + System.out.println("Starting " + this + " and throwing an Exception"); + throw new IllegalArgumentException("Sample exception from " + this); + } +} diff --git a/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/work/JSR237MyFailingRunnable.java b/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/work/JSR237MyFailingRunnable.java new file mode 100644 index 0000000000..91b45dfbcb --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/work/JSR237MyFailingRunnable.java @@ -0,0 +1,43 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.work; + +/** + * Simple Runnable that throws an IllegalArgumentException + * + * @version $Rev$ $Date$ + */ +public class JSR237MyFailingRunnable extends JSR237MyRunnable { + + /** + * Constructor + */ + public JSR237MyFailingRunnable() { + super(-1); + } + + /** + * Sleeps for a period of time defined by sleepTime + */ + @Override + public void run() { + System.out.println("Starting " + this + " and throwing an Exception"); + throw new IllegalArgumentException("Sample exception from " + this); + } +} diff --git a/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/work/JSR237MyRunnable.java b/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/work/JSR237MyRunnable.java new file mode 100644 index 0000000000..a7617f7a70 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/work/JSR237MyRunnable.java @@ -0,0 +1,71 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.work; + +import java.util.concurrent.atomic.AtomicInteger; + +/** + * Simple Runnable that is used for testing Jsr237WorkScheduler + * + * @version $Rev$ $Date$ + */ +public class JSR237MyRunnable implements Runnable { + + /** + * Count of workAccepted() method calls + */ + private AtomicInteger runCompletedCount = new AtomicInteger(); + + /** + * The amount of time to sleep in the Run loop + */ + private final long sleepTime; + + /** + * Constructor + * + * @param sleepTime The amount of time to sleep (in milliseconds) in the run() method + */ + public JSR237MyRunnable(long sleepTime) { + this.sleepTime = sleepTime; + } + + /** + * Sleeps for a period of time defined by sleepTime + */ + public void run() { + System.out.println("Starting " + this); + try { + Thread.sleep(sleepTime); + } catch (InterruptedException e) { + e.printStackTrace(); + } + System.out.println("Done " + this); + runCompletedCount.incrementAndGet(); + } + + /** + * Returns the number of completed calls to run() + * + * @return The number of completed calls to run() + */ + public int getRunCompletedCount() { + return runCompletedCount.get(); + } +} diff --git a/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/work/JSR237MyRunnerListener.java b/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/work/JSR237MyRunnerListener.java new file mode 100644 index 0000000000..75840efef4 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/work/JSR237MyRunnerListener.java @@ -0,0 +1,154 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.work; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +import org.apache.tuscany.sca.work.NotificationListener; + +/** + * Simple NotificationListener that is used for testing Jsr237WorkScheduler + * + * @version $Rev$ $Date$ + */ +public class JSR237MyRunnerListener implements NotificationListener<JSR237MyRunnable> { + + /** + * Count of workAccepted() method calls + */ + private AtomicInteger workAcceptedCallCount = new AtomicInteger(); + + /** + * Count of workStarted() method calls + */ + private AtomicInteger workStartedCallCount = new AtomicInteger(); + + /** + * Count of workCompleted() method calls + */ + private AtomicInteger workCompletedCallCount = new AtomicInteger(); + + /** + * Count of workFailed() method calls + */ + private AtomicInteger workFailedCallCount = new AtomicInteger(); + + /** + * Count of workRejected() method calls + */ + private AtomicInteger workRejectedCallCount = new AtomicInteger(); + + /** + * List of all exceptions thrown by Work items + */ + private List<Throwable> workExceptions = Collections.synchronizedList(new ArrayList<Throwable>()); + + /** + * {@inheritDoc} + */ + public void workAccepted(JSR237MyRunnable work) { + workAcceptedCallCount.incrementAndGet(); + } + + /** + * {@inheritDoc} + */ + public void workCompleted(JSR237MyRunnable work) { + workCompletedCallCount.incrementAndGet(); + } + + /** + * {@inheritDoc} + */ + public void workFailed(JSR237MyRunnable work, Throwable error) { + workExceptions.add(error); + workFailedCallCount.incrementAndGet(); + } + + /** + * {@inheritDoc} + */ + public void workRejected(JSR237MyRunnable work) { + workRejectedCallCount.incrementAndGet(); + } + + /** + * {@inheritDoc} + */ + public void workStarted(JSR237MyRunnable work) { + workStartedCallCount.incrementAndGet(); + } + + /** + * Returns the number of calls to workAccepted() + * + * @return The number of calls to workAccepted() + */ + public int getWorkAcceptedCallCount() { + return workAcceptedCallCount.get(); + } + + /** + * Returns the number of calls to workStarted() + * + * @return The number of calls to workStarted() + */ + public int getWorkStartedCallCount() { + return workStartedCallCount.get(); + } + + /** + * Returns the number of calls to workCompleted() + * + * @return The number of calls to workCompleted() + */ + public int getWorkCompletedCallCount() { + return workCompletedCallCount.get(); + } + + /** + * Returns the number of calls to workFailed() + * + * @return The number of calls to workFailed() + */ + public int getWorkFailedCallCount() { + return workFailedCallCount.get(); + } + + /** + * Returns the number of calls to workRejected() + * + * @return The number of calls to workRejected() + */ + public int getWorkRejectedCallCount() { + return workRejectedCallCount.get(); + } + + /** + * Returns a List of all exceptions that are thrown by the Work items + * + * @return A List of all exceptions that are thrown by the Work items + */ + public List<Throwable> getWorkExceptions() { + return Collections.unmodifiableList(workExceptions); + } +} diff --git a/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/work/Jsr237WorkSchedulerTestCase.java b/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/work/Jsr237WorkSchedulerTestCase.java new file mode 100644 index 0000000000..185394d7e8 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/work/Jsr237WorkSchedulerTestCase.java @@ -0,0 +1,240 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.work; + +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + * Test case for Jsr237WorkScheduler + * + * @version $Rev$ $Date$ + */ +public class Jsr237WorkSchedulerTestCase { + + /** + * Wait up to 20 seconds for the Work units to complete + */ + private static final long WAIT_TIMEOUT = 20000; + + /** + * This is the shared instance of the ThreadPoolWorkManager used by the tests + */ + private static DefaultWorkScheduler workSchedular = null; + + /** + * Setup the Jsr237WorkScheduler + */ + @BeforeClass + public static void setup() { + workSchedular = new DefaultWorkScheduler(); + } + + /** + * Make sure that the Jsr237WorkScheduler is stopped after running the tests + */ + @AfterClass + public static void destroy() { + if (workSchedular != null) { + workSchedular.destroy(); + } + } + + /** + * Tests running a single fast job on the Jsr237WorkScheduler + */ + @Test + public void testSingleFastJob() { + // Create the work and register it + JSR237MyRunnable fast = new JSR237MyRunnable(10); + JSR237MyRunnerListener listener = new JSR237MyRunnerListener(); + workSchedular.scheduleWork(fast, listener); + + // Wait for the 1 job to complete + waitForWorkToComplete(listener, 1); + + // Test that the job completed successfully. + Assert.assertEquals(1, listener.getWorkAcceptedCallCount()); + Assert.assertEquals(0, listener.getWorkRejectedCallCount()); + Assert.assertEquals(1, listener.getWorkStartedCallCount()); + Assert.assertEquals(1, listener.getWorkCompletedCallCount()); + Assert.assertEquals(0, listener.getWorkExceptions().size()); + } + + /** + * Tests running a single job that fails on the Jsr237WorkScheduler + */ + @Test + public void testSingleFailingJob() { + // Create the work and register it + JSR237MyFailingRunnable fail = new JSR237MyFailingRunnable(); + JSR237MyRunnerListener listener = new JSR237MyRunnerListener(); + workSchedular.scheduleWork(fail, listener); + + // Wait for the 1 job to complete + waitForWorkToComplete(listener, 1); + + // Test that the job completed successfully. + Assert.assertEquals(1, listener.getWorkAcceptedCallCount()); + Assert.assertEquals(0, listener.getWorkRejectedCallCount()); + Assert.assertEquals(1, listener.getWorkStartedCallCount()); + Assert.assertEquals(0, listener.getWorkCompletedCallCount()); + Assert.assertEquals(1, listener.getWorkFailedCallCount()); + Assert.assertEquals(1, listener.getWorkExceptions().size()); + } + + /** + * Tests running a mixture of fast and slow jobs on the Jsr237WorkScheduler + */ + @Test + public void testMultipleJobs() { + // Create the work and register it + JSR237MyRunnable fast1 = new JSR237MyRunnable(50); + JSR237MyRunnable fast2 = new JSR237MyRunnable(100); + JSR237MyRunnable fast3 = new JSR237MyRunnable(200); + JSR237MyRunnable slow1= new JSR237MyRunnable(2000); + JSR237MyRunnable slow2 = new JSR237MyRunnable(2000); + JSR237MyRunnerListener listener = new JSR237MyRunnerListener(); + workSchedular.scheduleWork(fast1, listener); + workSchedular.scheduleWork(fast2, listener); + workSchedular.scheduleWork(fast3, listener); + workSchedular.scheduleWork(slow1, listener); + workSchedular.scheduleWork(slow2, listener); + + // Wait for the 5 jobs to complete + waitForWorkToComplete(listener, 5); + + // Test that the job completed successfully. + Assert.assertEquals(5, listener.getWorkAcceptedCallCount()); + Assert.assertEquals(0, listener.getWorkRejectedCallCount()); + Assert.assertEquals(5, listener.getWorkStartedCallCount()); + Assert.assertEquals(5, listener.getWorkCompletedCallCount()); + Assert.assertEquals(0, listener.getWorkExceptions().size()); + } + + /** + * Tests running a mixture of fast and slow jobs some of which fail on the + * Jsr237WorkScheduler + */ + @Test + public void testMultipleJobsSomeFail() { + // Create the work and register it + JSR237MyRunnable fast1 = new JSR237MyRunnable(50); + JSR237MyRunnable fast2 = new JSR237MyRunnable(100); + JSR237MyRunnable fast3 = new JSR237MyRunnable(200); + JSR237MyRunnable slow1= new JSR237MyRunnable(2000); + JSR237MyRunnable slow2 = new JSR237MyRunnable(2000); + JSR237MyFailingRunnable fail1 = new JSR237MyFailingRunnable(); + JSR237MyFailingRunnable fail2 = new JSR237MyFailingRunnable(); + JSR237MyRunnerListener listener = new JSR237MyRunnerListener(); + workSchedular.scheduleWork(fast1, listener); + workSchedular.scheduleWork(fast2, listener); + workSchedular.scheduleWork(fail1, listener); + workSchedular.scheduleWork(fast3, listener); + workSchedular.scheduleWork(slow1, listener); + workSchedular.scheduleWork(fail2, listener); + workSchedular.scheduleWork(slow2, listener); + + // Wait for the 7 jobs to complete + waitForWorkToComplete(listener, 7); + + // Test that the job completed successfully. + Assert.assertEquals(7, listener.getWorkAcceptedCallCount()); + Assert.assertEquals(0, listener.getWorkRejectedCallCount()); + Assert.assertEquals(7, listener.getWorkStartedCallCount()); + Assert.assertEquals(5, listener.getWorkCompletedCallCount()); + Assert.assertEquals(2, listener.getWorkFailedCallCount()); + Assert.assertEquals(2, listener.getWorkExceptions().size()); + } + + /** + * Tests running a single job that has no listener + */ + @Test + public void testSingleFastJobWithNoListener() { + // Create the work and register it + JSR237MyRunnable fast = new JSR237MyRunnable(10); + workSchedular.scheduleWork(fast); + + // Wait for the job to complete + long startTime = System.currentTimeMillis(); + while (true) { + int completedCount = fast.getRunCompletedCount(); + if (completedCount == 1) { + break; + } + + if (System.currentTimeMillis() - startTime > WAIT_TIMEOUT) { + Assert.fail("Only " + completedCount + " work items completed before timeout"); + return; + } + + // Lets wait for the job to complete + try { + Thread.sleep(25); + } catch (InterruptedException ex) { + Assert.fail("Unexpected exception: " + ex); + } + } + } + + /** + * Tests scheduling a null as the work item + */ + @Test + public void testNullWork() { + try { + workSchedular.scheduleWork(null); + Assert.fail("Should have thrown IllegalArgumentException "); + } catch (IllegalArgumentException ex) { + // As expected + Assert.assertTrue(ex.toString().indexOf("null") != -1); + } + } + + /** + * Waits for the specified number of jobs to complete or the timeout to fire. + * + * @param listener The listener to use to track Work unit completion + * @param completedWorkItemsToWaitFor The number of Work items to complete + */ + private void waitForWorkToComplete(JSR237MyRunnerListener listener, int completedWorkItemsToWaitFor) { + long startTime = System.currentTimeMillis(); + while (true) { + int completedCount = listener.getWorkCompletedCallCount() + listener.getWorkFailedCallCount(); + if (completedCount == completedWorkItemsToWaitFor) { + return; + } + + if (System.currentTimeMillis() - startTime > WAIT_TIMEOUT) { + Assert.fail("Only " + completedCount + " work items completed before timeout"); + return; + } + + // Lets wait for more jobs to complete + try { + Thread.sleep(25); + } catch (InterruptedException ex) { + Assert.fail("Unexpected exception: " + ex); + } + } + } +} diff --git a/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/work/TestWorkListener.java b/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/work/TestWorkListener.java new file mode 100644 index 0000000000..58a1b87c48 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/work/TestWorkListener.java @@ -0,0 +1,153 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.work; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +import org.apache.tuscany.sca.work.WorkSchedulerException; +import org.junit.Assert; + +/** + * A simple WorkListener that tracks invocations to it. + * + * @version $Rev$ $Date$ + */ +public class TestWorkListener implements WorkListener { + + /** + * Count of workAccepted() method calls + */ + private AtomicInteger workAcceptedCallCount = new AtomicInteger(); + + /** + * Count of workStarted() method calls + */ + private AtomicInteger workStartedCallCount = new AtomicInteger(); + + /** + * Count of workCompleted() method calls + */ + private AtomicInteger workCompletedCallCount = new AtomicInteger(); + + /** + * Count of workRejected() method calls + */ + private AtomicInteger workRejectedCallCount = new AtomicInteger(); + + /** + * List of all exceptions thrown by Work items + */ + private List<WorkSchedulerException> workExceptions = Collections.synchronizedList(new ArrayList<WorkSchedulerException>()); + + /** + * {@inheritDoc} + */ + public void workAccepted(WorkEvent work) { + workAcceptedCallCount.incrementAndGet(); + + // Validate the WorkEvent + Assert.assertNotNull(work.getWorkItem()); + Assert.assertEquals(WorkEvent.WORK_ACCEPTED, work.getType()); + } + + /** + * {@inheritDoc} + */ + public void workStarted(WorkEvent work) { + workStartedCallCount.incrementAndGet(); + + // Validate the WorkEvent + Assert.assertNotNull(work.getWorkItem()); + Assert.assertEquals(WorkEvent.WORK_STARTED, work.getType()); + } + + /** + * {@inheritDoc} + */ + public void workCompleted(WorkEvent work) { + if (work.getException() != null) { + workExceptions.add(work.getException()); + } + + // Validate the WorkEvent + Assert.assertNotNull(work.getWorkItem()); + Assert.assertEquals(WorkEvent.WORK_COMPLETED, work.getType()); + + workCompletedCallCount.incrementAndGet(); + } + + /** + * {@inheritDoc} + */ + public void workRejected(WorkEvent work) { + workRejectedCallCount.incrementAndGet(); + + // Validate the WorkEvent + Assert.assertNotNull(work.getWorkItem()); + Assert.assertEquals(WorkEvent.WORK_REJECTED, work.getType()); + } + + /** + * Returns the number of calls to workAccepted() + * + * @return The number of calls to workAccepted() + */ + public int getWorkAcceptedCallCount() { + return workAcceptedCallCount.get(); + } + + /** + * Returns the number of calls to workStarted() + * + * @return The number of calls to workStarted() + */ + public int getWorkStartedCallCount() { + return workStartedCallCount.get(); + } + + /** + * Returns the number of calls to workCompleted() + * + * @return The number of calls to workCompleted() + */ + public int getWorkCompletedCallCount() { + return workCompletedCallCount.get(); + } + + /** + * Returns the number of calls to workRejected() + * + * @return The number of calls to workRejected() + */ + public int getWorkRejectedCallCount() { + return workRejectedCallCount.get(); + } + + /** + * Returns a List of all exceptions that are thrown by the Work items + * + * @return A List of all exceptions that are thrown by the Work items + */ + public List<WorkSchedulerException> getWorkExceptions() { + return Collections.unmodifiableList(workExceptions); + } +} diff --git a/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/work/ThreadPoolWorkManagerTestCase.java b/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/work/ThreadPoolWorkManagerTestCase.java new file mode 100644 index 0000000000..9e5b8d035e --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/work/ThreadPoolWorkManagerTestCase.java @@ -0,0 +1,238 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.work; + +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + * This test case will test the ThreadPoolWorkManager + * + * @version $Rev$ $Date$ + */ +public class ThreadPoolWorkManagerTestCase { + + /** + * Wait up to 20 seconds for the Work units to complete + */ + private static final long WAIT_TIMEOUT = 20000; + + /** + * This is the shared instance of the ThreadPoolWorkManager used by the tests + */ + private static ThreadPoolWorkManager workManager = null; + + /** + * Setup the ThreadPoolWorkManager + */ + @BeforeClass + public static void setup() { + workManager = new ThreadPoolWorkManager(10); + } + + /** + * Make sure that the ThreadPoolWorkManager is stopped after running the tests + */ + @AfterClass + public static void destroy() { + if (workManager != null) { + workManager.destroy(); + } + } + + /** + * Tests running a single fast job on the ThreadPoolWorkManager + */ + @Test + public void testSingleFastJob() { + // Create the work and register it + TimeDelayWork fast = new TimeDelayWork(10); + TestWorkListener listener = new TestWorkListener(); + workManager.schedule(fast, listener); + + // Wait for the 1 job to complete + waitForWorkToComplete(listener, 1); + + // Test that the job completed successfully. + Assert.assertEquals(1, listener.getWorkAcceptedCallCount()); + Assert.assertEquals(0, listener.getWorkRejectedCallCount()); + Assert.assertEquals(1, listener.getWorkStartedCallCount()); + Assert.assertEquals(1, listener.getWorkCompletedCallCount()); + Assert.assertEquals(0, listener.getWorkExceptions().size()); + } + + /** + * Tests running a single job that fails on the ThreadPoolWorkManager + */ + @Test + public void testSingleFailingJob() { + // Create the work and register it + FailingWork fail = new FailingWork(); + TestWorkListener listener = new TestWorkListener(); + workManager.schedule(fail, listener); + + // Wait for the 1 job to complete + waitForWorkToComplete(listener, 1); + + // Test that the job completed successfully. + Assert.assertEquals(1, listener.getWorkAcceptedCallCount()); + Assert.assertEquals(0, listener.getWorkRejectedCallCount()); + Assert.assertEquals(1, listener.getWorkStartedCallCount()); + Assert.assertEquals(1, listener.getWorkCompletedCallCount()); + Assert.assertEquals(1, listener.getWorkExceptions().size()); + } + + /** + * Tests running a mixture of fast and slow jobs on the ThreadPoolWorkManager + */ + @Test + public void testMultipleJobs() { + // Create the work and register it + TimeDelayWork fast1 = new TimeDelayWork(50); + TimeDelayWork fast2 = new TimeDelayWork(100); + TimeDelayWork fast3 = new TimeDelayWork(200); + TimeDelayWork slow1= new TimeDelayWork(2000); + TimeDelayWork slow2 = new TimeDelayWork(2000); + TestWorkListener listener = new TestWorkListener(); + workManager.schedule(fast1, listener); + workManager.schedule(fast2, listener); + workManager.schedule(fast3, listener); + workManager.schedule(slow1, listener); + workManager.schedule(slow2, listener); + + // Wait for the 5 jobs to complete + waitForWorkToComplete(listener, 5); + + // Test that the job completed successfully. + Assert.assertEquals(5, listener.getWorkAcceptedCallCount()); + Assert.assertEquals(0, listener.getWorkRejectedCallCount()); + Assert.assertEquals(5, listener.getWorkStartedCallCount()); + Assert.assertEquals(5, listener.getWorkCompletedCallCount()); + Assert.assertEquals(0, listener.getWorkExceptions().size()); + } + + /** + * Tests running a mixture of fast and slow jobs some of which fail on the + * ThreadPoolWorkManager + */ + @Test + public void testMultipleJobsSomeFail() { + // Create the work and register it + TimeDelayWork fast1 = new TimeDelayWork(50); + TimeDelayWork fast2 = new TimeDelayWork(100); + TimeDelayWork fast3 = new TimeDelayWork(200); + TimeDelayWork slow1= new TimeDelayWork(2000); + TimeDelayWork slow2 = new TimeDelayWork(2000); + FailingWork fail1 = new FailingWork(); + FailingWork fail2 = new FailingWork(); + TestWorkListener listener = new TestWorkListener(); + workManager.schedule(fast1, listener); + workManager.schedule(fast2, listener); + workManager.schedule(fail1, listener); + workManager.schedule(fast3, listener); + workManager.schedule(slow1, listener); + workManager.schedule(fail2, listener); + workManager.schedule(slow2, listener); + + // Wait for the 7 jobs to complete + waitForWorkToComplete(listener, 7); + + // Test that the job completed successfully. + Assert.assertEquals(7, listener.getWorkAcceptedCallCount()); + Assert.assertEquals(0, listener.getWorkRejectedCallCount()); + Assert.assertEquals(7, listener.getWorkStartedCallCount()); + Assert.assertEquals(7, listener.getWorkCompletedCallCount()); + Assert.assertEquals(2, listener.getWorkExceptions().size()); + } + + /** + * Tests creating a ThreadPoolWorkManager with invalid pool sizes of -10 to 0 + * inclusive + */ + @Test + public void testThreadPoolWorkManagerLessThan1Size() { + for (int i = 0; i >= -10; i--) { + new ThreadPoolWorkManager(i); + } + } + + /** + * Tests running a single job that has no listener + */ + @Test + public void testSingleFastJobWithNoListener() { + // Create the work and register it + TimeDelayWork fast = new TimeDelayWork(10); + workManager.schedule(fast); + + // Wait for the job to complete + long startTime = System.currentTimeMillis(); + while (true) { + int completedCount = fast.getRunCompletedCount(); + if (completedCount == 1) { + break; + } + + if (System.currentTimeMillis() - startTime > WAIT_TIMEOUT) { + Assert.fail("Only " + completedCount + " work items completed before timeout"); + return; + } + + // Lets wait for the job to complete + try { + Thread.sleep(25); + } catch (InterruptedException ex) { + Assert.fail("Unexpected exception: " + ex); + } + } + + // Make sure we have got one completed run + Assert.assertEquals(1, fast.getRunCompletedCount()); + } + + /** + * Waits for the specified number of jobs to complete or the timeout to fire. + * + * @param listener The listener to use to track Work unit completion + * @param completedWorkItemsToWaitFor The number of Work items to complete + */ + private void waitForWorkToComplete(TestWorkListener listener, int completedWorkItemsToWaitFor) { + long startTime = System.currentTimeMillis(); + while (true) { + int completedCount = listener.getWorkCompletedCallCount(); + if (completedCount == completedWorkItemsToWaitFor) { + return; + } + + if (System.currentTimeMillis() - startTime > WAIT_TIMEOUT) { + Assert.fail("Only " + completedCount + " work items completed before timeout"); + return; + } + + // Lets wait for more jobs to complete + try { + Thread.sleep(25); + } catch (InterruptedException ex) { + Assert.fail("Unexpected exception: " + ex); + } + } + } +} diff --git a/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/work/TimeDelayWork.java b/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/work/TimeDelayWork.java new file mode 100644 index 0000000000..6c10057046 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/core/work/TimeDelayWork.java @@ -0,0 +1,86 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.core.work; + +import java.util.concurrent.atomic.AtomicInteger; + +/** + * Simple Work item that will sleep in the run() method for the specified + * period of time + * + * @version $Rev$ $Date$ + */ +public class TimeDelayWork extends Work { + + /** + * Count of completed run() method calls + */ + private AtomicInteger runCompletedCount = new AtomicInteger(); + + /** + * The amount of time to sleep in the Run loop + */ + private final long sleepTime; + + /** + * Constructor + * + * @param sleepTime The amount of time to sleep (in milliseconds) in the run() method + */ + public TimeDelayWork(long sleepTime) { + super(null); + this.sleepTime = sleepTime; + } + + /** + * {@inheritDoc} + */ + public boolean isDaemon() { + return false; + } + + /** + * {@inheritDoc} + */ + public void release() { + } + + /** + * Sleeps for a period of time defined by sleepTime + */ + public void run() { + System.out.println("Starting " + this); + try { + Thread.sleep(sleepTime); + } catch (InterruptedException e) { + e.printStackTrace(); + } + System.out.println("Done " + this); + runCompletedCount.incrementAndGet(); + } + + /** + * Returns the number of completed calls to run() + * + * @return The number of completed calls to run() + */ + public int getRunCompletedCount() { + return runCompletedCount.get(); + } +} diff --git a/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/scope/ScopeTestCase.java b/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/scope/ScopeTestCase.java new file mode 100644 index 0000000000..341d889b7d --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/test/java/org/apache/tuscany/sca/scope/ScopeTestCase.java @@ -0,0 +1,61 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.scope; + +import junit.framework.TestCase; + +import org.apache.tuscany.sca.core.scope.Scope; + +/** + * @version $Rev$ $Date$ + */ +public class ScopeTestCase extends TestCase { + + public void testEquals() throws Exception { + Scope scope = new Scope("COMPOSITE"); + assertTrue(scope.equals(Scope.COMPOSITE)); + } + + public void testEqualsNew() throws Exception { + Scope foo = new Scope("foo"); + Scope foo2 = new Scope("FOO"); + assertTrue(foo.equals(foo2)); + } + + public void testNotEquals() throws Exception { + Scope foo = new Scope("BAR"); + Scope foo2 = new Scope("FOO"); + assertFalse(foo.equals(foo2)); + } + + public void testNotEqualsDifferent() throws Exception { + Scope foo = new Scope("FOO"); + assertFalse(foo.equals(new Bar("FOO"))); + } + + public class Bar { + String scope; + + public Bar(String scope) { + this.scope = scope; + } + } + + +} diff --git a/branches/sca-java-1.5.1/modules/core/src/test/resources/META-INF/services/org.apache.tuscany.sca.invocation.PhaseTest b/branches/sca-java-1.5.1/modules/core/src/test/resources/META-INF/services/org.apache.tuscany.sca.invocation.PhaseTest new file mode 100644 index 0000000000..ad23df3761 --- /dev/null +++ b/branches/sca-java-1.5.1/modules/core/src/test/resources/META-INF/services/org.apache.tuscany.sca.invocation.PhaseTest @@ -0,0 +1,24 @@ +# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+name=implementation.last, stage=implementation, after=*
+name=reference.first, stage=reference, before=*
+name=reference.transaction, stage=reference, after=reference.interface
+name=reference.binding.header, stage=reference.binding, after=reference.binding.transport
+name=service.binding.header, stage=service.binding, after=service.binding.transport
+name=service.transaction, stage=service, after=service.binding, before=component.service
+name=implementation.transaction, stage=implementation, before=implementation.policy
|