summaryrefslogtreecommitdiffstats
path: root/sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java
diff options
context:
space:
mode:
Diffstat (limited to 'sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java')
-rw-r--r--sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/Axis2BindingInvoker.java247
-rw-r--r--sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/Axis2BindingProviderFactory.java86
-rw-r--r--sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/Axis2OneWayBindingInvoker.java69
-rw-r--r--sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/Axis2ReferenceBindingProvider.java129
-rw-r--r--sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/Axis2ServiceBindingProvider.java147
-rw-r--r--sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/Axis2ServiceClient.java661
-rw-r--r--sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/Axis2ServiceInMessageReceiver.java75
-rw-r--r--sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/Axis2ServiceInOutSyncMessageReceiver.java99
-rw-r--r--sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/Axis2ServiceProvider.java700
-rw-r--r--sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/Axis2ServiceServlet.java294
-rw-r--r--sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/AxisPolicyHelper.java79
-rw-r--r--sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/TuscanyAxisConfigurator.java206
-rw-r--r--sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/TuscanyDispatcher.java105
-rw-r--r--sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/TuscanyListingAgent.java235
-rw-r--r--sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/WSBindingDefinitionsProvider.java66
15 files changed, 3198 insertions, 0 deletions
diff --git a/sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/Axis2BindingInvoker.java b/sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/Axis2BindingInvoker.java
new file mode 100644
index 0000000000..b01707d93e
--- /dev/null
+++ b/sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/Axis2BindingInvoker.java
@@ -0,0 +1,247 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tuscany.sca.binding.ws.axis2;
+
+import java.security.AccessController;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
+import java.util.List;
+
+import javax.xml.namespace.QName;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.soap.SOAPBody;
+import org.apache.axiom.soap.SOAPEnvelope;
+import org.apache.axiom.soap.SOAPFactory;
+import org.apache.axiom.soap.SOAPHeader;
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.addressing.AddressingConstants;
+import org.apache.axis2.addressing.EndpointReference;
+import org.apache.axis2.addressing.EndpointReferenceHelper;
+import org.apache.axis2.client.OperationClient;
+import org.apache.axis2.client.Options;
+import org.apache.axis2.context.MessageContext;
+import org.apache.axis2.transport.http.HTTPConstants;
+import org.apache.axis2.wsdl.WSDLConstants;
+import org.apache.tuscany.sca.assembly.xml.Constants;
+import org.apache.tuscany.sca.interfacedef.util.FaultException;
+import org.apache.tuscany.sca.invocation.DataExchangeSemantics;
+import org.apache.tuscany.sca.invocation.Invoker;
+import org.apache.tuscany.sca.invocation.Message;
+import org.apache.tuscany.sca.policy.util.PolicyHandler;
+import org.apache.tuscany.sca.runtime.ReferenceParameters;
+
+/**
+ * Axis2BindingInvoker uses an Axis2 OperationClient to invoke a remote web service
+ *
+ * @version $Rev$ $Date$
+ */
+public class Axis2BindingInvoker implements Invoker, DataExchangeSemantics {
+
+ private Axis2ServiceClient serviceClient;
+ private QName wsdlOperationName;
+ private Options options;
+ private SOAPFactory soapFactory;
+
+ public static final QName QNAME_WSA_FROM =
+ new QName(AddressingConstants.Final.WSA_NAMESPACE, AddressingConstants.WSA_FROM,
+ AddressingConstants.WSA_DEFAULT_PREFIX);
+
+ public static final String TUSCANY_PREFIX = "tuscany";
+ public static final QName CALLBACK_ID_REFPARM_QN =
+ new QName(Constants.SCA10_TUSCANY_NS, "CallbackID", TUSCANY_PREFIX);
+ public static final QName CONVERSATION_ID_REFPARM_QN =
+ new QName(Constants.SCA10_TUSCANY_NS, "ConversationID", TUSCANY_PREFIX);
+
+ private List<PolicyHandler> policyHandlerList = null;
+
+ public Axis2BindingInvoker(Axis2ServiceClient serviceClient,
+ QName wsdlOperationName,
+ Options options,
+ SOAPFactory soapFactory,
+ List<PolicyHandler> policyHandlerList) {
+ this.serviceClient = serviceClient;
+ this.wsdlOperationName = wsdlOperationName;
+ this.options = options;
+ this.soapFactory = soapFactory;
+ this.policyHandlerList = policyHandlerList;
+ }
+
+ private static final QName EXCEPTION = new QName("", "Exception");
+
+ public Message invoke(Message msg) {
+ try {
+ for ( PolicyHandler policyHandler : policyHandlerList ) {
+ policyHandler.beforeInvoke(msg);
+ }
+
+ Object resp = invokeTarget(msg);
+
+ for ( PolicyHandler policyHandler : policyHandlerList ) {
+ policyHandler.afterInvoke(msg);
+ }
+ msg.setBody(resp);
+ } catch (AxisFault e) {
+ if (e.getDetail() != null ) {
+ FaultException f = new FaultException(e.getMessage(), e.getDetail(), e);
+ f.setFaultName(e.getDetail().getQName());
+ msg.setFaultBody(f);
+ } else {
+ msg.setFaultBody(e);
+ }
+ } catch (Throwable e) {
+ msg.setFaultBody(e);
+ }
+
+ return msg;
+ }
+
+ protected Object invokeTarget(Message msg) throws AxisFault {
+ final OperationClient operationClient = createOperationClient(msg);
+
+ // ensure connections are tracked so that they can be closed by the reference binding
+ MessageContext requestMC = operationClient.getMessageContext(WSDLConstants.MESSAGE_LABEL_OUT_VALUE);
+ requestMC.getOptions().setProperty(HTTPConstants.REUSE_HTTP_CLIENT, Boolean.TRUE);
+ requestMC.getOptions().setTimeOutInMilliSeconds(240000L);
+
+ // Allow privileged access to read properties. Requires PropertiesPermission read in
+ // security policy.
+ try {
+ AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
+ public Object run() throws AxisFault {
+ operationClient.execute(true);
+ return null;
+ }
+ });
+ } catch (PrivilegedActionException e) {
+ operationClient.complete(requestMC);
+ throw (AxisFault)e.getException();
+ }
+
+ MessageContext responseMC = operationClient.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
+
+ OMElement response = responseMC.getEnvelope().getBody().getFirstElement();
+
+ // FIXME: [rfeng] We have to pay performance penalty to build the complete OM as the operationClient.complete() will
+ // release the underlying HTTP connection.
+ // Force the response to be populated, see https://issues.apache.org/jira/browse/TUSCANY-1541
+ if (response != null) {
+ response.build();
+ }
+
+ operationClient.complete(requestMC);
+
+ return response;
+ }
+
+ @SuppressWarnings("deprecation")
+ protected OperationClient createOperationClient(Message msg) throws AxisFault {
+ SOAPEnvelope env = soapFactory.getDefaultEnvelope();
+ Object[] args = (Object[])msg.getBody();
+ if (args != null && args.length > 0) {
+ SOAPBody body = env.getBody();
+ for (Object bc : args) {
+ if (bc instanceof OMElement) {
+ body.addChild((OMElement)bc);
+ } else {
+ throw new IllegalArgumentException(
+ "Can't handle mixed payloads between OMElements and other types.");
+ }
+ }
+ }
+ final MessageContext requestMC = new MessageContext();
+ requestMC.setEnvelope(env);
+
+ // Axis2 operationClients can not be shared so create a new one for each request
+ final OperationClient operationClient = serviceClient.getServiceClient().createClient(wsdlOperationName);
+ operationClient.setOptions(options);
+
+ ReferenceParameters parameters = msg.getFrom().getReferenceParameters();
+
+ // set callback endpoint and callback ID for WS-Addressing header
+ EndpointReference fromEPR = null;
+ org.apache.tuscany.sca.runtime.EndpointReference callbackEPR = parameters.getCallbackReference();
+ if (callbackEPR != null) {
+ fromEPR = new EndpointReference(callbackEPR.getBinding().getURI());
+ }
+ Object callbackID = parameters.getCallbackID();
+ if (callbackID != null) {
+ if (fromEPR == null) {
+ fromEPR = new EndpointReference(AddressingConstants.Final.WSA_ANONYMOUS_URL);
+ }
+ //FIXME: serialize callback ID to XML in case it is not a string
+ fromEPR.addReferenceParameter(CALLBACK_ID_REFPARM_QN, callbackID.toString());
+ }
+
+ // set conversation ID for WS-Addressing header
+ Object conversationId = parameters.getConversationID();
+ if (conversationId != null) {
+ if (fromEPR == null) {
+ fromEPR = new EndpointReference(AddressingConstants.Final.WSA_ANONYMOUS_URL);
+ }
+ //FIXME: serialize conversation ID to XML in case it is not a string
+ fromEPR.addReferenceParameter(CONVERSATION_ID_REFPARM_QN, conversationId.toString());
+ }
+
+ // add WS-Addressing header
+ //FIXME: is there any way to use the Axis2 addressing support for this?
+ if (fromEPR != null) {
+ SOAPEnvelope sev = requestMC.getEnvelope();
+ SOAPHeader sh = sev.getHeader();
+ OMElement epr =
+ EndpointReferenceHelper.toOM(sev.getOMFactory(),
+ fromEPR,
+ QNAME_WSA_FROM,
+ AddressingConstants.Final.WSA_NAMESPACE);
+ sh.addChild(epr);
+ requestMC.setFrom(fromEPR);
+ }
+
+ // if target endpoint was not specified when this invoker was created,
+ // use dynamically specified target endpoint passed in on this call
+ if (options.getTo() == null) {
+ org.apache.tuscany.sca.runtime.EndpointReference ep = msg.getTo();
+ if (ep != null) {
+ requestMC.setTo(new EndpointReference(ep.getURI()));
+ } else {
+ throw new RuntimeException("Unable to determine destination endpoint");
+ }
+ } else {
+ requestMC.setTo(new EndpointReference(options.getTo().getAddress()));
+ }
+
+ // Allow privileged access to read properties. Requires PropertiesPermission read in
+ // security policy.
+ try {
+ AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
+ public Object run() throws AxisFault {
+ operationClient.addMessageContext(requestMC);
+ return null;
+ }
+ });
+ } catch (PrivilegedActionException e) {
+ throw (AxisFault)e.getException();
+ }
+ return operationClient;
+ }
+
+ public boolean allowsPassByReference() {
+ return true;
+ }
+}
diff --git a/sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/Axis2BindingProviderFactory.java b/sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/Axis2BindingProviderFactory.java
new file mode 100644
index 0000000000..83df3481ce
--- /dev/null
+++ b/sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/Axis2BindingProviderFactory.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.binding.ws.axis2;
+
+import java.util.List;
+import java.util.Map;
+
+import org.apache.tuscany.sca.binding.ws.WebServiceBinding;
+import org.apache.tuscany.sca.contribution.ModelFactoryExtensionPoint;
+import org.apache.tuscany.sca.core.ExtensionPointRegistry;
+import org.apache.tuscany.sca.databinding.DataBindingExtensionPoint;
+import org.apache.tuscany.sca.host.http.ServletHost;
+import org.apache.tuscany.sca.host.http.ServletHostExtensionPoint;
+import org.apache.tuscany.sca.invocation.MessageFactory;
+import org.apache.tuscany.sca.policy.util.PolicyHandlerDefinitionsLoader;
+import org.apache.tuscany.sca.policy.util.PolicyHandlerTuple;
+import org.apache.tuscany.sca.provider.BindingProviderFactory;
+import org.apache.tuscany.sca.provider.ReferenceBindingProvider;
+import org.apache.tuscany.sca.provider.ServiceBindingProvider;
+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;
+
+/**
+ * Axis2BindingProviderFactory
+ *
+ * @version $Rev$ $Date$
+ */
+
+public class Axis2BindingProviderFactory implements BindingProviderFactory<WebServiceBinding> {
+
+ private ModelFactoryExtensionPoint modelFactories;
+ private ServletHost servletHost;
+ private Map<ClassLoader, List<PolicyHandlerTuple>> policyHandlerClassnames = null;
+ private DataBindingExtensionPoint dataBindings;
+
+ public Axis2BindingProviderFactory(ExtensionPointRegistry extensionPoints) {
+ ServletHostExtensionPoint servletHosts = extensionPoints.getExtensionPoint(ServletHostExtensionPoint.class);
+ List<ServletHost> hosts = servletHosts.getServletHosts();
+ if (hosts.isEmpty()) {
+ throw new ServiceRuntimeException("No Servlet host is avaible for HTTP web services");
+ } else {
+ this.servletHost = hosts.get(0);
+ }
+ modelFactories = extensionPoints.getExtensionPoint(ModelFactoryExtensionPoint.class);
+ policyHandlerClassnames = PolicyHandlerDefinitionsLoader.loadPolicyHandlerClassnames();
+ dataBindings = extensionPoints.getExtensionPoint(DataBindingExtensionPoint.class);
+ }
+
+ public ReferenceBindingProvider createReferenceBindingProvider(RuntimeComponent component,
+ RuntimeComponentReference reference,
+ WebServiceBinding binding) {
+ return new Axis2ReferenceBindingProvider(component, reference, binding,
+ servletHost, modelFactories,
+ policyHandlerClassnames, dataBindings);
+ }
+
+ public ServiceBindingProvider createServiceBindingProvider(RuntimeComponent component,
+ RuntimeComponentService service,
+ WebServiceBinding binding) {
+ return new Axis2ServiceBindingProvider(component, service, binding,
+ servletHost, modelFactories,
+ policyHandlerClassnames, dataBindings);
+ }
+
+ public Class<WebServiceBinding> getModelType() {
+ return WebServiceBinding.class;
+ }
+}
diff --git a/sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/Axis2OneWayBindingInvoker.java b/sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/Axis2OneWayBindingInvoker.java
new file mode 100644
index 0000000000..7ea5d65ce9
--- /dev/null
+++ b/sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/Axis2OneWayBindingInvoker.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.binding.ws.axis2;
+
+import java.util.List;
+
+import javax.xml.namespace.QName;
+
+import org.apache.axiom.soap.SOAPFactory;
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.client.OperationClient;
+import org.apache.axis2.client.Options;
+import org.apache.axis2.context.MessageContext;
+import org.apache.axis2.transport.http.HTTPConstants;
+import org.apache.axis2.wsdl.WSDLConstants;
+import org.apache.tuscany.sca.invocation.Message;
+import org.apache.tuscany.sca.policy.util.PolicyHandler;
+
+/**
+ * Axis2OneWayBindingInvoker uses an Axis2 OperationClient to invoke a OneWay remote web service.
+ *
+ * @version $Rev$ $Date$
+ */
+public class Axis2OneWayBindingInvoker extends Axis2BindingInvoker {
+
+ public Axis2OneWayBindingInvoker(Axis2ServiceClient serviceClient,
+ QName wsdlOperationName,
+ Options options,
+ SOAPFactory soapFactory,
+ List<PolicyHandler> policyHandlerList) {
+
+ super(serviceClient, wsdlOperationName, options, soapFactory, policyHandlerList);
+ }
+
+ @Override
+ protected Object invokeTarget(Message msg) throws AxisFault {
+ OperationClient operationClient = createOperationClient(msg);
+
+ // ensure connections are tracked so that they can be closed by the reference binding
+ MessageContext requestMC = operationClient.getMessageContext(WSDLConstants.MESSAGE_LABEL_OUT_VALUE);
+ //requestMC.getOptions().setProperty(HTTPConstants.REUSE_HTTP_CLIENT, Boolean.TRUE);
+ Options opt = requestMC.getOptions();
+ opt.setProperty(HTTPConstants.REUSE_HTTP_CLIENT, Boolean.TRUE);
+ opt.setUseSeparateListener(true);
+ opt.setProperty(HTTPConstants.AUTO_RELEASE_CONNECTION,Boolean.TRUE);
+
+ operationClient.execute(false);
+
+ // REVIEW it seems ok to return null
+ return null;
+ }
+
+}
diff --git a/sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/Axis2ReferenceBindingProvider.java b/sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/Axis2ReferenceBindingProvider.java
new file mode 100644
index 0000000000..6ce40b5eca
--- /dev/null
+++ b/sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/Axis2ReferenceBindingProvider.java
@@ -0,0 +1,129 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tuscany.sca.binding.ws.axis2;
+
+import java.util.List;
+import java.util.Map;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.tuscany.sca.binding.ws.WebServiceBinding;
+import org.apache.tuscany.sca.contribution.ModelFactoryExtensionPoint;
+import org.apache.tuscany.sca.contribution.resolver.ModelResolver;
+import org.apache.tuscany.sca.contribution.resolver.ResolverExtension;
+import org.apache.tuscany.sca.host.http.ServletHost;
+import org.apache.tuscany.sca.databinding.DataBindingExtensionPoint;
+import org.apache.tuscany.sca.interfacedef.InterfaceContract;
+import org.apache.tuscany.sca.interfacedef.Operation;
+import org.apache.tuscany.sca.interfacedef.java.JavaInterfaceContract;
+import org.apache.tuscany.sca.interfacedef.wsdl.WSDLFactory;
+import org.apache.tuscany.sca.interfacedef.wsdl.java2wsdl.Java2WSDLHelper;
+import org.apache.tuscany.sca.invocation.Invoker;
+import org.apache.tuscany.sca.invocation.MessageFactory;
+import org.apache.tuscany.sca.policy.util.PolicyHandlerTuple;
+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.xsd.XSDFactory;
+
+public class Axis2ReferenceBindingProvider implements ReferenceBindingProvider {
+
+ private WebServiceBinding wsBinding;
+ private Axis2ServiceClient axisClient;
+
+ public Axis2ReferenceBindingProvider(RuntimeComponent component,
+ RuntimeComponentReference reference,
+ WebServiceBinding wsBinding,
+ ServletHost servletHost,
+ ModelFactoryExtensionPoint modelFactories,
+ Map<ClassLoader, List<PolicyHandlerTuple>> policyHandlerClassnames,
+ DataBindingExtensionPoint dataBindings) {
+
+ MessageFactory messageFactory = modelFactories.getFactory(MessageFactory.class);
+ WSDLFactory wsdlFactory = modelFactories.getFactory(WSDLFactory.class);
+ XSDFactory xsdFactory = modelFactories.getFactory(XSDFactory.class);
+ this.wsBinding = wsBinding;
+
+ InterfaceContract contract = wsBinding.getBindingInterfaceContract();
+ if (contract == null) {
+ contract = reference.getInterfaceContract().makeUnidirectional(false);
+ if (contract instanceof JavaInterfaceContract) {
+ ModelResolver resolver = component instanceof ResolverExtension ?
+ ((ResolverExtension)component).getModelResolver() : null;
+ contract = Java2WSDLHelper.createWSDLInterfaceContract(
+ (JavaInterfaceContract)contract,
+ Axis2ServiceBindingProvider.requiresSOAP12(wsBinding),
+ resolver,
+ dataBindings,
+ wsdlFactory,
+ xsdFactory);
+ }
+ wsBinding.setBindingInterfaceContract(contract);
+ }
+
+ // TODO - fix up the conversational flag and operation sequences in case the contract has come from WSDL
+ // as we don't yet support requires="conversational" or sca:endConversation annotations
+ // in WSDL interface descriptions (see section 1.5.4 of the Assembly Specification V1.0)
+ if ( reference.getInterfaceContract().getInterface() != null && contract.getInterface() != null) {
+ contract.getInterface().setConversational(reference.getInterfaceContract().getInterface().isConversational());
+
+ for (Operation operation : contract.getInterface().getOperations()){
+ Operation referenceOperation = null;
+
+ for (Operation tmpOp : reference.getInterfaceContract().getInterface().getOperations()){
+ if ( operation.getName().equals(tmpOp.getName())) {
+ referenceOperation = tmpOp;
+ break;
+ }
+ }
+
+ if (referenceOperation != null ){
+ operation.setConversationSequence(referenceOperation.getConversationSequence());
+ }
+ }
+ }
+
+ // Set to use the Axiom data binding
+ if (contract.getInterface() != null) {
+ contract.getInterface().resetDataBinding(OMElement.class.getName());
+ }
+
+ axisClient = new Axis2ServiceClient(component, reference, wsBinding, servletHost, messageFactory, policyHandlerClassnames);
+ }
+
+ public void start() {
+ axisClient.start();
+ }
+
+ public void stop() {
+ axisClient.stop();
+ }
+
+ public InterfaceContract getBindingInterfaceContract() {
+ return wsBinding.getBindingInterfaceContract();
+ }
+
+ public boolean supportsOneWayInvocation() {
+ return true;
+ }
+
+ public Invoker createInvoker(Operation operation) {
+ return axisClient.createInvoker(operation);
+ }
+
+}
diff --git a/sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/Axis2ServiceBindingProvider.java b/sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/Axis2ServiceBindingProvider.java
new file mode 100644
index 0000000000..9afd1283c1
--- /dev/null
+++ b/sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/Axis2ServiceBindingProvider.java
@@ -0,0 +1,147 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tuscany.sca.binding.ws.axis2;
+
+import java.util.List;
+import java.util.Map;
+
+import javax.xml.namespace.QName;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.tuscany.sca.binding.ws.WebServiceBinding;
+import org.apache.tuscany.sca.contribution.ModelFactoryExtensionPoint;
+import org.apache.tuscany.sca.contribution.resolver.ModelResolver;
+import org.apache.tuscany.sca.contribution.resolver.ResolverExtension;
+import org.apache.tuscany.sca.host.http.ServletHost;
+import org.apache.tuscany.sca.databinding.DataBindingExtensionPoint;
+import org.apache.tuscany.sca.interfacedef.InterfaceContract;
+import org.apache.tuscany.sca.interfacedef.Operation;
+import org.apache.tuscany.sca.interfacedef.java.JavaInterfaceContract;
+import org.apache.tuscany.sca.interfacedef.wsdl.WSDLFactory;
+import org.apache.tuscany.sca.interfacedef.wsdl.java2wsdl.Java2WSDLHelper;
+import org.apache.tuscany.sca.invocation.MessageFactory;
+import org.apache.tuscany.sca.policy.Intent;
+import org.apache.tuscany.sca.policy.IntentAttachPoint;
+import org.apache.tuscany.sca.policy.util.PolicyHandlerTuple;
+import org.apache.tuscany.sca.provider.ServiceBindingProvider;
+import org.apache.tuscany.sca.runtime.RuntimeComponent;
+import org.apache.tuscany.sca.runtime.RuntimeComponentService;
+import org.apache.tuscany.sca.xsd.XSDFactory;
+
+public class Axis2ServiceBindingProvider implements ServiceBindingProvider {
+
+ private WebServiceBinding wsBinding;
+ private Axis2ServiceProvider axisProvider;
+
+ public Axis2ServiceBindingProvider(RuntimeComponent component,
+ RuntimeComponentService service,
+ WebServiceBinding wsBinding,
+ ServletHost servletHost,
+ ModelFactoryExtensionPoint modelFactories,
+ Map<ClassLoader, List<PolicyHandlerTuple>> policyHandlerClassnames,
+ DataBindingExtensionPoint dataBindings) {
+
+ MessageFactory messageFactory = modelFactories.getFactory(MessageFactory.class);
+ WSDLFactory wsdlFactory = modelFactories.getFactory(WSDLFactory.class);
+ XSDFactory xsdFactory = modelFactories.getFactory(XSDFactory.class);
+ this.wsBinding = wsBinding;
+
+ InterfaceContract contract = wsBinding.getBindingInterfaceContract();
+ if (contract == null) {
+ contract = service.getInterfaceContract().makeUnidirectional(false);
+ if (contract instanceof JavaInterfaceContract) {
+ ModelResolver resolver = component instanceof ResolverExtension ?
+ ((ResolverExtension)component).getModelResolver() : null;
+ contract = Java2WSDLHelper.createWSDLInterfaceContract(
+ (JavaInterfaceContract)contract,
+ requiresSOAP12(wsBinding),
+ resolver,
+ dataBindings,
+ wsdlFactory,
+ xsdFactory);
+ } else {
+ try {
+ //TUSCANY-2316 Cloning the Interface Contract to avoid overriding data biding information
+ contract = (InterfaceContract) contract.clone();
+ } catch (Exception e) {
+ //ignore
+ }
+ }
+ wsBinding.setBindingInterfaceContract(contract);
+ }
+
+ // TODO - fix up the conversational flag and operation sequences in case the contract has come from WSDL
+ // as we don't yet support requires="conversational" or sca:endConversation annotations
+ // in WSDL interface descriptions (see section 1.5.4 of the Assembly Specification V1.0)
+ if (service.getInterfaceContract().getInterface() != null ) {
+ contract.getInterface().setConversational(service.getInterfaceContract().getInterface().isConversational());
+
+ for (Operation operation : contract.getInterface().getOperations()){
+ Operation serviceOperation = null;
+
+ for (Operation tmpOp : service.getInterfaceContract().getInterface().getOperations()){
+ if ( operation.getName().equals(tmpOp.getName())) {
+ serviceOperation = tmpOp;
+ break;
+ }
+ }
+
+ if (serviceOperation != null ){
+ operation.setConversationSequence(serviceOperation.getConversationSequence());
+ }
+ }
+ }
+
+
+ // Set to use the Axiom data binding
+ contract.getInterface().resetDataBinding(OMElement.class.getName());
+
+ axisProvider = new Axis2ServiceProvider(component, service, wsBinding, servletHost, messageFactory, policyHandlerClassnames);
+ }
+
+ public void start() {
+ axisProvider.start();
+ }
+
+ public void stop() {
+ axisProvider.stop();
+ }
+
+ public InterfaceContract getBindingInterfaceContract() {
+ return wsBinding.getBindingInterfaceContract();
+ }
+
+ public boolean supportsOneWayInvocation() {
+ return true;
+ }
+
+ private static final QName SOAP12_INTENT = new QName("http://www.osoa.org/xmlns/sca/1.0", "soap.1_2");
+
+ protected static boolean requiresSOAP12(WebServiceBinding wsBinding) {
+ if (wsBinding instanceof IntentAttachPoint) {
+ List<Intent> intents = ((IntentAttachPoint)wsBinding).getRequiredIntents();
+ for (Intent intent : intents) {
+ if (SOAP12_INTENT.equals(intent.getName())) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+}
diff --git a/sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/Axis2ServiceClient.java b/sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/Axis2ServiceClient.java
new file mode 100644
index 0000000000..fbdeb6dd13
--- /dev/null
+++ b/sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/Axis2ServiceClient.java
@@ -0,0 +1,661 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tuscany.sca.binding.ws.axis2;
+
+import static org.apache.tuscany.sca.binding.ws.axis2.AxisPolicyHelper.SOAP12_INTENT;
+import static org.apache.tuscany.sca.binding.ws.axis2.AxisPolicyHelper.isIntentRequired;
+
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+import javax.wsdl.Binding;
+import javax.wsdl.BindingOperation;
+import javax.wsdl.Definition;
+import javax.wsdl.Import;
+import javax.wsdl.Port;
+import javax.wsdl.PortType;
+import javax.wsdl.Service;
+import javax.wsdl.WSDLException;
+import javax.wsdl.extensions.ExtensibilityElement;
+import javax.wsdl.extensions.soap.SOAPAddress;
+import javax.wsdl.extensions.soap.SOAPBinding;
+import javax.wsdl.extensions.soap.SOAPOperation;
+import javax.wsdl.extensions.soap12.SOAP12Address;
+import javax.wsdl.extensions.soap12.SOAP12Binding;
+import javax.wsdl.factory.WSDLFactory;
+import javax.xml.namespace.QName;
+import javax.xml.stream.FactoryConfigurationError;
+import javax.xml.stream.XMLInputFactory;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamReader;
+import javax.xml.transform.dom.DOMSource;
+
+import org.apache.axiom.om.OMAbstractFactory;
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.impl.builder.StAXOMBuilder;
+import org.apache.axiom.soap.SOAPFactory;
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.addressing.EndpointReference;
+import org.apache.axis2.addressing.EndpointReferenceHelper;
+import org.apache.axis2.client.Options;
+import org.apache.axis2.client.ServiceClient;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.description.AxisEndpoint;
+import org.apache.axis2.description.AxisService;
+import org.apache.axis2.description.Parameter;
+import org.apache.axis2.description.WSDL11ToAxisServiceBuilder;
+import org.apache.axis2.description.WSDL2Constants;
+import org.apache.axis2.transport.http.HTTPConstants;
+import org.apache.axis2.util.threadpool.ThreadPool;
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
+import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
+import org.apache.tuscany.sca.assembly.AbstractContract;
+import org.apache.tuscany.sca.binding.ws.WebServiceBinding;
+import org.apache.tuscany.sca.host.http.ServletHost;
+import org.apache.tuscany.sca.interfacedef.InterfaceContract;
+import org.apache.tuscany.sca.interfacedef.Operation;
+import org.apache.tuscany.sca.interfacedef.wsdl.WSDLDefinition;
+import org.apache.tuscany.sca.interfacedef.wsdl.WSDLInterface;
+import org.apache.tuscany.sca.interfacedef.wsdl.interface2wsdl.WSDLDefinitionGenerator;
+import org.apache.tuscany.sca.invocation.Invoker;
+import org.apache.tuscany.sca.invocation.MessageFactory;
+import org.apache.tuscany.sca.policy.PolicySet;
+import org.apache.tuscany.sca.policy.PolicySetAttachPoint;
+import org.apache.tuscany.sca.policy.security.ws.Axis2ConfigParamPolicy;
+import org.apache.tuscany.sca.policy.util.PolicyHandler;
+import org.apache.tuscany.sca.policy.util.PolicyHandlerTuple;
+import org.apache.tuscany.sca.policy.util.PolicyHandlerUtils;
+import org.apache.tuscany.sca.runtime.RuntimeComponent;
+import org.apache.tuscany.sca.xsd.xml.XMLDocumentHelper;
+import org.apache.ws.commons.schema.resolver.URIResolver;
+import org.osoa.sca.ServiceRuntimeException;
+
+public class Axis2ServiceClient {
+
+ private RuntimeComponent component;
+ private AbstractContract contract;
+ private WebServiceBinding wsBinding;
+ private ServiceClient serviceClient;
+ Map<ClassLoader, List<PolicyHandlerTuple>> policyHandlerClassnames = null;
+ private List<PolicyHandler> policyHandlerList = new ArrayList<PolicyHandler>();
+
+ public Axis2ServiceClient(RuntimeComponent component,
+ AbstractContract contract,
+ WebServiceBinding wsBinding,
+ ServletHost servletHost,
+ MessageFactory messageFactory,
+ Map<ClassLoader, List<PolicyHandlerTuple>> policyHandlerClassnames) {
+
+ this.component = component;
+ this.contract = contract;
+ this.wsBinding = wsBinding;
+ this.policyHandlerClassnames = policyHandlerClassnames;
+ }
+
+ protected void start() {
+ if (serviceClient == null) {
+ this.serviceClient = createServiceClient();
+ }
+ }
+
+ public ServiceClient getServiceClient() {
+ return serviceClient;
+ }
+
+ protected void configurePolicy(ConfigurationContext context, PolicySet ps) throws AxisFault {
+ if (ps == null) {
+ return;
+ }
+ for (Object policy : ps.getPolicies()) {
+ if (policy instanceof Axis2ConfigParamPolicy) {
+ Axis2ConfigParamPolicy axis2ConfigParamPolicy = (Axis2ConfigParamPolicy)policy;
+ for (Map.Entry<String, OMElement> param : axis2ConfigParamPolicy.getParamElements().entrySet()) {
+ Parameter configParam = new Parameter(param.getKey(), param.getValue().getFirstElement());
+ configParam.setParameterElement(param.getValue());
+ context.getAxisConfiguration().addParameter(configParam);
+ }
+ }
+ }
+ }
+
+ /**
+ * Create an Axis2 ServiceClient
+ */
+ protected ServiceClient createServiceClient() {
+ try {
+ final boolean isRampartRequired = AxisPolicyHelper.isRampartRequired(wsBinding);
+ ConfigurationContext configContext;
+
+ try {
+ // TuscanyAxisConfigurator tuscanyAxisConfigurator = new TuscanyAxisConfigurator();
+ // Allow privileged access to read properties. Requires PropertyPermission read in
+ // security policy.
+ TuscanyAxisConfigurator tuscanyAxisConfigurator =
+ AccessController.doPrivileged(new PrivilegedExceptionAction<TuscanyAxisConfigurator>() {
+ public TuscanyAxisConfigurator run() throws AxisFault {
+ return new TuscanyAxisConfigurator(isRampartRequired);
+ }
+ });
+ configContext = tuscanyAxisConfigurator.getConfigurationContext();
+ // deployRampartModule();
+ // configureSecurity();
+ } catch (PrivilegedActionException e) {
+ throw new ServiceRuntimeException(e.getException());
+ }
+
+ createPolicyHandlers();
+ setupPolicyHandlers(policyHandlerList, configContext);
+
+ configureWSDLDefinition(wsBinding, component, contract);
+ // The service, port and WSDL definition can be set by the above call
+ Definition wsdlDefinition = wsBinding.getWSDLDefinition().getDefinition();
+ QName serviceQName =
+ wsBinding.getService() != null ? wsBinding.getService().getQName() : wsBinding.getServiceName();
+ String portName = wsBinding.getPort() != null ? wsBinding.getPort().getName() : wsBinding.getPortName();
+ AxisService axisService =
+ createClientSideAxisService(wsdlDefinition, serviceQName, portName, new Options());
+
+ HttpClient httpClient = (HttpClient)configContext.getProperty(HTTPConstants.CACHED_HTTP_CLIENT);
+ if (httpClient == null) {
+ MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
+ HttpConnectionManagerParams connectionManagerParams = new HttpConnectionManagerParams();
+ connectionManagerParams.setDefaultMaxConnectionsPerHost(2);
+ connectionManagerParams.setTcpNoDelay(true);
+ connectionManagerParams.setStaleCheckingEnabled(true);
+ connectionManagerParams.setLinger(0);
+ connectionManager.setParams(connectionManagerParams);
+ httpClient = new HttpClient(connectionManager);
+ configContext.setThreadPool(new ThreadPool(1, 5));
+ configContext.setProperty(HTTPConstants.REUSE_HTTP_CLIENT, Boolean.TRUE);
+ configContext.setProperty(HTTPConstants.CACHED_HTTP_CLIENT, httpClient);
+ }
+
+ return new ServiceClient(configContext, axisService);
+
+ } catch (AxisFault e) {
+ throw new RuntimeException(e); // TODO: better exception
+ } catch (ClassNotFoundException e) {
+ throw new RuntimeException(e);
+ } catch (InstantiationException e) {
+ throw new RuntimeException(e);
+ } catch (IllegalAccessException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * URI resolver implementation for XML schema
+ */
+ public static class URIResolverImpl implements URIResolver {
+ private Definition definition;
+
+ public URIResolverImpl(Definition definition) {
+ this.definition = definition;
+ }
+
+ public org.xml.sax.InputSource resolveEntity(java.lang.String targetNamespace,
+ java.lang.String schemaLocation,
+ java.lang.String baseUri) {
+ try {
+ if (baseUri == null) {
+ baseUri = definition.getDocumentBaseURI();
+ }
+ URL url = new URL(new URL(baseUri), schemaLocation);
+ return XMLDocumentHelper.getInputSource(url);
+ } catch (IOException e) {
+ return null;
+ }
+ }
+ }
+
+ /**
+ * Workaround for https://issues.apache.org/jira/browse/AXIS2-3205
+ * @param definition
+ * @param serviceName
+ * @return
+ */
+ private static Definition getDefinition(Definition definition, QName serviceName) {
+
+ if (serviceName == null) {
+ return definition;
+ }
+
+ if (definition == null) {
+ return null;
+ }
+ Object service = definition.getServices().get(serviceName);
+ if (service != null) {
+ return definition;
+ }
+ for (Object i : definition.getImports().values()) {
+ List<Import> imports = (List<Import>)i;
+ for (Import imp : imports) {
+ Definition d = getDefinition(imp.getDefinition(), serviceName);
+ if (d != null) {
+ return d;
+ }
+ }
+ }
+ return null;
+ }
+
+ /**
+ * This method is copied from AxisService.createClientSideAxisService to
+ * work around http://issues.apache.org/jira/browse/WSCOMMONS-228
+ *
+ * @param wsdlDefinition
+ * @param wsdlServiceName
+ * @param portName
+ * @param options
+ * @return
+ * @throws AxisFault
+ */
+ @Deprecated
+ public static AxisService createClientSideAxisService(Definition wsdlDefinition,
+ QName wsdlServiceName,
+ String portName,
+ Options options) throws AxisFault {
+ Definition def = getDefinition(wsdlDefinition, wsdlServiceName);
+ final WSDL11ToAxisServiceBuilder serviceBuilder = new WSDL11ToAxisServiceBuilder(def, wsdlServiceName, portName);
+ serviceBuilder.setServerSide(false);
+ // [rfeng] Add a custom resolver to work around WSCOMMONS-228
+ serviceBuilder.setCustomResolver(new URIResolverImpl(def));
+ serviceBuilder.setBaseUri(def.getDocumentBaseURI());
+ // [rfeng]
+ // Allow access to read properties. Requires PropertiesPermission in security policy.
+ AxisService axisService;
+ try {
+ axisService = AccessController.doPrivileged(new PrivilegedExceptionAction<AxisService>() {
+ public AxisService run() throws AxisFault {
+ return serviceBuilder.populateService();
+ }
+ });
+ } catch ( PrivilegedActionException e ) {
+ throw (AxisFault) e.getException();
+ }
+
+ AxisEndpoint axisEndpoint = (AxisEndpoint)axisService.getEndpoints().get(axisService.getEndpointName());
+ options.setTo(new EndpointReference(axisEndpoint.getEndpointURL()));
+ if (axisEndpoint != null) {
+ options.setSoapVersionURI((String)axisEndpoint.getBinding().getProperty(WSDL2Constants.ATTR_WSOAP_VERSION));
+ }
+ return axisService;
+ }
+
+ private static <T extends ExtensibilityElement> T getExtensibilityElement(List elements, Class<T> type) {
+ for (Object e : elements) {
+ if (type.isInstance(e)) {
+ return type.cast(e);
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Generate a suitably configured WSDL definition
+ */
+ protected static void configureWSDLDefinition(WebServiceBinding wsBinding,
+ RuntimeComponent component,
+ AbstractContract contract) {
+ WSDLDefinition wsdlDefinition = wsBinding.getWSDLDefinition();
+ Definition def = wsdlDefinition.getDefinition();
+ if (wsBinding.getWSDLDefinition().getURI() != null) {
+ // The WSDL document was provided by the user. Generate a new
+ // WSDL document with imports from the user-provided document.
+ WSDLFactory factory = null;
+ try {
+ factory = WSDLFactory.newInstance();
+ } catch (WSDLException e) {
+ throw new RuntimeException(e);
+ }
+ Definition definition = factory.newDefinition();
+
+ // Construct a target namespace from the base URI of the user's
+ // WSDL document (is this what we should be using?) and a path
+ // computed according to the SCA Web Service binding spec.
+ String nsName = component.getName() + "/" + contract.getName();
+ String namespaceURI = null;
+ try {
+ URI userTNS = new URI(def.getTargetNamespace());
+ namespaceURI = userTNS.resolve("/" + nsName).toString();
+ } catch (URISyntaxException e1) {
+ } catch (IllegalArgumentException e2) {
+ }
+
+ // set name and targetNamespace attributes on the definition
+ String defsName = component.getName() + "." + contract.getName();
+ definition.setQName(new QName(namespaceURI, defsName));
+ definition.setTargetNamespace(namespaceURI);
+ definition.addNamespace("tns", namespaceURI);
+
+ // add soap11 or soap12 prefix as required
+ boolean requiresSOAP11 = false;
+ boolean requiresSOAP12 = false;
+ for (Object binding : def.getAllBindings().values()) {
+ List bindingExtensions = ((Binding)binding).getExtensibilityElements();
+ for (final Object extension : bindingExtensions) {
+ if (extension instanceof SOAPBinding) {
+ requiresSOAP11 = true;
+ }
+ if (extension instanceof SOAP12Binding) {
+ requiresSOAP12 = true;
+ }
+ }
+ }
+ if (requiresSOAP11 || wsBinding.getBinding() == null) {
+ definition.addNamespace("soap11", "http://schemas.xmlsoap.org/wsdl/soap/");
+ }
+ if (requiresSOAP12) {
+ definition.addNamespace("soap12", "http://schemas.xmlsoap.org/wsdl/soap12/");
+ }
+
+ // set wsdl namespace prefix on the definition
+ definition.addNamespace("wsdl", "http://schemas.xmlsoap.org/wsdl/");
+
+ // import the existing portType
+ int index = 0;
+ List<WSDLDefinition> imports = new ArrayList<WSDLDefinition>();
+ InterfaceContract ic = wsBinding.getBindingInterfaceContract();
+ WSDLInterface wi = (WSDLInterface)ic.getInterface();
+ PortType portType = wi.getPortType();
+ WSDLDefinition ptDef = getPortTypeDefinition(wsdlDefinition, portType.getQName());
+ if (ptDef != null) {
+ Import imp = definition.createImport();
+ String ptNamespace = portType.getQName().getNamespaceURI();
+ imp.setNamespaceURI(ptNamespace);
+ imp.setLocationURI(ptDef.getURI().toString());
+ imp.setDefinition(ptDef.getDefinition());
+ imports.add(ptDef);
+ definition.addNamespace("ns" + index++, ptNamespace);
+ definition.addImport(imp);
+ } else {
+ throw new RuntimeException("Unable to find portType " + portType.getQName());
+ }
+
+ // import an existing binding if specified
+ Binding binding = wsBinding.getBinding();
+ if (binding != null) {
+ String biNamespace = binding.getQName().getNamespaceURI();
+ if (definition.getImports(biNamespace) == null) {
+ WSDLDefinition biDef = getBindingDefinition(wsdlDefinition, binding.getQName());
+ if (biDef != null) {
+ Import imp = definition.createImport();
+ imp.setNamespaceURI(biNamespace);
+ imp.setLocationURI(biDef.getURI().toString());
+ imp.setDefinition(biDef.getDefinition());
+ imports.add(biDef);
+ definition.addNamespace("ns" + index++, biNamespace);
+ definition.addImport(imp);
+ } else {
+ throw new RuntimeException("Unable to find binding " + binding.getQName());
+ }
+ }
+ }
+
+ // replace original WSDL definition by the generated definition
+ def = definition;
+ wsdlDefinition.setDefinition(definition);
+ wsdlDefinition.setLocation(null);
+ wsdlDefinition.setURI(null);
+ wsdlDefinition.getImportedDefinitions().clear();
+ wsdlDefinition.getImportedDefinitions().addAll(imports);
+ }
+
+ QName serviceQName = wsBinding.getServiceName();
+ String portName = wsBinding.getPortName();
+
+ if (portName != null || serviceQName != null) {
+ return;
+ }
+
+ // If no WSDL service or port is specified in the binding element, add a
+ // suitably configured service and port to the WSDL definition.
+ WSDLDefinitionGenerator helper =
+ new WSDLDefinitionGenerator(Axis2ServiceBindingProvider.requiresSOAP12(wsBinding));
+ if (wsBinding.getBinding() == null) {
+ InterfaceContract ic = wsBinding.getBindingInterfaceContract();
+ WSDLInterface wi = (WSDLInterface)ic.getInterface();
+ PortType portType = wi.getPortType();
+ Service service = helper.createService(def, portType);
+ Binding binding = helper.createBinding(def, portType);
+ helper.createBindingOperations(def, binding, portType);
+ binding.setUndefined(false);
+ def.addBinding(binding);
+
+ Port port = helper.createPort(def, binding, service, wsBinding.getURI());
+ wsBinding.setService(service);
+ wsBinding.setPort(port);
+ wsBinding.setBinding(port.getBinding());
+ } else {
+ Service service = helper.createService(def, wsBinding.getBinding());
+ Port port = helper.createPort(def, wsBinding.getBinding(), service, wsBinding.getURI());
+ wsBinding.setService(service);
+ wsBinding.setPort(port);
+ }
+
+ }
+
+ private static WSDLDefinition getPortTypeDefinition(WSDLDefinition def, QName portTypeName) {
+
+ if (def == null || portTypeName == null) {
+ return def;
+ }
+ Object portType = def.getDefinition().getPortTypes().get(portTypeName);
+ if (portType != null) {
+ return def;
+ }
+ for (WSDLDefinition impDef : def.getImportedDefinitions()) {
+ WSDLDefinition d = getPortTypeDefinition(impDef, portTypeName);
+ if (d != null) {
+ return d;
+ }
+ }
+ return null;
+ }
+
+ private static WSDLDefinition getBindingDefinition(WSDLDefinition def, QName bindingName) {
+
+ if (def == null || bindingName == null) {
+ return def;
+ }
+ Object binding = def.getDefinition().getBindings().get(bindingName);
+ if (binding != null) {
+ return def;
+ }
+ for (WSDLDefinition impDef : def.getImportedDefinitions()) {
+ WSDLDefinition d = getBindingDefinition(impDef, bindingName);
+ if (d != null) {
+ return d;
+ }
+ }
+ return null;
+ }
+
+ protected void stop() {
+ if (serviceClient != null) {
+ // close all connections that we have initiated, so that the jetty server
+ // can be restarted without seeing ConnectExceptions
+ HttpClient httpClient =
+ (HttpClient)serviceClient.getServiceContext().getConfigurationContext()
+ .getProperty(HTTPConstants.CACHED_HTTP_CLIENT);
+ if (httpClient != null)
+ ((MultiThreadedHttpConnectionManager)httpClient.getHttpConnectionManager()).shutdown();
+
+ serviceClient = null;
+ }
+ }
+
+ /**
+ * Create and configure an Axis2BindingInvoker for each operation
+ */
+ protected Invoker createInvoker(Operation operation) {
+ Options options = new Options();
+ EndpointReference epTo = getWSATOEPR(wsBinding);
+ if (epTo != null) {
+ options.setTo(epTo);
+ }
+ options.setProperty(HTTPConstants.CHUNKED, Boolean.FALSE);
+
+ String operationName = operation.getName();
+
+ String soapAction = getSOAPAction(operationName);
+ if (soapAction != null && soapAction.length() > 1) {
+ options.setAction(soapAction);
+ }
+
+ options.setTimeOutInMilliSeconds(30 * 1000); // 30 seconds
+
+ // Allow privileged access to read properties. Requires PropertiesPermission read in
+ // security policy.
+ SOAPFactory soapFactory = AccessController.doPrivileged(new PrivilegedAction<SOAPFactory>() {
+ public SOAPFactory run() {
+ if (requiresSOAP12())
+ return OMAbstractFactory.getSOAP12Factory();
+ else
+ return OMAbstractFactory.getSOAP11Factory();
+
+ }
+ });
+ QName wsdlOperationQName = new QName(operationName);
+ if (requiresMTOM())
+ {
+ options.setProperty(org.apache.axis2.Constants.Configuration.ENABLE_MTOM, org.apache.axis2.Constants.VALUE_TRUE);
+ }
+ Axis2BindingInvoker invoker;
+ if (operation.isNonBlocking()) {
+ invoker = new Axis2OneWayBindingInvoker(this, wsdlOperationQName, options, soapFactory, policyHandlerList);
+ } else {
+ invoker = new Axis2BindingInvoker(this, wsdlOperationQName, options, soapFactory, policyHandlerList);
+ }
+
+ return invoker;
+ }
+
+ private boolean requiresSOAP12() {
+ return isIntentRequired(wsBinding, SOAP12_INTENT);
+ }
+
+ private boolean requiresMTOM() {
+ return isIntentRequired(wsBinding, AxisPolicyHelper.MTOM_INTENT);
+ }
+
+ protected EndpointReference getWSATOEPR(WebServiceBinding binding) {
+ EndpointReference epr = getEPR(binding);
+ if (epr == null) {
+ epr = getPortLocationEPR(binding);
+ } else if (epr.getAddress() == null || epr.getAddress().length() < 1) {
+ EndpointReference bindingEPR = getPortLocationEPR(binding);
+ if (bindingEPR != null) {
+ epr.setAddress(bindingEPR.getAddress());
+ }
+ }
+ return epr;
+ }
+
+ protected EndpointReference getPortLocationEPR(WebServiceBinding binding) {
+ String ep = null;
+ if (binding.getPort() != null) {
+ List<?> wsdlPortExtensions = binding.getPort().getExtensibilityElements();
+ for (final Object extension : wsdlPortExtensions) {
+ if (extension instanceof SOAPAddress) {
+ ep = ((SOAPAddress)extension).getLocationURI();
+ break;
+ }
+ if (extension instanceof SOAP12Address) {
+ SOAP12Address address = (SOAP12Address)extension;
+ ep = address.getLocationURI();
+ break;
+ }
+ }
+ }
+ if(ep == null || ep.equals("")) {
+ ep = binding.getURI();
+ }
+ return ep == null || "".equals(ep) ? null : new EndpointReference(ep);
+ }
+
+ protected org.apache.axis2.addressing.EndpointReference getEPR(WebServiceBinding wsBinding) {
+ if (wsBinding.getEndPointReference() == null) {
+ return null;
+ }
+ try {
+
+ XMLStreamReader parser =
+ XMLInputFactory.newInstance().createXMLStreamReader(new DOMSource(wsBinding.getEndPointReference()));
+ StAXOMBuilder builder = new StAXOMBuilder(parser);
+ OMElement omElement = builder.getDocumentElement();
+ org.apache.axis2.addressing.EndpointReference epr = EndpointReferenceHelper.fromOM(omElement);
+ return epr;
+
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ } catch (XMLStreamException e) {
+ throw new RuntimeException(e);
+ } catch (FactoryConfigurationError e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ protected String getSOAPAction(String operationName) {
+ Binding binding = wsBinding.getBinding();
+ if (binding != null) {
+ for (Object o : binding.getBindingOperations()) {
+ BindingOperation bop = (BindingOperation)o;
+ if (bop.getName().equalsIgnoreCase(operationName)) {
+ for (Object o2 : bop.getExtensibilityElements()) {
+ if (o2 instanceof SOAPOperation) {
+ return ((SOAPOperation)o2).getSoapActionURI();
+ }
+ }
+ }
+ }
+ }
+ return null;
+ }
+
+ private void createPolicyHandlers() throws IllegalAccessException, InstantiationException, ClassNotFoundException {
+ if (wsBinding instanceof PolicySetAttachPoint) {
+ PolicySetAttachPoint policiedBinding = (PolicySetAttachPoint)wsBinding;
+ PolicyHandler policyHandler = null;
+ for (PolicySet policySet : policiedBinding.getPolicySets()) {
+ policyHandler = PolicyHandlerUtils.findPolicyHandler(policySet, policyHandlerClassnames);
+ if (policyHandler != null) {
+ policyHandler.setApplicablePolicySet(policySet);
+ policyHandlerList.add(policyHandler);
+ }
+ }
+ }
+ }
+
+ private void setupPolicyHandlers(List<PolicyHandler> policyHandlers, ConfigurationContext configContext) {
+ for (PolicyHandler aHandler : policyHandlers) {
+ aHandler.setUp(configContext);
+ }
+ }
+}
diff --git a/sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/Axis2ServiceInMessageReceiver.java b/sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/Axis2ServiceInMessageReceiver.java
new file mode 100644
index 0000000000..3b188b0176
--- /dev/null
+++ b/sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/Axis2ServiceInMessageReceiver.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.binding.ws.axis2;
+
+import java.lang.reflect.InvocationTargetException;
+import java.util.List;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.context.MessageContext;
+import org.apache.axis2.receivers.AbstractInMessageReceiver;
+import org.apache.tuscany.sca.interfacedef.Operation;
+import org.apache.tuscany.sca.policy.util.PolicyHandler;
+
+public class Axis2ServiceInMessageReceiver extends AbstractInMessageReceiver {
+
+ protected Operation operation;
+
+ private Axis2ServiceProvider provider;
+
+ private List<PolicyHandler> policyHandlerList = null;
+
+ public Axis2ServiceInMessageReceiver(Axis2ServiceProvider provider, Operation operation, List<PolicyHandler> policyHandlerList) {
+ this.provider = provider;
+ this.operation = operation;
+ this.policyHandlerList = policyHandlerList;
+ }
+
+ public Axis2ServiceInMessageReceiver() {
+ }
+
+ @Override
+ public void invokeBusinessLogic(MessageContext inMC) throws AxisFault {
+ try {
+ OMElement requestOM = inMC.getEnvelope().getBody().getFirstElement();
+ Object[] args = new Object[] {requestOM};
+
+ for ( PolicyHandler policyHandler : policyHandlerList ) {
+ policyHandler.beforeInvoke(operation, args, inMC);
+ }
+
+ provider.invokeTarget(operation, args, inMC);
+
+ for ( PolicyHandler policyHandler : policyHandlerList ) {
+ policyHandler.afterInvoke(operation, args, inMC);
+ }
+
+ } catch (InvocationTargetException e) {
+ Throwable t = e.getCause();
+ if (t instanceof Exception) {
+ throw AxisFault.makeFault((Exception)t);
+ }
+ throw new RuntimeException(e);
+ } catch (Exception e) {
+ e.printStackTrace();
+ throw AxisFault.makeFault(e);
+ }
+ }
+}
diff --git a/sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/Axis2ServiceInOutSyncMessageReceiver.java b/sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/Axis2ServiceInOutSyncMessageReceiver.java
new file mode 100644
index 0000000000..20930666b1
--- /dev/null
+++ b/sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/Axis2ServiceInOutSyncMessageReceiver.java
@@ -0,0 +1,99 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tuscany.sca.binding.ws.axis2;
+
+import java.lang.reflect.InvocationTargetException;
+import java.util.List;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.soap.SOAPEnvelope;
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.Constants;
+import org.apache.axis2.context.MessageContext;
+import org.apache.axis2.receivers.AbstractInOutSyncMessageReceiver;
+import org.apache.tuscany.sca.interfacedef.Operation;
+import org.apache.tuscany.sca.interfacedef.util.FaultException;
+import org.apache.tuscany.sca.policy.util.PolicyHandler;
+import org.osoa.sca.ServiceRuntimeException;
+
+public class Axis2ServiceInOutSyncMessageReceiver extends AbstractInOutSyncMessageReceiver {
+ private static final Logger logger = Logger.getLogger(Axis2ServiceInOutSyncMessageReceiver.class.getName());
+
+ protected Operation operation;
+ private List<PolicyHandler> policyHandlerList = null;
+
+ private Axis2ServiceProvider provider;
+
+ public Axis2ServiceInOutSyncMessageReceiver(Axis2ServiceProvider provider, Operation operation, List<PolicyHandler> policyHandlerList) {
+ this.provider = provider;
+ this.operation = operation;
+ this.policyHandlerList = policyHandlerList;
+ }
+
+ public Axis2ServiceInOutSyncMessageReceiver() {
+ }
+
+ @Override
+ public void invokeBusinessLogic(MessageContext inMC, MessageContext outMC) throws AxisFault {
+ try {
+ OMElement requestOM = inMC.getEnvelope().getBody().getFirstElement();
+ Object[] args = null;
+
+ if (requestOM != null) {
+ args = new Object[] {requestOM};
+ }
+
+ for ( PolicyHandler policyHandler : policyHandlerList ) {
+ policyHandler.beforeInvoke(operation, args, inMC);
+ }
+
+ OMElement responseOM = (OMElement)provider.invokeTarget(operation, args, inMC);
+
+ for ( PolicyHandler policyHandler : policyHandlerList ) {
+ policyHandler.afterInvoke(operation, args, inMC, responseOM);
+ }
+
+ SOAPEnvelope soapEnvelope = getSOAPFactory(inMC).getDefaultEnvelope();
+ if (null != responseOM ) {
+ soapEnvelope.getBody().addChild(responseOM);
+ }
+ outMC.setEnvelope(soapEnvelope);
+ outMC.getOperationContext().setProperty(Constants.RESPONSE_WRITTEN, Constants.VALUE_TRUE);
+
+ } catch (InvocationTargetException e) {
+ Throwable t = e.getCause();
+ if (t instanceof FaultException && ((FaultException)t).getFaultInfo() instanceof OMElement) {
+ OMElement faultDetail = (OMElement)((FaultException)t).getFaultInfo();
+ inMC.setProperty(Constants.FAULT_NAME, faultDetail.getQName().getLocalPart());
+ AxisFault f = new AxisFault(null, e.getMessage(), "faultNode", "faultRole", faultDetail);
+ throw f;
+ }
+ if (t instanceof Exception) {
+ throw AxisFault.makeFault((Exception)t);
+ }
+ logger.log(Level.SEVERE, e.getMessage(), t);
+ throw new ServiceRuntimeException(e);
+ } catch (Throwable e) {
+ logger.log(Level.SEVERE, e.getMessage(), e);
+ throw AxisFault.makeFault(e);
+ }
+ }
+}
diff --git a/sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/Axis2ServiceProvider.java b/sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/Axis2ServiceProvider.java
new file mode 100644
index 0000000000..b90a3ee42b
--- /dev/null
+++ b/sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/Axis2ServiceProvider.java
@@ -0,0 +1,700 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.tuscany.sca.binding.ws.axis2;
+
+import java.io.IOException;
+import java.lang.reflect.InvocationTargetException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.security.AccessController;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Vector;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import javax.wsdl.Definition;
+import javax.wsdl.Import;
+import javax.wsdl.Port;
+import javax.wsdl.extensions.soap.SOAPAddress;
+import javax.wsdl.extensions.soap12.SOAP12Address;
+import javax.xml.namespace.QName;
+import javax.xml.stream.FactoryConfigurationError;
+import javax.xml.stream.XMLInputFactory;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamReader;
+import javax.xml.transform.dom.DOMSource;
+
+import org.apache.axiom.om.OMAbstractFactory;
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.OMFactory;
+import org.apache.axiom.om.impl.builder.StAXOMBuilder;
+import org.apache.axiom.soap.SOAPHeader;
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.Constants;
+import org.apache.axis2.addressing.AddressingConstants;
+import org.apache.axis2.addressing.EndpointReferenceHelper;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.context.MessageContext;
+import org.apache.axis2.deployment.util.Utils;
+import org.apache.axis2.description.AxisEndpoint;
+import org.apache.axis2.description.AxisOperation;
+import org.apache.axis2.description.AxisService;
+import org.apache.axis2.description.Parameter;
+import org.apache.axis2.description.TransportInDescription;
+import org.apache.axis2.description.TransportOutDescription;
+import org.apache.axis2.description.WSDL11ToAxisServiceBuilder;
+import org.apache.axis2.description.WSDL2Constants;
+import org.apache.axis2.description.WSDLToAxisServiceBuilder;
+import org.apache.axis2.engine.ListenerManager;
+import org.apache.axis2.engine.MessageReceiver;
+import org.apache.axis2.transport.jms.JMSConstants;
+import org.apache.axis2.transport.jms.JMSListener;
+import org.apache.axis2.transport.jms.JMSSender;
+import org.apache.axis2.transport.jms.JMSUtils;
+import org.apache.axis2.wsdl.WSDLConstants;
+import org.apache.tuscany.sca.assembly.AbstractContract;
+import org.apache.tuscany.sca.assembly.Binding;
+import org.apache.tuscany.sca.binding.ws.WebServiceBinding;
+import org.apache.tuscany.sca.binding.ws.axis2.Axis2ServiceClient.URIResolverImpl;
+import org.apache.tuscany.sca.core.assembly.EndpointReferenceImpl;
+import org.apache.tuscany.sca.host.http.ServletHost;
+import org.apache.tuscany.sca.interfacedef.Interface;
+import org.apache.tuscany.sca.interfacedef.Operation;
+import org.apache.tuscany.sca.interfacedef.java.JavaInterface;
+import org.apache.tuscany.sca.invocation.Message;
+import org.apache.tuscany.sca.invocation.MessageFactory;
+import org.apache.tuscany.sca.policy.PolicySet;
+import org.apache.tuscany.sca.policy.PolicySetAttachPoint;
+import org.apache.tuscany.sca.policy.security.ws.Axis2ConfigParamPolicy;
+import org.apache.tuscany.sca.policy.util.PolicyHandler;
+import org.apache.tuscany.sca.policy.util.PolicyHandlerTuple;
+import org.apache.tuscany.sca.policy.util.PolicyHandlerUtils;
+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.RuntimeComponentService;
+import org.apache.tuscany.sca.runtime.RuntimeWire;
+import org.apache.ws.security.WSSecurityEngineResult;
+import org.apache.ws.security.handler.WSHandlerConstants;
+import org.apache.ws.security.handler.WSHandlerResult;
+import org.osoa.sca.ServiceRuntimeException;
+
+public class Axis2ServiceProvider {
+
+ private static final Logger logger = Logger.getLogger(Axis2ServiceProvider.class.getName());
+
+ private RuntimeComponent component;
+ private AbstractContract contract;
+ private WebServiceBinding wsBinding;
+ private ServletHost servletHost;
+ private MessageFactory messageFactory;
+ private ConfigurationContext configContext;
+ private JMSSender jmsSender;
+ private JMSListener jmsListener;
+ private Map<ClassLoader, List<PolicyHandlerTuple>> policyHandlerClassnames = null;
+ private List<PolicyHandler> policyHandlerList = new ArrayList<PolicyHandler>();
+
+ public static final QName QNAME_WSA_ADDRESS =
+ new QName(AddressingConstants.Final.WSA_NAMESPACE, AddressingConstants.EPR_ADDRESS);
+ public static final QName QNAME_WSA_FROM =
+ new QName(AddressingConstants.Final.WSA_NAMESPACE, AddressingConstants.WSA_FROM);
+ public static final QName QNAME_WSA_REFERENCE_PARAMETERS =
+ new QName(AddressingConstants.Final.WSA_NAMESPACE, AddressingConstants.EPR_REFERENCE_PARAMETERS);
+
+ private static final String DEFAULT_QUEUE_CONNECTION_FACTORY = "TuscanyQueueConnectionFactory";
+
+ private static final QName TRANSPORT_JMS_QUALIFIED_INTENT = new QName("http://www.osoa.org/xmlns/sca/1.0","transport.jms");
+ private PolicySet transportJmsPolicySet = null;
+
+
+ public Axis2ServiceProvider(RuntimeComponent component,
+ AbstractContract contract,
+ WebServiceBinding wsBinding,
+ ServletHost servletHost,
+ MessageFactory messageFactory,
+ Map<ClassLoader, List<PolicyHandlerTuple>> policyHandlerClassnames) {
+
+ this.component = component;
+ this.contract = contract;
+ this.wsBinding = wsBinding;
+ this.servletHost = servletHost;
+ this.messageFactory = messageFactory;
+ this.policyHandlerClassnames = policyHandlerClassnames;
+
+ final boolean isRampartRequired = AxisPolicyHelper.isRampartRequired(wsBinding);
+ try {
+ // TuscanyAxisConfigurator tuscanyAxisConfigurator = new TuscanyAxisConfigurator();
+ // Allow privileged access to read properties. Requires PropertyPermission read in
+ // security policy.
+ TuscanyAxisConfigurator tuscanyAxisConfigurator =
+ AccessController.doPrivileged(new PrivilegedExceptionAction<TuscanyAxisConfigurator>() {
+ public TuscanyAxisConfigurator run() throws AxisFault {
+ return new TuscanyAxisConfigurator(isRampartRequired);
+ }
+ });
+ configContext = tuscanyAxisConfigurator.getConfigurationContext();
+ // deployRampartModule();
+ // configureSecurity();
+ } catch (PrivilegedActionException e) {
+ throw new ServiceRuntimeException(e.getException());
+ } catch (AxisFault e) {
+ throw new ServiceRuntimeException(e); // TODO: better exception
+ }
+
+ configContext.setContextRoot(servletHost.getContextPath());
+
+ // pull out the binding intents to see what sort of transport is required
+ transportJmsPolicySet = AxisPolicyHelper.getPolicySet(wsBinding, TRANSPORT_JMS_QUALIFIED_INTENT);
+
+ String uri;
+
+ if (transportJmsPolicySet != null){
+ uri = computeActualURI(component, contract);
+
+ if (!uri.startsWith("jms:/")) {
+ uri = "jms:" + uri;
+ }
+
+ // construct the rest of the URI based on the policy. All the details are put
+ // into the URI here rather than being place directly into the Axis configuration
+ // as the Axis JMS sender relies on parsing the target URI
+ Axis2ConfigParamPolicy axis2ConfigParamPolicy = null;
+ for ( Object policy : transportJmsPolicySet.getPolicies() ) {
+ if ( policy instanceof Axis2ConfigParamPolicy ) {
+ axis2ConfigParamPolicy = (Axis2ConfigParamPolicy)policy;
+ Iterator paramIterator = axis2ConfigParamPolicy.getParamElements().get(DEFAULT_QUEUE_CONNECTION_FACTORY).getChildElements();
+
+ if (paramIterator.hasNext()){
+ StringBuffer uriParams = new StringBuffer("?");
+
+ while (paramIterator.hasNext()){
+ OMElement parameter = (OMElement)paramIterator.next();
+ uriParams.append(parameter.getAttributeValue(new QName("","name")));
+ uriParams.append("=");
+ uriParams.append(parameter.getText());
+
+ if (paramIterator.hasNext()){
+ uriParams.append("&");
+ }
+ }
+
+ uri = uri + uriParams;
+ }
+ }
+ }
+ } else {
+ uri = computeActualURI(component, contract);
+ if (!uri.startsWith("jms:")) {
+ uri = servletHost.getURLMapping(uri).toString();
+ }
+ }
+
+ wsBinding.setURI(uri);
+ }
+
+ public void start() {
+
+ // TODO: if <binding.ws> specifies the WSDL service then should create a
+ // service for every port
+
+ try {
+ createPolicyHandlers();
+ AxisService axisService = createAxisService();
+ configContext.getAxisConfiguration().addService( axisService );
+
+ setupPolicyHandlers(policyHandlerList, configContext);
+
+ String endpointURL = axisService.getEndpointURL();
+ if ( endpointURL.startsWith( "http://") || endpointURL.startsWith("/")) {
+ Axis2ServiceServlet servlet = new Axis2ServiceServlet();
+ servlet.init(configContext);
+ String servletURI = wsBinding.getURI();
+ configContext.setContextRoot(servletURI);
+ servletHost.addServletMapping(servletURI, servlet);
+ } else if ( axisService.getEndpointURL().startsWith( "jms" ) ) {
+ logger.log(Level.INFO,"Axis2 JMS URL=" + axisService.getEndpointURL() );
+
+ jmsListener = new JMSListener();
+ jmsSender = new JMSSender();
+ ListenerManager listenerManager = configContext.getListenerManager();
+ TransportInDescription trsIn = configContext.getAxisConfiguration().getTransportIn(Constants.TRANSPORT_JMS);
+
+ // get JMS transport parameters from the binding URI
+ Map<String, String> jmsProps = JMSUtils.getProperties( wsBinding.getURI() );
+
+ // collect the parameters used to configure the JMS transport
+ OMFactory fac = OMAbstractFactory.getOMFactory();
+ OMElement parms = fac.createOMElement(DEFAULT_QUEUE_CONNECTION_FACTORY, null);
+
+ for ( String key : jmsProps.keySet() ) {
+ OMElement param = fac.createOMElement("parameter", null);
+ param.addAttribute( "name", key, null );
+ param.addChild(fac.createOMText(param, jmsProps.get(key)));
+ parms.addChild(param);
+ }
+
+ Parameter queueConnectionFactory = new Parameter(DEFAULT_QUEUE_CONNECTION_FACTORY, parms);
+ trsIn.addParameter( queueConnectionFactory );
+
+ trsIn.setReceiver(jmsListener);
+
+ configContext.getAxisConfiguration().addTransportIn( trsIn );
+ TransportOutDescription trsOut = configContext.getAxisConfiguration().getTransportOut(Constants.TRANSPORT_JMS);
+ //configContext.getAxisConfiguration().addTransportOut( trsOut );
+ trsOut.setSender(jmsSender);
+
+ if (listenerManager == null) {
+ listenerManager = new ListenerManager();
+ listenerManager.init(configContext);
+ }
+ listenerManager.addListener(trsIn, true);
+ jmsSender.init(configContext, trsOut);
+ jmsListener.init(configContext, trsIn);
+ jmsListener.start();
+ }
+ } catch (AxisFault e) {
+ throw new RuntimeException(e);
+ } catch (ClassNotFoundException e) {
+ throw new RuntimeException(e);
+ } catch (InstantiationException e) {
+ throw new RuntimeException(e);
+ } catch (IllegalAccessException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public void stop() {
+ if ( jmsListener != null ) {
+ jmsListener.stop();
+ jmsListener.destroy();
+ }
+ else {
+ servletHost.removeServletMapping(wsBinding.getURI());
+ }
+
+ if ( jmsSender != null )
+ jmsSender.stop();
+
+ try {
+ // get the path to the service
+ URI uriPath = new URI(wsBinding.getURI());
+ String stringURIPath = uriPath.getPath();
+
+ // remove any "/" from the start of the path
+ if (stringURIPath.startsWith("/")) {
+ stringURIPath = stringURIPath.substring(1, stringURIPath.length());
+ }
+
+ // remove it from the Axis context
+ configContext.getAxisConfiguration().removeService(stringURIPath);
+ } catch (URISyntaxException e) {
+ throw new RuntimeException(e);
+ } catch (AxisFault e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Compute the endpoint URI based on section 2.1.1 of the WS binding Specification 1.
+ * The URIs in the endpoint(s) of the referenced WSDL, which may be relative
+ * 2. The URI specified by the wsa:Address element of the
+ * wsa:EndpointReference, which may be relative 3. The explicitly stated URI
+ * in the "uri" attribute of the binding.ws element, which may be relative,
+ * 4. The implicit URI as defined by in section 1.7 in the SCA Assembly Specification
+ * If the <binding.ws> has no wsdlElement but does have a uri attribute then
+ * the uri takes precedence over any implicitly used WSDL.
+ *
+ */
+ protected String computeActualURI(RuntimeComponent component, AbstractContract contract) {
+
+ org.apache.axis2.addressing.EndpointReference epr = null;
+ URI eprURI = null;
+ if (wsBinding.getEndPointReference() != null) {
+ epr = getEPR();
+ if (epr.getAddress() != null) {
+ eprURI = URI.create(epr.getAddress());
+ }
+ }
+
+ URI wsdlURI = null;
+ if (wsBinding.getServiceName() != null && wsBinding.getBindingName() == null) {
+ // <binding.ws> explicitly points at a WSDL port, may be a relative URI
+ wsdlURI = getEndpoint(wsBinding.getPort());
+ }
+
+ // if the WSDL port/endpoint has an absolute URI use that
+ if (wsdlURI != null && wsdlURI.isAbsolute()) {
+ return wsdlURI.toString();
+ }
+
+ // if the wsa:EndpointReference has an address element with an absolute URI use that
+ if (eprURI != null && eprURI.isAbsolute()) {
+ return eprURI.toString();
+ }
+
+ // either there is no WSDL port endpoint URI or that URI is relative
+ String actualURI = wsBinding.getURI();
+ if (eprURI != null && eprURI.toString().length() != 0) {
+ // there is a relative URI in the binding EPR
+ actualURI = actualURI + "/" + eprURI;
+ }
+
+ if (wsdlURI != null && wsdlURI.toString().length() != 0) {
+ // there is a relative URI in the WSDL port
+ actualURI = actualURI + "/" + wsdlURI;
+ }
+
+ actualURI = URI.create(actualURI).normalize().toString();
+
+ return actualURI;
+ }
+
+ private org.apache.axis2.addressing.EndpointReference getEPR() {
+ try {
+
+ XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(new DOMSource(wsBinding.getEndPointReference()));
+ StAXOMBuilder builder = new StAXOMBuilder(parser);
+ OMElement omElement = builder.getDocumentElement();
+ org.apache.axis2.addressing.EndpointReference epr = EndpointReferenceHelper.fromOM(omElement);
+ return epr;
+
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ } catch (XMLStreamException e) {
+ throw new RuntimeException(e);
+ } catch (FactoryConfigurationError e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Returns the endpoint of a given port.
+ */
+ protected URI getEndpoint(Port wsdlPort) {
+ if (wsdlPort != null) {
+ List<?> wsdlPortExtensions = wsdlPort.getExtensibilityElements();
+ for (Object extension : wsdlPortExtensions) {
+ if (extension instanceof SOAPAddress) {
+ String uri = ((SOAPAddress)extension).getLocationURI();
+ return (uri == null || "".equals(uri)) ? null : URI.create(uri);
+ }
+ if (extension instanceof SOAP12Address) {
+ SOAP12Address address = (SOAP12Address)extension;
+ String uri = address.getLocationURI();
+ return (uri == null || "".equals(uri)) ? null : URI.create(uri);
+ }
+ }
+ }
+ return null;
+ }
+
+ private AxisService createAxisService() throws AxisFault {
+ AxisService axisService;
+ if (wsBinding.getWSDLDefinition() != null) {
+ axisService = createWSDLAxisService();
+ } else {
+ axisService = createJavaAxisService();
+ }
+ initAxisOperations(axisService);
+ return axisService;
+ }
+
+ /**
+ * Create an AxisService from the interface class from the SCA service interface
+ */
+ protected AxisService createJavaAxisService() throws AxisFault {
+ AxisService axisService = new AxisService();
+ String path = URI.create(wsBinding.getURI()).getPath();
+ axisService.setName(path);
+ axisService.setServiceDescription("Tuscany configured AxisService for service: " + wsBinding.getURI());
+ axisService.setClientSide(false);
+ Parameter classParam =
+ new Parameter(Constants.SERVICE_CLASS, ((JavaInterface)contract.getInterfaceContract().getInterface())
+ .getJavaClass().getName());
+ axisService.addParameter(classParam);
+ try {
+ Utils.fillAxisService(axisService, configContext.getAxisConfiguration(), null, null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return axisService;
+ }
+
+ /**
+ * Workaround for https://issues.apache.org/jira/browse/AXIS2-3205
+ * @param definition
+ * @param serviceName
+ * @return
+ */
+ private static Definition getDefinition(Definition definition, QName serviceName) {
+
+ if (serviceName == null){
+ return definition;
+ }
+
+ if (definition == null) {
+ return null;
+ }
+ Object service = definition.getServices().get(serviceName);
+ if (service != null) {
+ return definition;
+ }
+ for (Object i : definition.getImports().values()) {
+ List<Import> imports = (List<Import>)i;
+ for (Import imp : imports) {
+ Definition d = getDefinition(imp.getDefinition(), serviceName);
+ if (d != null) {
+ return d;
+ }
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Create an AxisService from the WSDL doc used by ws binding
+ */
+ protected AxisService createWSDLAxisService() throws AxisFault {
+
+ Axis2ServiceClient.configureWSDLDefinition(wsBinding, component, contract);
+ // The service, port and WSDL definition can be set by the above call
+ Definition definition = wsBinding.getWSDLDefinition().getDefinition();
+ QName serviceQName =
+ wsBinding.getService() != null ? wsBinding.getService().getQName() : wsBinding.getServiceName();
+ String portName = wsBinding.getPort() != null ? wsBinding.getPort().getName() : wsBinding.getPortName();
+
+ Definition def = getDefinition(definition, serviceQName);
+
+ final WSDLToAxisServiceBuilder builder = new WSDL11ToAxisServiceBuilder(def, serviceQName, portName);
+ builder.setServerSide(true);
+ // [rfeng] Add a custom resolver to work around WSCOMMONS-228
+ builder.setCustomResolver(new URIResolverImpl(def));
+ builder.setBaseUri(def.getDocumentBaseURI());
+ // [rfeng]
+ // AxisService axisService = builder.populateService();
+ // Allow privileged access to read properties. Requires PropertiesPermission read in
+ // security policy.
+ AxisService axisService;
+ try {
+ axisService = AccessController.doPrivileged(new PrivilegedExceptionAction<AxisService>() {
+ public AxisService run() throws AxisFault {
+ return builder.populateService();
+ }
+ });
+ } catch (PrivilegedActionException e) {
+ throw (AxisFault)e.getException();
+ }
+ String path = URI.create(wsBinding.getURI()).getPath();
+ String name = ( path.startsWith( "/") ? path.substring(1) : path );
+ axisService.setName(name);
+ String endpointURL = wsBinding.getURI();
+ axisService.setEndpointURL(endpointURL );
+ axisService.setDocumentation("Tuscany configured AxisService for service: " + wsBinding.getURI());
+ for ( Iterator i = axisService.getEndpoints().values().iterator(); i.hasNext(); ) {
+ AxisEndpoint ae = (AxisEndpoint)i.next();
+ if (endpointURL.startsWith("jms") ) {
+ Parameter qcf = new Parameter(JMSConstants.CONFAC_PARAM, null);
+ qcf.setValue(DEFAULT_QUEUE_CONNECTION_FACTORY);
+ axisService.addParameter(qcf);
+ break;
+ }
+ }
+ // Use the existing WSDL
+ Parameter wsdlParam = new Parameter(WSDLConstants.WSDL_4_J_DEFINITION, null);
+ wsdlParam.setValue(def);
+ axisService.addParameter(wsdlParam);
+ Parameter userWSDL = new Parameter("useOriginalwsdl", "true");
+ axisService.addParameter(userWSDL);
+
+ return axisService;
+ }
+
+ protected void initAxisOperations(AxisService axisService) {
+ for (Iterator<?> i = axisService.getOperations(); i.hasNext();) {
+ AxisOperation axisOp = (AxisOperation)i.next();
+ Operation op = getOperation(axisOp);
+ if (op != null) {
+
+ if (op.isNonBlocking()) {
+ axisOp.setMessageExchangePattern(WSDL2Constants.MEP_URI_IN_ONLY);
+ } else {
+ axisOp.setMessageExchangePattern(WSDL2Constants.MEP_URI_IN_OUT);
+ }
+
+ MessageReceiver msgrec = null;
+ if (op.isNonBlocking()) {
+ msgrec = new Axis2ServiceInMessageReceiver(this, op, policyHandlerList);
+ } else {
+ msgrec = new Axis2ServiceInOutSyncMessageReceiver(this, op, policyHandlerList);
+ }
+ axisOp.setMessageReceiver(msgrec);
+ }
+ }
+ }
+
+ protected Operation getOperation(AxisOperation axisOp) {
+ String operationName = axisOp.getName().getLocalPart();
+ Interface iface = wsBinding.getBindingInterfaceContract().getInterface();
+ for (Operation op : iface.getOperations()) {
+ if (op.getName().equalsIgnoreCase(operationName)) {
+ return op;
+ }
+ }
+ return null;
+ }
+
+ // methods for Axis2 message receivers
+
+ public Object invokeTarget(Operation op, Object[] args, MessageContext inMC) throws InvocationTargetException {
+ String callbackAddress = null;
+ String callbackID = null;
+ Object conversationID = null;
+
+ //FIXME: can we use the Axis2 addressing support for this?
+ SOAPHeader header = inMC.getEnvelope().getHeader();
+ if (header != null) {
+ OMElement from = header.getFirstChildWithName(QNAME_WSA_FROM);
+ if (from != null) {
+ OMElement callbackAddrElement = from.getFirstChildWithName(QNAME_WSA_ADDRESS);
+ if (callbackAddrElement != null) {
+ if (contract.getInterfaceContract().getCallbackInterface() != null) {
+ callbackAddress = callbackAddrElement.getText();
+ }
+ }
+ OMElement params = from.getFirstChildWithName(QNAME_WSA_REFERENCE_PARAMETERS);
+ if (params != null) {
+ OMElement convIDElement =
+ params.getFirstChildWithName(Axis2BindingInvoker.CONVERSATION_ID_REFPARM_QN);
+ if (convIDElement != null) {
+ if (isConversational()) {
+ conversationID = convIDElement.getText();
+ }
+ }
+ OMElement callbackIDElement =
+ params.getFirstChildWithName(Axis2BindingInvoker.CALLBACK_ID_REFPARM_QN);
+ if (callbackIDElement != null) {
+ callbackID = callbackIDElement.getText();
+ }
+ }
+ }
+ }
+
+ // create a message object and set the args as its body
+ Message msg = messageFactory.createMessage();
+ msg.setBody(args);
+ msg.setOperation(op);
+
+ //fill message with QoS context info
+ fillQoSContext(msg, inMC);
+
+ // if reference parameters are needed, create a new "From" EPR to hold them
+ EndpointReference from = null;
+ ReferenceParameters parameters = null;
+ if (callbackAddress != null ||
+ callbackID != null ||
+ conversationID != null) {
+ from = new EndpointReferenceImpl(null);
+ parameters = from.getReferenceParameters();
+ msg.setFrom(from);
+ }
+
+ // set the reference parameters into the "From" EPR
+ if (callbackAddress != null) {
+ parameters.setCallbackReference(new EndpointReferenceImpl(callbackAddress));
+ }
+ if (callbackID != null) {
+ parameters.setCallbackID(callbackID);
+ }
+ if (conversationID != null) {
+ parameters.setConversationID(conversationID);
+ }
+
+ // find the runtime wire and invoke it with the message
+ RuntimeWire wire = ((RuntimeComponentService)contract).getRuntimeWire(getBinding());
+ return wire.invoke(op, msg);
+ }
+
+ public boolean isConversational() {
+ return wsBinding.getBindingInterfaceContract().getInterface().isConversational();
+ }
+
+ /**
+ * Return the binding for this provider as a primitive binding type
+ * For use when looking up wires registered against the binding.
+ *
+ * @return the binding
+ */
+ protected Binding getBinding() {
+ return wsBinding;
+ }
+
+ private void setupPolicyHandlers(List<PolicyHandler> policyHandlers, ConfigurationContext configContext) {
+ for ( PolicyHandler aHandler : policyHandlers ) {
+ aHandler.setUp(configContext);
+ }
+ }
+
+ private void createPolicyHandlers() throws IllegalAccessException,
+ InstantiationException,
+ ClassNotFoundException {
+ if (wsBinding instanceof PolicySetAttachPoint) {
+ PolicySetAttachPoint policiedBinding = (PolicySetAttachPoint)wsBinding;
+ PolicyHandler policyHandler = null;
+ for (PolicySet policySet : policiedBinding.getPolicySets()) {
+ policyHandler =
+ PolicyHandlerUtils.findPolicyHandler(policySet, policyHandlerClassnames);
+ if (policyHandler != null) {
+ policyHandler.setApplicablePolicySet(policySet);
+ policyHandlerList.add(policyHandler);
+ }
+ }
+ }
+ }
+
+
+ private void fillQoSContext(Message message, MessageContext axis2MsgCtx) {
+ if ( axis2MsgCtx.getProperty(WSHandlerConstants.RECV_RESULTS) != null &&
+ axis2MsgCtx.getProperty(WSHandlerConstants.RECV_RESULTS) instanceof Vector ) {
+ Vector recvResults = (Vector)axis2MsgCtx.getProperty(WSHandlerConstants.RECV_RESULTS);
+ for ( int count1 = 0 ; count1 < recvResults.size() ; ++count1 ) {
+ if ( recvResults.elementAt(count1) instanceof WSHandlerResult ) {
+ WSHandlerResult wshr = (WSHandlerResult)recvResults.elementAt(count1);
+ Vector results = wshr.getResults();
+ for ( int count2 = 0 ; count2 < results.size() ; ++count2 ) {
+ if ( results.elementAt(count2) instanceof WSSecurityEngineResult ) {
+ WSSecurityEngineResult securityResult =
+ (WSSecurityEngineResult)wshr.getResults().elementAt(count2);
+ if ( securityResult.get("principal") != null ) {
+ message.getQoSContext().put(Message.QOS_CTX_SECURITY_PRINCIPAL, securityResult.get("principal"));
+ }
+ }
+ }
+ }
+ }
+
+ }
+ }
+}
diff --git a/sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/Axis2ServiceServlet.java b/sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/Axis2ServiceServlet.java
new file mode 100644
index 0000000000..4ef71fafe6
--- /dev/null
+++ b/sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/Axis2ServiceServlet.java
@@ -0,0 +1,294 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tuscany.sca.binding.ws.axis2;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.MalformedURLException;
+import java.net.SocketException;
+import java.net.URI;
+import java.net.URL;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.Set;
+import java.util.Vector;
+
+import javax.servlet.RequestDispatcher;
+import javax.servlet.Servlet;
+import javax.servlet.ServletConfig;
+import javax.servlet.ServletContext;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.addressing.EndpointReference;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.transport.http.AxisServlet;
+import org.apache.axis2.transport.http.ListingAgent;
+import org.apache.axis2.transport.http.server.HttpUtils;
+
+/**
+ * This overrides the Servlet init of the AxisServlet so Tuscany can use
+ * a single Axis2 ConfigurationContext instance shared between AxisServlet
+ * instances for each SCA service with a ws binding.
+ * TODO: need to review if thats really what we want to be doing
+ *
+ * @version $Rev$ $Date$
+ */
+public class Axis2ServiceServlet extends AxisServlet {
+
+ protected TuscanyListingAgent agent;
+
+ private static final long serialVersionUID = 1L;
+ private static final ServletConfig DUMMY_CONFIG = createDummyServletConfig();
+
+//JIRA TUSCANY-1561 Port to Axis2 1.3
+ private ConfigurationContext tmpconfigContext;
+
+ public void init(ConfigurationContext configContext) {
+ this.tmpconfigContext = configContext;
+ try {
+ super.init(DUMMY_CONFIG);
+ } catch (ServletException e) {
+ throw new RuntimeException(e);
+ }
+ agent = new TuscanyListingAgent(configContext);
+ }
+
+ /**
+ * Override Axis2 Servlet method to avoid loop when init
+ * is called after servletConfig already initialized by
+ * this classes init(ConfigurationContext) method.
+ */
+ @Override
+ public void init() throws ServletException {
+ }
+
+ public void init(ServletConfig config) throws ServletException {
+ ServletContext servletContext = config.getServletContext();
+ servletContext.setAttribute(CONFIGURATION_CONTEXT, tmpconfigContext);
+ super.init(config);
+ }
+
+ /**
+ * We've setup the Servlet by passing in a ConfigurationContext on our init method
+ * override this method to just return that
+ */
+ @Override
+ protected ConfigurationContext initConfigContext(ServletConfig config) throws ServletException {
+ return this.tmpconfigContext;
+ }
+
+ @Override
+ public ServletConfig getServletConfig() {
+ return DUMMY_CONFIG;
+ }
+
+ @Override
+ public String getServletName() {
+ return "TuscanyAxis2Servlet";
+ }
+
+ /**
+ * The AxisServlet gets NPE during init without a ServletConfig so this is a mocked up one to prevent that.
+ */
+ private static ServletConfig createDummyServletConfig() {
+ ServletConfig sc = new ServletConfig() {
+
+ public String getServletName() {
+ return "TuscanyAxis2DummyServlet";
+ }
+
+ public ServletContext getServletContext() {
+ return new ServletContext() {
+
+ public ServletContext getContext(String uripath) {
+ return null;
+ }
+
+ @SuppressWarnings("unused") // it's on the Servlet 2.5 API so we need it
+ public String getContextPath() {
+ return null;
+ }
+
+ public int getMajorVersion() {
+ return 0;
+ }
+
+ public int getMinorVersion() {
+ return 0;
+ }
+
+ public String getMimeType(String file) {
+ return null;
+ }
+
+ public Set<?> getResourcePaths(String path) {
+ return Collections.emptySet();
+ }
+
+ public URL getResource(String path) throws MalformedURLException {
+ if("/".equals(path)) {
+ // HACK: To avoid NPE
+ return new URL("/axis2");
+ }
+ return null;
+ }
+
+ public InputStream getResourceAsStream(String path) {
+ return null;
+ }
+
+ public RequestDispatcher getRequestDispatcher(String path) {
+ return null;
+ }
+
+ public RequestDispatcher getNamedDispatcher(String arg0) {
+ return null;
+ }
+
+ public Servlet getServlet(String arg0) throws ServletException {
+ return null;
+ }
+
+ public Enumeration getServlets() {
+ return null;
+ }
+
+ public Enumeration getServletNames() {
+ return null;
+ }
+
+ public void log(String arg0) {
+ }
+
+ public void log(Exception arg0, String arg1) {
+ }
+
+ public void log(String arg0, Throwable arg1) {
+ }
+
+ public String getRealPath(String arg0) {
+ return null;
+ }
+
+ public String getServerInfo() {
+ return null;
+ }
+
+ public String getInitParameter(String arg0) {
+ return null;
+ }
+
+ public Enumeration getInitParameterNames() {
+ return null;
+ }
+
+ public Object getAttribute(String arg0) {
+ return null;
+ }
+
+ public Enumeration getAttributeNames() {
+ return null;
+ }
+
+ public void setAttribute(String arg0, Object arg1) {
+ }
+
+ public void removeAttribute(String arg0) {
+ }
+
+ public String getServletContextName() {
+ return null;
+ }
+ };
+ }
+
+ public String getInitParameter(String arg0) {
+ return null;
+ }
+
+ public Enumeration getInitParameterNames() {
+ return new Vector().elements();
+ }
+ };
+ return sc;
+ }
+
+ @Override
+ public void destroy() {
+ try {
+ super.destroy();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * Override the AxisServlet doGet to use the TuscanyListingAgent for ?wsdl
+ */
+ @Override
+ protected void doGet(HttpServletRequest request,
+ HttpServletResponse response) throws ServletException, IOException {
+
+ initContextRoot(request);
+
+ String query = request.getQueryString();
+ if ((query != null) && (query.indexOf("wsdl2") >= 0 ||
+ query.indexOf("wsdl") >= 0 || query.indexOf("xsd") >= 0 ||
+ query.indexOf("policy") >= 0)) {
+ agent.processListService(request, response);
+ } else {
+ super.doGet(request, response);
+ }
+ }
+
+ /**
+
+ /**
+ * Override the AxisServlet method so as to not add "/services" into the URL
+ * and to work with Tuscany service names. can go once moved to Axis2 1.3
+ */
+ @Override
+ public EndpointReference[] getEPRsForService(String serviceName, String ip) throws AxisFault {
+ //RUNNING_PORT
+ String port = (String) configContext.getProperty(ListingAgent.RUNNING_PORT);
+ if (port == null) {
+ port = "8080";
+ }
+ if (ip == null) {
+ try {
+ ip = HttpUtils.getIpAddress();
+ if (ip == null) {
+ ip = "localhost";
+ }
+ } catch (SocketException e) {
+//TUSCANY-1561 Port to Axis2 1.3
+// throw new AxisFault.(e);
+ throw AxisFault.makeFault(e);
+ }
+ }
+
+ URI epURI = URI.create("http://" + ip + ":" + port + "/" + serviceName).normalize();
+
+ return new EndpointReference[]{new EndpointReference(epURI.toString())};
+ }
+
+}
diff --git a/sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/AxisPolicyHelper.java b/sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/AxisPolicyHelper.java
new file mode 100644
index 0000000000..c5b1666e4f
--- /dev/null
+++ b/sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/AxisPolicyHelper.java
@@ -0,0 +1,79 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.tuscany.sca.binding.ws.axis2;
+
+import java.util.List;
+
+import javax.xml.namespace.QName;
+
+import org.apache.tuscany.sca.assembly.Binding;
+import org.apache.tuscany.sca.policy.Intent;
+import org.apache.tuscany.sca.policy.IntentAttachPoint;
+import org.apache.tuscany.sca.policy.PolicySet;
+import org.apache.tuscany.sca.policy.PolicySetAttachPoint;
+
+/**
+ * @version $Rev$ $Date$
+ */
+public class AxisPolicyHelper {
+
+ public static final String XMLNS_SCA_1_0 = "http://www.osoa.org/xmlns/sca/1.0";
+ public static final QName AUTHENTICATION_INTENT = new QName(XMLNS_SCA_1_0, "authentication");
+ public static final QName CONFIDENTIALITY_INTENT = new QName(XMLNS_SCA_1_0, "confidentiality");
+ public static final QName INTEGRITY_INTENT = new QName(XMLNS_SCA_1_0, "integrity");
+ public static final QName MTOM_INTENT = new QName(XMLNS_SCA_1_0, "MTOM");
+ public static final QName SOAP12_INTENT = new QName(XMLNS_SCA_1_0, "soap12");
+
+ public static PolicySet getPolicySet(Binding wsBinding, QName intentName) {
+ PolicySet returnPolicySet = null;
+
+ if (wsBinding instanceof PolicySetAttachPoint) {
+ PolicySetAttachPoint policiedBinding = (PolicySetAttachPoint)wsBinding;
+ for (PolicySet policySet : policiedBinding.getPolicySets()) {
+ for (Intent intent : policySet.getProvidedIntents()) {
+ if (intent.getName().equals(intentName)) {
+ returnPolicySet = policySet;
+ break;
+ }
+ }
+ }
+ }
+
+ return returnPolicySet;
+ }
+
+ public static boolean isIntentRequired(Binding wsBinding, QName intent) {
+ if (wsBinding instanceof IntentAttachPoint) {
+ List<Intent> intents = ((IntentAttachPoint)wsBinding).getRequiredIntents();
+ for (Intent i : intents) {
+ if (intent.equals(i.getName())) {
+ return true;
+ }
+ }
+ }
+ return getPolicySet(wsBinding, intent) != null;
+ }
+
+ public static boolean isRampartRequired(Binding wsBinding) {
+ return isIntentRequired(wsBinding, AUTHENTICATION_INTENT) || isIntentRequired(wsBinding, INTEGRITY_INTENT)
+ || isIntentRequired(wsBinding, CONFIDENTIALITY_INTENT);
+ }
+
+}
diff --git a/sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/TuscanyAxisConfigurator.java b/sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/TuscanyAxisConfigurator.java
new file mode 100644
index 0000000000..8b3a5122d9
--- /dev/null
+++ b/sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/TuscanyAxisConfigurator.java
@@ -0,0 +1,206 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tuscany.sca.binding.ws.axis2;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
+
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.Constants;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.context.ConfigurationContextFactory;
+import org.apache.axis2.deployment.DeploymentConstants;
+import org.apache.axis2.deployment.DeploymentErrorMsgs;
+import org.apache.axis2.deployment.DeploymentException;
+import org.apache.axis2.deployment.ModuleBuilder;
+import org.apache.axis2.deployment.URLBasedAxisConfigurator;
+import org.apache.axis2.description.AxisModule;
+import org.apache.axis2.description.Parameter;
+import org.apache.axis2.engine.AxisConfiguration;
+import org.apache.axis2.engine.AxisConfigurator;
+import org.apache.axis2.i18n.Messages;
+import org.apache.axis2.util.Loader;
+
+/**
+ * Helps configure Axis2 from a resource in binding.ws.axis2 instead of Axis2.xml
+ * <p/> TODO: Review: should there be a single global Axis ConfigurationContext
+ *
+ * @version $Rev$ $Date$
+ */
+public class TuscanyAxisConfigurator extends URLBasedAxisConfigurator implements AxisConfigurator {
+
+ /* these two fields are part of a temporary fix to solve problems that Maven has with including
+ * rampart-1.3.mar into the classpath and also at the time of Release 1.0 rampart-1.3.mar seems
+ * to pull in a SNAPSHOT version of rampart-project pom. Hence rampart.mar has been excluded
+ * as a Maven dependency and has been packed with this module
+ */
+ /************start of fix *********************************************************************/
+ private URL axis2_xml =
+ getResource("/org/apache/tuscany/sca/binding/ws/axis2/engine/config/axis2.xml");
+ private URL axis2_repository = null;
+ private URL rampart_mar_url =
+ getResource("/org/apache/tuscany/sca/binding/ws/axis2/engine/config/modules/rampart-1.3.mar");
+ /************** end of fix *************************************************************/
+
+ private boolean isRampartRequired;
+
+ public TuscanyAxisConfigurator(boolean isRampartRequired) throws AxisFault {
+ //super(TuscanyAxisConfigurator.class.getResource("/org/apache/tuscany/sca/binding/ws/axis2/engine/config/axis2.xml"),
+ // TuscanyAxisConfigurator.class.getResource("/org/apache/tuscany/sca/binding/ws/axis2/engine/config/modules/rampart.mar"));
+ super(getResource("/org/apache/tuscany/sca/binding/ws/axis2/engine/config/axis2.xml"),
+ null);
+ this.isRampartRequired = isRampartRequired;
+ }
+
+ private static URL getResource(final String name) {
+ return AccessController.doPrivileged(new PrivilegedAction<URL>() {
+ public URL run() {
+ return TuscanyAxisConfigurator.class.getResource(name);
+ }
+ });
+ }
+
+ public ConfigurationContext getConfigurationContext() throws AxisFault {
+ if (configContext == null) {
+ configContext = ConfigurationContextFactory.createConfigurationContext(this);
+ }
+ return configContext;
+ }
+
+ /* these three methods are part of a temporary fix to solve problems that Maven has with including
+ * rampart-1.3.mar into the classpath and also at the time of Release 1.0 rampart-1.3.mar seems
+ * to pull in a SNAPSHOT version of rampart-project pom. Hence rampart.mar has been excluded
+ * as a Maven dependency and has been packed with this module
+ */
+ /************start of fix *********************************************************************/
+ public AxisConfiguration getAxisConfiguration() throws AxisFault {
+ InputStream axis2xmlStream;
+ try {
+ if (axis2_xml == null) {
+ axis2xmlStream =
+ Loader.getResourceAsStream(DeploymentConstants.AXIS2_CONFIGURATION_RESOURCE);
+ } else {
+ axis2xmlStream = axis2_xml.openStream();
+ }
+ axisConfig = populateAxisConfiguration(axis2xmlStream);
+ if (isRampartRequired) {
+ axisConfig.addGlobalModuleRef("rampart");
+ }
+ if (axis2_repository == null) {
+ Parameter axis2repoPara = axisConfig.getParameter(DeploymentConstants.AXIS2_REPO);
+ if (axis2repoPara != null) {
+ String repoValue = (String) axis2repoPara.getValue();
+ if (repoValue != null && !"".equals(repoValue.trim())) {
+ if (repoValue.startsWith("file:/")) {
+ // we treat this case specially , by assuming file is
+ // located in the local machine
+ loadRepository(repoValue);
+ } else {
+ loadRepositoryFromURL(new URL(repoValue));
+ }
+ }
+ } else {
+ //log.info("No repository found , module will be loaded from classpath");
+ try {
+ loadFromClassPath();
+ } catch ( Exception e ) {
+ if (isRampartRequired) {
+ loadRampartModule();
+ }
+ }
+ }
+
+ } else {
+ loadRepositoryFromURL(axis2_repository);
+ }
+
+ } catch (IOException e) {
+ throw new AxisFault(e.getMessage());
+ }
+ axisConfig.setConfigurator(this);
+ return axisConfig;
+ }
+
+ public void loadRampartModule() throws DeploymentException {
+ try {
+ ClassLoader deploymentClassLoader =
+ org.apache.axis2.deployment.util.Utils.createClassLoader(
+ new URL[]{rampart_mar_url},
+ axisConfig.getModuleClassLoader(),
+ true,
+ (File) axisConfig.getParameterValue(Constants.Configuration.ARTIFACTS_TEMP_DIR));
+ final AxisModule module = new AxisModule();
+ module.setModuleClassLoader(deploymentClassLoader);
+ module.setParent(axisConfig);
+ //String moduleFile = fileUrl.substring(0, fileUrl.indexOf(".mar"));
+ if (module.getName() == null) {
+ module.setName(org.apache.axis2.util.Utils.getModuleName("rampart-1.3"));
+ module.setVersion(org.apache.axis2.util.Utils.getModuleVersion("rampart-1.3"));
+ }
+ populateModule(module, rampart_mar_url);
+ module.setFileName(rampart_mar_url);
+ // Allow privileged access to read properties. Requires PropertiesPermission read in
+ // security policy.
+ try {
+ AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
+ public Object run() throws IOException {
+ addNewModule(module, axisConfig);
+ return null;
+ }
+ });
+ } catch (PrivilegedActionException e) {
+ throw (AxisFault)e.getException();
+ }
+
+ org.apache.axis2.util.Utils.
+ calculateDefaultModuleVersion(axisConfig.getModules(), axisConfig);
+ axisConfig.validateSystemPredefinedPhases();
+ } catch (IOException e) {
+ throw new DeploymentException(e);
+ }
+ }
+
+ private void populateModule(AxisModule module, URL moduleUrl) throws DeploymentException {
+ try {
+ ClassLoader classLoader = module.getModuleClassLoader();
+ InputStream moduleStream = classLoader.getResourceAsStream("META-INF/module.xml");
+ if (moduleStream == null) {
+ moduleStream = classLoader.getResourceAsStream("meta-inf/module.xml");
+ }
+ if (moduleStream == null) {
+ throw new DeploymentException(
+ Messages.getMessage(
+ DeploymentErrorMsgs.MODULE_XML_MISSING, moduleUrl.toString()));
+ }
+ ModuleBuilder moduleBuilder = new ModuleBuilder(moduleStream, module, axisConfig);
+ moduleBuilder.populateModule();
+ } catch (IOException e) {
+ throw new DeploymentException(e);
+ }
+ }
+
+ /************** end of fix *************************************************************/
+
+}
diff --git a/sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/TuscanyDispatcher.java b/sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/TuscanyDispatcher.java
new file mode 100644
index 0000000000..34899a4af0
--- /dev/null
+++ b/sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/TuscanyDispatcher.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.binding.ws.axis2;
+
+import java.net.URI;
+import java.util.HashMap;
+
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.addressing.EndpointReference;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.context.MessageContext;
+import org.apache.axis2.description.AxisService;
+import org.apache.axis2.description.HandlerDescription;
+import org.apache.axis2.engine.AxisConfiguration;
+import org.apache.axis2.engine.RequestURIBasedDispatcher;
+import org.apache.axis2.util.JavaUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+/**
+ * A Tuscany specific Axis2 Dispatcher that enables using services
+ * exposed at the SCA defined service URI instead of /services/<serviceName>
+ *
+ * @version $Rev$ $Date$
+ */
+public class TuscanyDispatcher extends RequestURIBasedDispatcher {
+
+ public static final String NAME = "TuscanyDispatcher";
+ private static final Log log = LogFactory.getLog(RequestURIBasedDispatcher.class);
+ private static final boolean isDebugEnabled = log.isDebugEnabled();
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.apache.axis2.engine.AbstractDispatcher#findService(org.apache.axis2.context.MessageContext)
+ */
+ @Override
+ public AxisService findService(MessageContext messageContext) throws AxisFault {
+ EndpointReference toEPR = messageContext.getTo();
+
+ if (toEPR != null) {
+ if(isDebugEnabled){
+ log.debug("Checking for Service using target endpoint address : " + toEPR.getAddress());
+ }
+
+ String path = URI.create(toEPR.getAddress()).getPath();
+
+ ConfigurationContext configurationContext = messageContext.getConfigurationContext();
+ AxisConfiguration registry = configurationContext.getAxisConfiguration();
+
+ String serviceName = findAxisServiceName(registry, path);
+ return registry.getService(serviceName);
+
+ } else {
+ if(isDebugEnabled){
+ log.debug("Attempted to check for Service using null target endpoint URI");
+ }
+ return null;
+ }
+ }
+
+ @Override
+ public void initDispatcher() {
+ init(new HandlerDescription(NAME));
+ }
+
+ protected String findAxisServiceName(AxisConfiguration registry, String path) {
+ HashMap services = registry.getServices();
+ if (services == null) {
+ return null;
+ }
+ String[] parts = JavaUtils.split(path, '/');
+ String serviceName = "";
+ for (int i=parts.length-1; i>=0; i--) {
+ serviceName = parts[i] + serviceName;
+ if (services.containsKey(serviceName)) {
+ return serviceName;
+ }
+ serviceName = "/" + serviceName;
+ if (services.containsKey(serviceName)) {
+ return serviceName;
+ }
+ }
+
+ return null;
+ }
+
+}
diff --git a/sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/TuscanyListingAgent.java b/sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/TuscanyListingAgent.java
new file mode 100644
index 0000000000..8e2e40c753
--- /dev/null
+++ b/sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/TuscanyListingAgent.java
@@ -0,0 +1,235 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.tuscany.sca.binding.ws.axis2;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.wsdl.Definition;
+import javax.wsdl.Port;
+import javax.wsdl.Service;
+import javax.wsdl.extensions.soap.SOAPAddress;
+import javax.wsdl.extensions.soap12.SOAP12Address;
+import javax.xml.stream.FactoryConfigurationError;
+import javax.xml.stream.XMLOutputFactory;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamWriter;
+
+import org.apache.axiom.attachments.utils.IOUtils;
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.Constants;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.deployment.DeploymentConstants;
+import org.apache.axis2.description.AxisDescription;
+import org.apache.axis2.description.AxisService;
+import org.apache.axis2.description.Parameter;
+import org.apache.axis2.description.PolicyInclude;
+import org.apache.axis2.transport.http.ListingAgent;
+import org.apache.axis2.util.ExternalPolicySerializer;
+import org.apache.axis2.util.JavaUtils;
+import org.apache.axis2.wsdl.WSDLConstants;
+import org.apache.neethi.Policy;
+import org.apache.neethi.PolicyRegistry;
+import org.apache.ws.commons.schema.XmlSchema;
+
+/**
+ * A Tuscany specific Axis2 ListingAgent as the Axis2 one does not work
+ * with the Tuscany service names which include slash ('/') characters.
+ * Unfortunately it ends up having to copy a fair amount of Axis2 code to do this.
+ *
+ * @version $Rev$ $Date$
+ */
+public class TuscanyListingAgent extends ListingAgent {
+
+ private static final String LIST_SINGLE_SERVICE_JSP_NAME =
+ "listSingleService.jsp";
+
+ public TuscanyListingAgent(ConfigurationContext aConfigContext) {
+ super(aConfigContext);
+ }
+
+ /**
+ * This method overrides the Axis2 listing agent's computation of the
+ * service name.
+ */
+ @Override
+ public String extractServiceName(String urlString) {
+ String serviceName = findAxisServiceName(urlString);
+ setContextRoot(urlString, serviceName);
+ return serviceName;
+ }
+
+ private String findAxisServiceName(String path) {
+ HashMap services = configContext.getAxisConfiguration().getServices();
+ if (services == null) {
+ return null;
+ }
+ String[] parts = JavaUtils.split(path, '/');
+ String serviceName = "";
+ for (int i=parts.length-1; i>=0; i--) {
+ serviceName = parts[i] + serviceName;
+ if (services.containsKey(serviceName)) {
+ return serviceName;
+ }
+ serviceName = "/" + serviceName;
+ if (services.containsKey(serviceName)) {
+ return serviceName;
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * Hack for Tuscany to get ?wsdl working with Tuscany service names
+ * Can go once moved up to Axis2 1.3
+ */
+ private void setContextRoot(String filePart, String serviceName) {
+ String contextRoot = configContext.getContextRoot();
+ if (contextRoot != null && contextRoot.length() > 0) {
+ if (contextRoot.equals("/")) {
+ configContext.setServicePath("/");
+ } else {
+ int i = filePart.indexOf(contextRoot) + contextRoot.length();
+ int j = filePart.lastIndexOf(serviceName);
+ if (i>=j || (i+1 == j)) {
+ configContext.setServicePath("/");
+ } else {
+ String mapping = filePart.substring(i+1, j);
+ configContext.setServicePath(mapping);
+ }
+ }
+ configContext.setContextRoot(contextRoot);
+ }
+ }
+
+ private String extractHostAndPort(String filePart, boolean isHttp) {
+ int ipindex = filePart.indexOf("//");
+ String ip = null;
+ if (ipindex >= 0) {
+ ip = filePart.substring(ipindex + 2, filePart.length());
+ int seperatorIndex = ip.indexOf(":");
+ int slashIndex = ip.indexOf("/");
+ String port;
+ if (seperatorIndex >= 0) {
+ port = ip.substring(seperatorIndex + 1, slashIndex);
+ ip = ip.substring(0, seperatorIndex);
+ } else {
+ ip = ip.substring(0, slashIndex);
+ port = "80";
+ }
+ if (isHttp) {
+ configContext.setProperty(RUNNING_PORT, port);
+ }
+ }
+ return ip;
+ }
+
+ private Policy findPolicy(String id, AxisDescription des) {
+
+ List policyElements = des.getPolicyInclude().getPolicyElements();
+ PolicyRegistry registry = des.getPolicyInclude().getPolicyRegistry();
+
+ Object policyComponent;
+
+ Policy policy = registry.lookup(id);
+
+ if (policy != null) {
+ return policy;
+ }
+
+ for (Iterator iterator = policyElements.iterator(); iterator.hasNext();) {
+ policyComponent = iterator.next();
+
+ if (policyComponent instanceof Policy) {
+ // policy found for the id
+
+ if (id.equals(((Policy) policyComponent).getId())) {
+ return (Policy) policyComponent;
+ }
+ }
+ }
+
+ AxisDescription child;
+
+ for (Iterator iterator = des.getChildren(); iterator.hasNext();) {
+ child = (AxisDescription) iterator.next();
+ policy = findPolicy(id, child);
+
+ if (policy != null) {
+ return policy;
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * Hack to get ?wsdl working with soap 1.2
+ * Fixed in Axis2 1.3
+ */
+ private void patchSOAP12Port(AxisService as) throws AxisFault {
+ Parameter wsld4jdefinition = as.getParameter(WSDLConstants.WSDL_4_J_DEFINITION);
+ Definition definition = (Definition) wsld4jdefinition.getValue();
+ setPortAddress(definition, null, as);
+ }
+
+ /**
+ * This is a copy of the AxisService setPortAddress patched to work with SOAP 1.2 Addresses
+ * Fixed in Axis2 1.3
+ */
+ private void setPortAddress(Definition definition, String requestIP, AxisService axisService) throws AxisFault {
+ Iterator serviceItr = definition.getServices().values().iterator();
+ while (serviceItr.hasNext()) {
+ Service serviceElement = (Service) serviceItr.next();
+ Iterator portItr = serviceElement.getPorts().values().iterator();
+ while (portItr.hasNext()) {
+ Port port = (Port) portItr.next();
+ List list = port.getExtensibilityElements();
+ for (int i = 0; i < list.size(); i++) {
+ Object extensibilityEle = list.get(i);
+ String locationURI = null;
+ if (requestIP == null) {
+ locationURI = axisService.getEPRs()[0];
+ } else {
+// can't do this as the method's not visible, but Tuscany doesn't use this path anyway
+// locationURI = axisService.getEPRs(requestIP)[0]);
+ }
+ if (extensibilityEle instanceof SOAPAddress) {
+ ((SOAPAddress) extensibilityEle).setLocationURI(locationURI);
+ } else if (extensibilityEle instanceof SOAP12Address) {
+ ((SOAP12Address) extensibilityEle).setLocationURI(locationURI);
+ }
+ }
+ }
+ }
+ }
+
+}
diff --git a/sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/WSBindingDefinitionsProvider.java b/sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/WSBindingDefinitionsProvider.java
new file mode 100644
index 0000000000..5254a5716c
--- /dev/null
+++ b/sandbox/sebastien/java/sca-node/modules/binding-ws-axis2/src/main/java/org/apache/tuscany/sca/binding/ws/axis2/WSBindingDefinitionsProvider.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.binding.ws.axis2;
+
+import java.net.URI;
+import java.net.URL;
+import java.security.AccessController;
+import java.security.PrivilegedExceptionAction;
+
+import org.apache.tuscany.sca.contribution.processor.URLArtifactProcessor;
+import org.apache.tuscany.sca.contribution.processor.URLArtifactProcessorExtensionPoint;
+import org.apache.tuscany.sca.contribution.service.ContributionReadException;
+import org.apache.tuscany.sca.core.ExtensionPointRegistry;
+import org.apache.tuscany.sca.definitions.SCADefinitions;
+import org.apache.tuscany.sca.provider.SCADefinitionsProvider;
+import org.apache.tuscany.sca.provider.SCADefinitionsProviderException;
+
+/**
+ * Provider for Policy Intents and PolicySet definitions related to security
+ *
+ * @version $Rev$ $Date$
+ */
+public class WSBindingDefinitionsProvider implements SCADefinitionsProvider {
+ private String definitionsFile = "org/apache/tuscany/sca/binding/ws/axis2/definitions.xml";
+ URLArtifactProcessor urlArtifactProcessor = null;
+
+ public WSBindingDefinitionsProvider(ExtensionPointRegistry registry) {
+ URLArtifactProcessorExtensionPoint documentProcessors = registry.getExtensionPoint(URLArtifactProcessorExtensionPoint.class);
+ urlArtifactProcessor = (URLArtifactProcessor)documentProcessors.getProcessor(SCADefinitions.class);
+ }
+
+ public SCADefinitions getSCADefinition() throws SCADefinitionsProviderException {
+ final URL definitionsFileUrl = getClass().getClassLoader().getResource(definitionsFile);
+ SCADefinitions scaDefn = null;
+ try {
+ final URI uri = new URI(definitionsFile);
+ // Allow bindings to read properties. Requires PropertyPermission read in security policy.
+ scaDefn = AccessController.doPrivileged(new PrivilegedExceptionAction<SCADefinitions>() {
+ public SCADefinitions run() throws ContributionReadException {
+ return (SCADefinitions)urlArtifactProcessor.read(null, uri, definitionsFileUrl);
+ }
+ });
+ } catch (Exception e) {
+ throw new SCADefinitionsProviderException(e);
+ }
+ return scaDefn;
+ }
+
+}