Example usage for javax.xml.soap SOAPEnvelope getHeader

List of usage examples for javax.xml.soap SOAPEnvelope getHeader

Introduction

In this page you can find the example usage for javax.xml.soap SOAPEnvelope getHeader.

Prototype

public SOAPHeader getHeader() throws SOAPException;

Source Link

Document

Returns the SOAPHeader object for this SOAPEnvelope object.

Usage

From source file:org.jasig.portal.security.provider.saml.SAMLDelegatedAuthenticationService.java

private Document createSOAPFaultDocument(String faultString) throws SOAPException {
    MessageFactory factory = MessageFactory.newInstance();
    SOAPMessage message = factory.createMessage();
    SOAPPart sp = message.getSOAPPart();
    SOAPEnvelope se = sp.getEnvelope();
    se.setPrefix(SOAP_PREFIX);//from   w w w.  j av a2s  . c o  m
    se.getHeader().detachNode();
    se.addHeader();
    se.getBody().detachNode();
    SOAPBody body = se.addBody();
    SOAPFault fault = body.addFault();
    Name faultCode = se.createName("Client", null, SOAPConstants.URI_NS_SOAP_ENVELOPE);
    fault.setFaultCode(faultCode);
    fault.setFaultString(faultString);
    return se.getOwnerDocument();
}

From source file:it.cnr.icar.eric.common.SOAPMessenger.java

/** Send a SOAP request to the registry server. Main entry point for
 * this class. If credentials have been set on the registry connection,
 * they will be used to sign the request.
 *
 * @param requestString/* w w  w.  ja  va2s . co m*/
 *     String that will be placed in the body of the
 *     SOAP message to be sent to the server
 *
 * @param attachments
 *     HashMap consisting of entries each of which
 *     corresponds to an attachment where the entry key is the ContentId
 *     and the entry value is a javax.activation.DataHandler of the
 *     attachment. A parameter value of null means no attachments.
 *
 * @return
 *     RegistryResponseHolder that represents the response from the
 *     server
 */
@SuppressWarnings("unchecked")
public RegistryResponseHolder sendSoapRequest(String requestString, Map<?, ?> attachments)
        throws JAXRException {
    boolean logRequests = Boolean.valueOf(
            CommonProperties.getInstance().getProperty("eric.common.soapMessenger.logRequests", "false"))
            .booleanValue();

    if (logRequests) {
        PrintStream requestLogPS = null;
        try {
            requestLogPS = new PrintStream(
                    new FileOutputStream(java.io.File.createTempFile("SOAPMessenger_requestLog", ".xml")));
            requestLogPS.println(requestString);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (requestLogPS != null) {
                requestLogPS.close();
            }
        }
    }

    // =================================================================

    //        // Remove the XML Declaration, if any
    //        if (requestString.startsWith("<?xml")) {
    //            requestString = requestString.substring(requestString.indexOf("?>")+2).trim();
    //        }
    //
    //        StringBuffer soapText = new StringBuffer(
    //                "<soap-env:Envelope xmlns:soap-env=\"http://schemas.xmlsoap.org/soap/envelope/\">");
    //
    //      soapText.append("<soap-env:Header>\n");
    //      // tell server about our superior SOAP Fault capabilities
    //      soapText.append("<");
    //      soapText.append(BindingUtility.SOAP_CAPABILITY_HEADER_LocalName);
    //      soapText.append(" xmlns='");
    //      soapText.append(BindingUtility.SOAP_CAPABILITY_HEADER_Namespace);
    //      soapText.append("'>");
    //      soapText.append(BindingUtility.SOAP_CAPABILITY_ModernFaultCodes);
    //      soapText.append("</");
    //      soapText.append(BindingUtility.SOAP_CAPABILITY_HEADER_LocalName);
    //      soapText.append(">\n");
    //      soapText.append("</soap-env:Header>\n");

    //      soapText.append("<soap-env:Body>\n");
    //        soapText.append(requestString);
    //        soapText.append("</soap-env:Body>");
    //        soapText.append("</soap-env:Envelope>");

    MessageFactory messageFactory;
    SOAPMessage message = null;
    SOAPPart sp = null;
    SOAPEnvelope se = null;
    SOAPBody sb = null;
    SOAPHeader sh = null;

    if (log.isTraceEnabled()) {
        log.trace("requestString=\"" + requestString + "\"");
    }
    try {

        messageFactory = MessageFactory.newInstance();
        message = messageFactory.createMessage();

        sp = message.getSOAPPart();
        se = sp.getEnvelope();
        sb = se.getBody();
        sh = se.getHeader();

        /*
         * <soap-env:Envelope xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/">
         *       <soap-env:Header>
         *          <capabilities xmlns="urn:freebxml:registry:soap">urn:freebxml:registry:soap:modernFaultCodes</capabilities>
         *
         * change with explicit namespace
         *          <ns1:capabilities xmlns:ns1="urn:freebxml:registry:soap">urn:freebxml:registry:soap:modernFaultCodes</ns1:capabilities>
                
         */
        SOAPHeaderElement capabilityElement = sh
                .addHeaderElement(se.createName(BindingUtility.SOAP_CAPABILITY_HEADER_LocalName, "ns1",
                        BindingUtility.SOAP_CAPABILITY_HEADER_Namespace));
        //           capabilityElement.addAttribute(
        //                 se.createName("xmlns"), 
        //                 BindingUtility.SOAP_CAPABILITY_HEADER_Namespace);
        capabilityElement.setTextContent(BindingUtility.SOAP_CAPABILITY_ModernFaultCodes);

        /*
         * body
         */

        // Remove the XML Declaration, if any
        if (requestString.startsWith("<?xml")) {
            requestString = requestString.substring(requestString.indexOf("?>") + 2).trim();
        }

        // Generate DOM Document from request xml string
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        builderFactory.setNamespaceAware(true);
        InputStream stream = new ByteArrayInputStream(requestString.getBytes("UTF-8"));

        // Inject request into body
        sb.addDocument(builderFactory.newDocumentBuilder().parse(stream));

        // Is it never the case that there attachments but no credentials
        if ((attachments != null) && !attachments.isEmpty()) {
            addAttachments(message, attachments);
        }

        if (credentialInfo == null) {
            throw new JAXRException(resourceBundle.getString("message.credentialInfo"));
        }

        WSS4JSecurityUtilSAML.signSOAPEnvelopeOnClientSAML(se, credentialInfo);

        SOAPMessage response = send(message);

        // Check to see if the session has expired
        // by checking for an error response code
        // TODO: what error code to we look for?
        if (isSessionExpired(response)) {
            credentialInfo.sessionId = null;
            // sign the SOAPMessage this time
            // TODO: session - add method to do the signing
            // signSOAPMessage(msg);
            // send signed message
            // SOAPMessage response = send(msg);
        }

        // Process the main SOAPPart of the response
        //check for soapfault and throw RegistryException
        SOAPFault fault = response.getSOAPBody().getFault();
        if (fault != null) {
            throw createRegistryException(fault);
        }

        Reader reader = processResponseBody(response, "Response");

        RegistryResponseType ebResponse = null;

        try {
            Object obj = BindingUtility.getInstance().getJAXBContext().createUnmarshaller()
                    .unmarshal(new InputSource(reader));

            if (obj instanceof JAXBElement<?>)
                // if Element: take ComplexType from Element
                obj = ((JAXBElement<RegistryResponseType>) obj).getValue();

            ebResponse = (RegistryResponseType) obj;
        } catch (Exception x) {
            log.error(CommonResourceBundle.getInstance().getString("message.FailedToUnmarshalServerResponse"),
                    x);
            throw new JAXRException(resourceBundle.getString("message.invalidServerResponse"));
        }

        // Process the attachments of the response if any
        HashMap<String, Object> responseAttachments = processResponseAttachments(response);

        return new RegistryResponseHolder(ebResponse, responseAttachments);

    } catch (SAXException e) {
        throw new JAXRException(e);

    } catch (ParserConfigurationException e) {
        throw new JAXRException(e);

    } catch (UnsupportedEncodingException x) {
        throw new JAXRException(x);

    } catch (MessagingException x) {
        throw new JAXRException(x);

    } catch (FileNotFoundException x) {
        throw new JAXRException(x);

    } catch (IOException e) {
        throw new JAXRException(e);

    } catch (SOAPException x) {
        x.printStackTrace();
        throw new JAXRException(resourceBundle.getString("message.cannotConnect"), x);

    } catch (TransformerConfigurationException x) {
        throw new JAXRException(x);

    } catch (TransformerException x) {
        throw new JAXRException(x);
    }
}

From source file:com.twinsoft.convertigo.engine.translators.WebServiceTranslator.java

public Object buildOutputData(Context context, Object convertigoResponse) throws Exception {
    Engine.logBeans.debug("[WebServiceTranslator] Encoding the SOAP response...");

    SOAPMessage responseMessage = null;
    String sResponseMessage = "";
    String encodingCharSet = "UTF-8";
    if (context.requestedObject != null)
        encodingCharSet = context.requestedObject.getEncodingCharSet();

    if (convertigoResponse instanceof Document) {
        Engine.logBeans.debug("[WebServiceTranslator] The Convertigo response is a XML document.");
        Document document = Engine.theApp.schemaManager.makeResponse((Document) convertigoResponse);

        //MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL);
        MessageFactory messageFactory = MessageFactory.newInstance();
        responseMessage = messageFactory.createMessage();

        responseMessage.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, encodingCharSet);

        SOAPPart sp = responseMessage.getSOAPPart();
        SOAPEnvelope se = sp.getEnvelope();
        SOAPBody sb = se.getBody();

        sb.setEncodingStyle("http://schemas.xmlsoap.org/soap/encoding/");

        //se.addNamespaceDeclaration(prefix, targetNameSpace);
        se.addNamespaceDeclaration("soapenc", "http://schemas.xmlsoap.org/soap/encoding/");
        se.addNamespaceDeclaration("xsi", "http://www.w3.org/2001/XMLSchema-instance");
        se.addNamespaceDeclaration("xsd", "http://www.w3.org/2001/XMLSchema");

        // Remove header as it not used. Seems that empty headers causes the WS client of Flex 4 to fail 
        se.getHeader().detachNode();

        addSoapElement(context, se, sb, document.getDocumentElement());

        sResponseMessage = SOAPUtils.toString(responseMessage, encodingCharSet);

        // Correct missing "xmlns" (Bug AXA POC client .NET)
        //sResponseMessage = sResponseMessage.replaceAll("<soapenv:Envelope", "<soapenv:Envelope xmlns=\""+targetNameSpace+"\"");
    } else {// w  ww  .j av  a  2  s.c o m
        Engine.logBeans.debug("[WebServiceTranslator] The Convertigo response is not a XML document.");
        sResponseMessage = convertigoResponse.toString();
    }

    if (Engine.logBeans.isDebugEnabled()) {
        Engine.logBeans.debug("[WebServiceTranslator] SOAP response:\n" + sResponseMessage);
    }

    return responseMessage == null ? sResponseMessage.getBytes(encodingCharSet) : responseMessage;
}

From source file:com.twinsoft.convertigo.engine.translators.WebServiceTranslator.java

public Object __buildOutputData(Context context, Object convertigoResponse) throws Exception {
    Engine.logBeans.debug("[WebServiceTranslator] Encoding the SOAP response...");

    SOAPMessage responseMessage = null;
    String sResponseMessage = "";
    String encodingCharSet = "UTF-8";
    if (context.requestedObject != null)
        encodingCharSet = context.requestedObject.getEncodingCharSet();

    if (convertigoResponse instanceof Document) {
        Engine.logBeans.debug("[WebServiceTranslator] The Convertigo response is a XML document.");
        Document document = (Document) convertigoResponse;

        //MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL);
        MessageFactory messageFactory = MessageFactory.newInstance();
        responseMessage = messageFactory.createMessage();

        responseMessage.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, encodingCharSet);

        SOAPPart sp = responseMessage.getSOAPPart();
        SOAPEnvelope se = sp.getEnvelope();
        SOAPBody sb = se.getBody();

        sb.setEncodingStyle("http://schemas.xmlsoap.org/soap/encoding/");

        String targetNamespace = context.project.getTargetNamespace();
        String prefix = getPrefix(context.projectName, targetNamespace);

        //se.addNamespaceDeclaration(prefix, targetNameSpace);
        se.addNamespaceDeclaration("soapenc", "http://schemas.xmlsoap.org/soap/encoding/");
        se.addNamespaceDeclaration("xsi", "http://www.w3.org/2001/XMLSchema-instance");
        se.addNamespaceDeclaration("xsd", "http://www.w3.org/2001/XMLSchema");

        // Remove header as it not used. Seems that empty headers causes the WS client of Flex 4 to fail 
        se.getHeader().detachNode();

        // Add the method response element
        SOAPElement soapMethodResponseElement = null;
        String soapElementName = context.sequenceName != null ? context.sequenceName
                : context.connectorName + "__" + context.transactionName;
        soapElementName += "Response";

        soapMethodResponseElement = sb.addChildElement(se.createName(soapElementName, prefix, targetNamespace));

        if (XsdForm.qualified == context.project.getSchemaElementForm()) {
            soapMethodResponseElement.addAttribute(se.createName("xmlns"), targetNamespace);
        }//  w  w w  .ja  v a2  s .  co  m

        // Add a 'response' root child element or not
        SOAPElement soapResponseElement;
        if (context.sequenceName != null) {
            Sequence sequence = (Sequence) context.requestedObject;
            if (sequence.isIncludeResponseElement()) {
                soapResponseElement = soapMethodResponseElement.addChildElement("response");
            } else {
                soapResponseElement = soapMethodResponseElement;
            }
        } else {
            soapResponseElement = soapMethodResponseElement.addChildElement("response");
        }

        if (soapResponseElement.getLocalName().equals("response")) {
            if (document.getDocumentElement().hasAttributes()) {
                addAttributes(responseMessage, se, context, document.getDocumentElement().getAttributes(),
                        soapResponseElement);
            }
        }

        NodeList childNodes = document.getDocumentElement().getChildNodes();
        int len = childNodes.getLength();
        org.w3c.dom.Node node;
        for (int i = 0; i < len; i++) {
            node = childNodes.item(i);
            if (node instanceof Element) {
                addElement(responseMessage, se, context, (Element) node, soapResponseElement);
            }
        }

        sResponseMessage = SOAPUtils.toString(responseMessage, encodingCharSet);

        // Correct missing "xmlns" (Bug AXA POC client .NET)
        //sResponseMessage = sResponseMessage.replaceAll("<soapenv:Envelope", "<soapenv:Envelope xmlns=\""+targetNameSpace+"\"");
    } else {
        Engine.logBeans.debug("[WebServiceTranslator] The Convertigo response is not a XML document.");
        sResponseMessage = convertigoResponse.toString();
    }

    if (Engine.logBeans.isDebugEnabled()) {
        Engine.logBeans.debug("[WebServiceTranslator] SOAP response:\n" + sResponseMessage);
    }

    return responseMessage == null ? sResponseMessage.getBytes(encodingCharSet) : responseMessage;
}

From source file:com.qubit.solution.fenixedu.bennu.webservices.services.client.WebServiceClientHandler.java

public boolean handleMessage(SOAPMessageContext smc) {

    boolean isOutbound = (Boolean) smc.get(SOAPMessageContext.MESSAGE_OUTBOUND_PROPERTY);

    if (isOutbound) {
        try {//from   w  w  w .  j a  v  a  2 s  . co  m

            final byte[] sessionKey = generateAESKey();
            final String encriptedPassword = cypher(sessionKey, password);
            final String encriptedTimestamp = cypher(sessionKey, getTimestamp());
            final String nonce = cypherSessionKey(getPublicKey(), sessionKey);

            SOAPEnvelope envelope = smc.getMessage().getSOAPPart().getEnvelope();
            SOAPFactory soapFactory = SOAPFactory.newInstance();

            // WSSecurity <Security> header
            SOAPElement wsSecHeaderElm = soapFactory.createElement("Security", AUTH_PREFIX, AUTH_NS);
            SOAPElement userNameTokenElm = soapFactory.createElement("UsernameToken", AUTH_PREFIX, AUTH_NS);
            // Username
            SOAPElement userNameElm = soapFactory.createElement("Username", AUTH_PREFIX, AUTH_NS);
            userNameElm.addTextNode(username);
            // Password
            SOAPElement passwdElm = soapFactory.createElement("Password", AUTH_PREFIX, AUTH_NS);
            passwdElm.addTextNode(encriptedPassword);
            // Nonce
            SOAPElement nonceElm = soapFactory.createElement("Nonce", AUTH_PREFIX, AUTH_NS);
            nonceElm.addTextNode(nonce);
            // Created
            SOAPElement createdElm = soapFactory.createElement("Created", AUTH_PREFIX, AUTH_NS);
            createdElm.addTextNode(encriptedTimestamp);

            userNameTokenElm.addChildElement(userNameElm);
            userNameTokenElm.addChildElement(passwdElm);
            userNameTokenElm.addChildElement(nonceElm);
            userNameTokenElm.addChildElement(createdElm);

            // add child elements to the root element
            wsSecHeaderElm.addChildElement(userNameTokenElm);

            SOAPHeader sh = envelope.getHeader();
            if (sh == null) {
                // create SOAPHeader instance for SOAP envelope
                sh = envelope.addHeader();
            }

            // add SOAP element for header to SOAP header object
            sh.addChildElement(wsSecHeaderElm);

        } catch (Exception e) {
            throw new RuntimeException("Problems in the securityHandler", e);
        }
    }
    return true;
}

From source file:org.apache.taverna.activities.wsdl.T2WSDLSOAPInvoker.java

@Override
protected void addSoapHeader(SOAPEnvelope envelope) throws SOAPException {
    if (wsrfEndpointReference != null) {

        // Extract elements
        // Add WSA-stuff
        // Add elements

        Document wsrfDoc;//from   w  w w  .  ja v a 2 s.c  o  m
        try {
            wsrfDoc = parseWsrfEndpointReference(wsrfEndpointReference);
        } catch (Exception e) {
            logger.warn("Could not parse endpoint reference, ignoring:\n" + wsrfEndpointReference, e);
            return;
        }

        Element wsrfRoot = wsrfDoc.getDocumentElement();

        Element endpointRefElem = null;
        if (!wsrfRoot.getNamespaceURI().equals(WSA200403NS)
                || !wsrfRoot.getLocalName().equals(ENDPOINT_REFERENCE)) {
            // Only look for child if the parent is not an EPR
            NodeList nodes = wsrfRoot.getChildNodes();
            for (int i = 0, n = nodes.getLength(); i < n; i++) {
                Node node = nodes.item(i);
                if (Node.ELEMENT_NODE == node.getNodeType() && node.getLocalName().equals(ENDPOINT_REFERENCE)
                        && node.getNamespaceURI().equals(WSA200403NS)) {
                    // Support wrapped endpoint reference for backward compatibility
                    // and convenience (T2-677)
                    endpointRefElem = (Element) node;
                    break;
                }
            }
        }

        if (endpointRefElem == null) {
            logger.warn("Unexpected element name for endpoint reference, but inserting anyway: "
                    + wsrfRoot.getTagName());
            endpointRefElem = wsrfRoot;
        }

        Element refPropsElem = null;
        NodeList nodes = endpointRefElem.getChildNodes();
        for (int i = 0, n = nodes.getLength(); i < n; i++) {
            Node node = nodes.item(i);
            if (Node.ELEMENT_NODE == node.getNodeType() && node.getLocalName().equals(REFERENCE_PROPERTIES)
                    && node.getNamespaceURI().equals(WSA200403NS)) {
                refPropsElem = (Element) node;
                break;
            }
        }
        if (refPropsElem == null) {
            logger.warn("Could not find " + REFERENCE_PROPERTIES);
            return;
        }

        SOAPHeader header = envelope.getHeader();
        if (header == null) {
            header = envelope.addHeader();
        }

        NodeList refProps = refPropsElem.getChildNodes();

        for (int i = 0, n = refProps.getLength(); i < n; i++) {
            Node node = refProps.item(i);

            if (Node.ELEMENT_NODE == node.getNodeType()) {
                SOAPElement soapElement = SOAPFactory.newInstance().createElement((Element) node);
                header.addChildElement(soapElement);

                Iterator<SOAPHeaderElement> headers = header.examineAllHeaderElements();
                while (headers.hasNext()) {
                    SOAPHeaderElement headerElement = headers.next();
                    if (headerElement.getElementQName().equals(soapElement.getElementQName())) {
                        headerElement.setMustUnderstand(false);
                        headerElement.setActor(null);
                    }
                }
            }
        }
    }
}

From source file:org.apache.axis2.jaxws.message.impl.XMLPartBase.java

public Set<QName> getHeaderQNames() {
    try {/*  ww w .j ava  2  s  .co m*/
        switch (contentType) {
        case OM: {
            HashSet<QName> qnames = new HashSet<QName>();
            OMElement om = this.getAsOMElement();
            if (om instanceof org.apache.axiom.soap.SOAPEnvelope) {
                org.apache.axiom.soap.SOAPEnvelope se = (org.apache.axiom.soap.SOAPEnvelope) om;
                org.apache.axiom.soap.SOAPHeader header = se.getHeader();
                if (header != null) {
                    Iterator it = header.getChildElements();
                    while (it != null && it.hasNext()) {
                        Object node = it.next();
                        if (node instanceof OMElement) {
                            qnames.add(((OMElement) node).getQName());
                        }
                    }
                }
            }
            return qnames;
        }
        case SOAPENVELOPE: {
            HashSet<QName> qnames = new HashSet<QName>();
            SOAPEnvelope se = this.getContentAsSOAPEnvelope();
            if (se != null) {
                SOAPHeader header = se.getHeader();
                if (header != null) {
                    Iterator it = header.getChildElements();
                    while (it != null && it.hasNext()) {
                        Object node = it.next();
                        if (node instanceof SOAPElement) {
                            qnames.add(((SOAPElement) node).getElementQName());
                        }
                    }
                }
            }
            return qnames;
        }
        case SPINE:
            return getContentAsXMLSpine().getHeaderQNames();
        default:
            return null;
        }
    } catch (SOAPException se) {
        throw ExceptionFactory.makeWebServiceException(se);
    }
}

From source file:org.apache.axis2.jaxws.message.util.impl.SAAJConverterImpl.java

public SOAPEnvelope toSAAJ(org.apache.axiom.soap.SOAPEnvelope omEnvelope) throws WebServiceException {
    if (log.isDebugEnabled()) {
        log.debug("Converting OM SOAPEnvelope to SAAJ SOAPEnvelope");
        log.debug("The conversion occurs due to " + JavaUtils.stackToString());
    }//from www.  j  a  va 2  s  . c  o  m

    SOAPEnvelope soapEnvelope = null;
    try {
        // Build the default envelope
        OMNamespace ns = omEnvelope.getNamespace();
        MessageFactory mf = createMessageFactory(ns.getNamespaceURI());
        SOAPMessage sm = mf.createMessage();
        SOAPPart sp = sm.getSOAPPart();
        soapEnvelope = sp.getEnvelope();

        // The getSOAPEnvelope() call creates a default SOAPEnvelope with a SOAPHeader and SOAPBody.
        // The SOAPHeader and SOAPBody are removed (they will be added back in if they are present in the
        // OMEnvelope).
        SOAPBody soapBody = soapEnvelope.getBody();
        if (soapBody != null) {
            soapBody.detachNode();
        }
        SOAPHeader soapHeader = soapEnvelope.getHeader();
        if (soapHeader != null) {
            soapHeader.detachNode();
        }

        // We don't know if there is a real OM tree or just a backing XMLStreamReader.
        // The best way to walk the data is to get the XMLStreamReader and use this
        // to build the SOAPElements
        XMLStreamReader reader = omEnvelope.getXMLStreamReader();

        NameCreator nc = new NameCreator(soapEnvelope);
        buildSOAPTree(nc, soapEnvelope, null, reader, false);
    } catch (WebServiceException e) {
        throw e;
    } catch (SOAPException e) {
        throw ExceptionFactory.makeWebServiceException(e);
    }
    return soapEnvelope;
}

From source file:org.mule.modules.paypal.util.PayPalAPIHelper.java

private static SOAPMessage createGetPalDetailsSOAPRequest(@NotNull String username, @NotNull String password,
        @NotNull String appId, String signature) throws Exception {
    MessageFactory messageFactory = MessageFactory.newInstance();
    SOAPMessage soapMessage = messageFactory.createMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();

    // SOAP Envelope
    SOAPEnvelope envelope = soapPart.getEnvelope();

    envelope.addNamespaceDeclaration(PREFIX_1, SOAP_HEADER_CREDENTIAL_NAMESPACE_1);
    envelope.addNamespaceDeclaration(PREFIX_2, SOAP_HEADER_CREDENTIAL_NAMESPACE_2);

    SOAPHeader soapHeader = envelope.getHeader();
    if (soapHeader == null)
        soapHeader = envelope.addHeader();

    SOAPElement soapReqElement = soapHeader.addChildElement(rootStringValue, PREFIX_1);
    SOAPElement soapCredElement = soapReqElement.addChildElement(subRootStringValue, PREFIX_2);
    soapCredElement.addChildElement(appIdStringValue, PREFIX_2).addTextNode(appId);
    soapCredElement.addChildElement(usernameStringValue, PREFIX_2).addTextNode(username);
    soapCredElement.addChildElement(passwordStringValue, PREFIX_2).addTextNode(password);
    soapCredElement.addChildElement("Signature", PREFIX_2).addTextNode(signature);

    // SOAP Body/*from   w  w  w .ja v a2s  .c  o m*/
    SOAPBody soapBody = envelope.getBody();
    SOAPElement soapBodyElem = soapBody.addChildElement("GetPalDetailsReq", PREFIX_1);
    SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("GetPalDetailsRequest", PREFIX_1);
    soapBodyElem1.addChildElement("Version", PREFIX_2).addTextNode("51");
    soapMessage.saveChanges();

    return soapMessage;
}