Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Licensed to the Apache Software Foundation (ASF) under one
   * or more contributor license agreements.  See the NOTICE file
   * distributed with this work for additional information
   * regarding copyright ownership.  The ASF licenses this file
   * to you under the Apache License, Version 2.0 (the
   * "License"); you may not use this file except in compliance
   * with the License.  You may obtain a copy of the License at
   *
  *   http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing,
  * software distributed under the License is distributed on an
  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  * 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.jaxws;
 
 import java.net.URL;
 import java.util.List;
 
 
Uses JAXWS Dispatch to invoke a remote web service

Version:
$Rev: 960020 $ $Date: 2010-07-02 18:12:28 +0300 (Fri, 02 Jul 2010) $
 
 public class JAXWSBindingInvoker implements InvokerDataExchangeSemantics {
     private final static String SCA11_TUSCANY_NS = "http://tuscany.apache.org/xmlns/sca/1.1";
 
     public static final String WSA_FINAL_NAMESPACE = "http://www.w3.org/2005/08/addressing";
     public static final QName QNAME_WSA_FROM = new QName("From""wsa");
     public static final QName QNAME_WSA_TO = new QName("To""wsa");
     public static final QName QNAME_WSA_ACTION = new QName("Action""wsa");
     public static final QName QNAME_WSA_RELATESTO = new QName("RelatesTo""wsa");
     private static final QName submissionWSAWNS = new QName("http://schemas.xmlsoap.org/ws/2004/08/addressing",
                                                             .getLocalPart());
     private static final QName finalWSANS = new QName("http://www.w3.org/2005/08/addressing",
                                                       .getLocalPart());
     private static final QName finalWSAWNS = new QName("http://www.w3.org/2006/05/addressing/wsdl",
                                                        .getLocalPart());
     private static final QName finalWSAMNS = new QName("http://www.w3.org/2007/05/addressing/metadata",
                                                        .getLocalPart());
 
     public static final String TUSCANY_PREFIX = "tuscany";
     public static final QName CALLBACK_ID_REFPARM_QN = new QName("CallbackID");
     public static final QName CONVERSATION_ID_REFPARM_QN =
         new QName("ConversationID");
 
     private Dispatch<SOAPMessagedispatch;
     private MessageFactory messageFactory;
     private Operation operation;
     private WebServiceBinding wsBinding;
    public JAXWSBindingInvoker(Operation operation,
                               WebServiceFeature[] features,
                               MessageFactory messageFactory,
                               WebServiceBinding wsBinding,
                               RuntimeEndpointReference endpointReference) {
        this. = messageFactory;
        this. = operation;
        this. = wsBinding;
        this. = endpointReference;
        this. = createDispatch(wsBinding);
    }
    private Dispatch<SOAPMessagecreateDispatch(WebServiceBinding wsBinding) {
        URL wsdlLocation = null;
        try {
            wsdlLocation = new URL(wsBinding.getGeneratedWSDLDocument().getDocumentBaseURI());
        } catch (Exception e) {
            try {
                if (wsBinding.getUserSpecifiedWSDLDefinition().getLocation() != null) {
                    wsdlLocation = wsBinding.getUserSpecifiedWSDLDefinition().getLocation().toURL();
                }
            } catch (MalformedURLException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
        QName serviceName = null;
        QName portName = null;
        Service service = null;
        if (wsdlLocation != null) {
            serviceName = wsBinding.getServiceName();
            portName = new QName(serviceName.getNamespaceURI(), wsBinding.getPortName());
            service = Service.create(wsdlLocationserviceName);
        } else {
            serviceName = wsBinding.getService().getQName();
            portName = new QName(serviceName.getNamespaceURI(), wsBinding.getPort().getName());
            service = Service.create(serviceName);
            service.addPort(portName.wsBinding.getURI());
        }
        return service.createDispatch(portNameSOAPMessage.class..);
    }
    public Message invoke(Message msg) {
        try {
            SOAPMessage resp = invokeTarget(msg);
            SOAPBody body = resp.getSOAPBody();
            if (body != null) {
                SOAPFault fault = body.getFault();
                if (fault != null) {
                    // setFault(msg, fault);
                } else {
                    // The 1st child element
                    msg.setBody(body.getChildElements().next());
                }
            }
        } catch (SOAPFaultException e) {
            setFault(msge);
        } catch (WebServiceException e) {
            msg.setFaultBody(e);
        } catch (SOAPException e) {
            msg.setFaultBody(e);
        } catch (Throwable e) {
            msg.setFaultBody(e);
        }
        return msg;
    }
    private void setFault(Message msgSOAPFaultException e) {
        SOAPFault fault = e.getFault();
        Detail detail = fault.getDetail();
        if (detail != null) {
            for (Iterator i = detail.getDetailEntries(); i.hasNext();) {
                DetailEntry entry = (DetailEntry)i.next();
                FaultException fe = new FaultException(e.getMessage(), entry.getFirstChild(), e);
                fe.setFaultName(entry.getElementQName());
                msg.setFaultBody(fe);
            }
        }
    }
    protected String getSOAPAction(String operationName) {
        Binding binding = .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();
                        } else if (o2 instanceof SOAP12Operation) {
                            return ((SOAP12Operation)o2).getSoapActionURI();
                        }
                    }
                }
            }
        }
        return null;
    }
    protected SOAPMessage invokeTarget(Message msgthrows SOAPException {
        SOAPMessage soapMessage = .createMessage();
        SOAPPart soapPart = soapMessage.getSOAPPart();
        javax.xml.soap.SOAPEnvelope envelope = soapPart.getEnvelope();
        String action = getSOAPAction(.getName());
        setHeaders(envelope.getHeader(), msgaction);
        javax.xml.soap.SOAPBody body = envelope.getBody();
        Object[] args = (Object[])msg.getBody();
        // In the unit test the owner doc is null
        // so explicitly adopt the node instead
        // body.addDocument(((Node)args[0]).getOwnerDocument());
        Node msgNode = body.getOwnerDocument().importNode((Node)args[0], true);
        body.appendChild(msgNode);
        soapMessage.saveChanges();
        if (.isNonBlocking()) {
            .invokeOneWay(soapMessage);
            return null;
        }
        if (action != null) {
        }
        SOAPMessage response = .invoke(soapMessage);
        return response;
    }
    protected void setHeaders(SOAPHeader shMessage msgString actionthrows SOAPException {
        Endpoint callbackEndpoint = msg.getFrom().getCallbackEndpoint();
        // add WS-Addressing header for the invocation of a bidirectional
        // service
        // FIXME: is there any way to use the Axis2 addressing support for this?
        if (callbackEndpoint != null) {
            // // Load the actual callback endpoint URI into an Axis EPR ready
            // to form the content of the wsa:From header
            // EndpointReference fromEPR = new
            // EndpointReference(callbackEndpoint.getBinding().getURI());
            //
            // addWSAFromHeader(sh, fromEPR);
            SOAPHeaderElement fromH = sh.addHeaderElement();
            fromH.setTextContent(callbackEndpoint.getBinding().getURI());
            addWSAActionHeader(shaction);
            // requestMC.setFrom(fromEPR);
        } // end if
        String toAddress = getToAddress(msg);
        // requestMC.setTo( new EndpointReference(toAddress) );
        if (isInvocationForCallback(msg)) {
            addWSAToHeader(shtoAddressmsg);
            addWSAActionHeader(shaction);
            addWSARelatesTo(shmsg);
        } // end if
    }
    private String getToAddress(Message msgthrows ServiceRuntimeException {
        String address = null;
        // if target endpoint was not specified when this invoker was created,
        // use dynamically specified target endpoint passed in with the message
        String to = getPortLocation();
        if (to == null) {
            Endpoint ep = msg.getTo();
            if (ep != null && ep.getBinding() != null) {
                address = ep.getBinding().getURI();
            } else {
                throw new ServiceRuntimeException(
                                                  "[BWS20025] Unable to determine destination endpoint for endpoint reference " + );
            }
        } else {
            address = to;
        }
        return address;
    } // end method getToAddress
    protected String getPortLocation(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;
    }
    // private void addWSAFromHeader( SOAPHeader sh, EndpointReference fromEPR )
    // throws AxisFault {
    // OMElement epr = EndpointReferenceHelper.toOM(sh.getOMFactory(),
    // fromEPR,
    // QNAME_WSA_FROM,
    // AddressingConstants.Final.WSA_NAMESPACE);
    // sh.addChild(epr);
    //
    // } // end method addWSAFromHeader
    private static String WS_REF_PARMS = "WS_REFERENCE_PARAMETERS";
    private void addWSAToHeader(SOAPHeader shString addressMessage msgthrows SOAPException {
        // Create wsa:To header which is required by ws-addressing spec
        // OMElement wsaToOM = sh.getOMFactory().createOMElement(QNAME_WSA_TO);
        // wsaToOM.setText( address );
        // sh.addChild(wsaToOM);
        SOAPHeaderElement toH = sh.addHeaderElement();
        toH.setTextContent(address);
        // Deal with Reference Parameters, if present - copy to the header
        // without the wsa:ReferenceParameters wrapper
        // OMElement refParms = (OMElement) msg.getHeaders().get(WS_REF_PARMS);
        // Iterator ces = sh.getChildElements(new QName(WSA_FINAL_NAMESPACE,
        // WS_REF_PARMS));
        Iterator<SOAPElementces = sh.getChildElements();
        while (ces.hasNext()) {
            SOAPElement se = ces.next();
            if (.equals(se.getElementQName().getLocalPart())) {
                // if( refParms != null ) {
                Iterator<SOAPElementchildren = se.getChildElements();
                while (children.hasNext()) {
                    SOAPElement node = (SOAPElement)children.next();
                    toH.addChildElement(node);
                }
                // } // end if
            }
        }
    } // end method addWSAActionHeader
    private void addWSAActionHeader(SOAPHeader shString actionthrows SOAPException {
        // Create wsa:Action header which is required by ws-addressing spec
        if (action == null) {
            javax.wsdl.Operation op = portType.getOperation(.getName(), nullnull);
            action = getActionFromInputElement(.getGeneratedWSDLDocument(), portTypeopop.getInput());
        }
        // OMElement actionOM =
        // sh.getOMFactory().createOMElement(QNAME_WSA_ACTION);
        // actionOM.setText(action == null ? "" : action);
        // sh.addChild(actionOM);
        SOAPHeaderElement actionH = sh.addHeaderElement();
        actionH.setTextContent(action == null ? "" : action);
    } // end method addWSAActionHeader
    private static String WS_MESSAGE_ID = "WS_MESSAGE_ID";
    protected static String SCA_CALLBACK_REL = "http://docs.oasis-open.org/opencsa/sca-bindings/ws/callback";

    
Adds a wsa:RelatesTo SOAP header if the incoming invocation had a wsa:MessageID SOAP header present - note that OASIS SCA requires that the RelationshipType attribute is set to a particular SCA value

Parameters:
sh - the SOAP headers
msg - the message
Throws:
javax.xml.soap.SOAPException
    private void addWSARelatesTo(SOAPHeader shMessage msgthrows SOAPException {
        String idValue = (String)msg.getHeaders().get();
        if (idValue != null) {
            SOAPHeaderElement relatesToH = sh.addHeaderElement();
            relatesToH.addAttribute(new QName(null"RelationshipType"), );
            relatesToH.setTextContent(idValue);
            // OMElement relatesToOM = sh.getOMFactory().createOMElement(
            // QNAME_WSA_RELATESTO );
            // OMAttribute relType =
            // sh.getOMFactory().createOMAttribute("RelationshipType", null,
            // SCA_CALLBACK_REL);
            // relatesToOM.addAttribute( relType );
            // relatesToOM.setText( idValue );
            // sh.addChild( relatesToOM );
        }
    } // end method addWSARelatesTo

    
Indicates if the invocation is for the callback of a bidirectional service

Parameters:
msg the Message
Returns:
true if the invocation is for the callback of a bidirectional service, false otherwise
    private boolean isInvocationForCallback(Message msg) {
        org.apache.tuscany.sca.assembly.EndpointReference fromEPR = msg.getFrom();
        if (fromEPR != null) {
            ComponentReference ref = fromEPR.getReference();
            if (ref != null)
                return ref.isForCallback();
        } // end if
        return false;
    } // end method isInvocationForCallback

    
getActionFromInputElement

Parameters:
def the wsdl:definitions which contains the wsdl:portType
wsdl4jPortType the wsdl:portType which contains the wsdl:operation
op the wsdl:operation which contains the input element
input the input element to be examined to generate the wsa:Action
Returns:
either the wsaw:Action from the input element or an action generated using the DefaultActionPattern
    public static String getActionFromInputElement(Definition def,
                                                   PortType wsdl4jPortType,
                                                   javax.wsdl.Operation op,
                                                   Input input) {
        String result = getWSAWActionExtensionAttribute(input);
        if (result == null) {
            result = generateActionFromInputElement(defwsdl4jPortTypeopinput);
        }
        return result;
    }
        // Search first for a wsaw:Action using the submission namespace
        Object attribute = ae.getExtensionAttribute();
        // Then if that did not exist one using the w3c WSAM namespace
        if (attribute == null) {
            attribute = ae.getExtensionAttribute();
        }
        // Then if that did not exist one using the w3c WSAW namespace
        // (for backwards compat reasons)
        if (attribute == null) {
            attribute = ae.getExtensionAttribute();
        }
        // Then finally if that did not exist, try the 2005/08 NS
        // (Included here because it's needed for Apache Muse)
        if (attribute == null) {
            attribute = ae.getExtensionAttribute();
        }
        // wsdl4j may return a String, QName or a List of either
        // If it is a list, extract the first element
        if (attribute instanceof List) {
            List l = (List)attribute;
            if (l.size() > 0) {
                attribute = l.get(0);
            } else {
                attribute = null;
            }
        }
        // attribute must now be a QName or String or null
        // If it is a QName, take the LocalPart as a String
        if (attribute instanceof QName) {
            QName qn = (QName)attribute;
            attribute = qn.getLocalPart();
        }
        if ((attribute instanceof String)) {
            String result = (String)attribute;
            return result;
        } else {
            return null;
        }
    }

    
Generate the Action for an Input using the Default Action Pattern

Pattern is defined as [target namespace][delimiter][port type name][delimiter][input name]

Parameters:
def is required to obtain the targetNamespace
wsdl4jPortType is required to obtain the portType name
op is required to generate the input name if not explicitly specified
input is required for its name if specified
Returns:
a wsa:Action value based on the Default Action Pattern and the provided objects
    public static String generateActionFromInputElement(Definition def,
                                                        PortType wsdl4jPortType,
                                                        javax.wsdl.Operation op,
                                                        Input input) {
        // Get the targetNamespace of the wsdl:definitions
        String targetNamespace = def.getTargetNamespace();
        // Determine the delimiter. Per the spec: 'is ":" when the [target
        // namespace] is a URN, otherwise "/".
        // Note that for IRI schemes other than URNs which aren't path-based
        // (i.e. those that outlaw the "/"
        // character), the default action value may not conform to the rules of
        // the IRI scheme. Authors
        // are advised to specify explicit values in the WSDL in this case.'
        String delimiter = ;
        if (targetNamespace.toLowerCase().startsWith()) {
            delimiter = ;
        }
        // Get the portType name (as a string to be included in the action)
        String portTypeName = wsdl4jPortType.getQName().getLocalPart();
        // Get the name of the input element (and generate one if none
        // explicitly specified)
        String inputName = getNameFromInputElement(opinput);
        // Append the bits together
        StringBuffer sb = new StringBuffer();
        sb.append(targetNamespace);
        // Deal with the problem that the targetNamespace may or may not have a
        // trailing delimiter
        if (!targetNamespace.endsWith(delimiter)) {
            sb.append(delimiter);
        }
        sb.append(portTypeName);
        sb.append(delimiter);
        sb.append(inputName);
        // Resolve the action from the StringBuffer
        String result = sb.toString();
        return result;
    }

    
Get the name of the specified Input element using the rules defined in WSDL 1.1 Section 2.4.5 http://www.w3.org/TR/wsdl#_names
    private static String getNameFromInputElement(javax.wsdl.Operation opInput input) {
        // Get the name from the input element if specified.
        String result = input.getName();
        // If not we'll have to generate it.
        if (result == null) {
            // If Request-Response or Solicit-Response do something special per
            // WSDL 1.1 Section 2.4.5
            OperationType operationType = op.getStyle();
            if (null != operationType) {
                if (operationType.equals(.)) {
                    result = op.getName() + ;
                } else if (operationType.equals(.)) {
                    result = op.getName() + ;
                }
            }
            // If the OperationType was not available for some reason, assume
            // on-way or notification
            if (result == null) {
                result = op.getName();
            }
        }
        return result;
    }
    private static final String URN = "urn";
    private static final String SLASH = "/";
    private static final String COLON = ":";
    private static final String REQUEST = "Request";
    private static final String RESPONSE = "Response";
    public boolean allowsPassByReference() {
        return true;
    }
New to GrepCode? Check out our FAQ X