Example usage for javax.xml.soap SOAPHeader detachNode

List of usage examples for javax.xml.soap SOAPHeader detachNode

Introduction

In this page you can find the example usage for javax.xml.soap SOAPHeader detachNode.

Prototype

public void detachNode();

Source Link

Document

Removes this Node object from the tree.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    SOAPConnectionFactory sfc = SOAPConnectionFactory.newInstance();
    SOAPConnection connection = sfc.createConnection();

    MessageFactory mf = MessageFactory.newInstance();
    SOAPMessage sm = mf.createMessage();

    SOAPHeader sh = sm.getSOAPHeader();
    SOAPBody sb = sm.getSOAPBody();
    sh.detachNode();
    QName bodyName = new QName("http://quoteCompany.com", "GetQuote", "d");
    SOAPBodyElement bodyElement = sb.addBodyElement(bodyName);
    QName qn = new QName("aName");
    SOAPElement quotation = bodyElement.addChildElement(qn);

    quotation.addTextNode("TextMode");

    System.out.println("\n Soap Request:\n");
    sm.writeTo(System.out);/*from  ww w . ja v a 2s.  c om*/
    System.out.println();

    URL endpoint = new URL("http://yourServer.com");
    SOAPMessage response = connection.call(sm, endpoint);
    System.out.println(response.getContentDescription());
}

From source file:SOAPRequest.java

public static void main(String[] args) {
    try {// w w w .j a  va2 s. co m
        SOAPConnectionFactory sfc = SOAPConnectionFactory.newInstance();
        SOAPConnection connection = sfc.createConnection();

        MessageFactory mf = MessageFactory.newInstance();
        SOAPMessage sm = mf.createMessage();

        SOAPHeader sh = sm.getSOAPHeader();
        SOAPBody sb = sm.getSOAPBody();
        sh.detachNode();
        QName bodyName = new QName("http://quoteCompany.com", "GetQuote", "d");
        SOAPBodyElement bodyElement = sb.addBodyElement(bodyName);
        QName qn = new QName("aName");
        SOAPElement quotation = bodyElement.addChildElement(qn);

        quotation.addTextNode("TextMode");

        System.out.println("\n Soap Request:\n");
        sm.writeTo(System.out);
        System.out.println();

        URL endpoint = new URL("http://yourServer.com");
        SOAPMessage response = connection.call(sm, endpoint);
        System.out.println(response.getContentDescription());
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:eu.planets_project.tb.gui.backing.admin.wsclient.util.WSClient.java

/**
 * Invokes an operation using SAAJ//from  w w  w  . j a  v  a2s.  c o m
 *
 * @param operation The operation to invoke
 */
public static void main(String[] args) {
    try {
        /*OperationInfo operation = new OperationInfo();
        operation.setEncodingStyle("http://schemas.xmlsoap.org/soap/encoding/");
        operation.setInputMessageName("HelloWorld_sayHello");
        operation.setInputMessageText("<urn:sayHello xmlns:urn='urn:jbosstest'><arg0>Markus</arg0></urn:sayHello>");
        operation.setNamespaceURI("urn:jbosstest");
        operation.setOutputMessageName("HelloWorld_sayHelloResponse");
        operation.setOutputMessageText("<sayHello><return>0</return></sayHello>");
        operation.setSoapActionURI("");
        operation.setStyle("document");
        operation.setTargetMethodName("sayHello");
        operation.setTargetObjectURI(null);
        operation.setTargetURL("http://localhost:8080/HelloWorld/HelloWorld");*/

        OperationInfo operation = new OperationInfo();
        operation.setEncodingStyle("http://schemas.xmlsoap.org/soap/encoding/");
        operation.setInputMessageName("ConversionRateSoapIn");
        operation.setInputMessageText(
                "<ns5:ConversionRate xmlns:ns5='http://www.webserviceX.NET/'><ns5:FromCurrency>EUR</ns5:FromCurrency><ns5:ToCurrency>SKK</ns5:ToCurrency></ns5:ConversionRate>");
        operation.setNamespaceURI("http://www.webserviceX.NET/");
        operation.setOutputMessageName("ConversionRateSoapOut");
        operation.setOutputMessageText(
                "<ConversionRate><ConversionRateResult>0</ConversionRateResult></ConversionRate>");
        operation.setSoapActionURI("http://www.webserviceX.NET/ConversionRate");
        operation.setStyle("document");
        operation.setTargetMethodName("ConversionRate");
        operation.setTargetObjectURI(null);
        operation.setTargetURL("http://www.webservicex.net/CurrencyConvertor.asmx");

        // Determine if the operation style is RPC
        boolean isRPC = operation.getStyle().equalsIgnoreCase("rpc");

        // All connections are created by using a connection factory
        SOAPConnectionFactory conFactory = SOAPConnectionFactory.newInstance();

        // Now we can create a SOAPConnection object using the connection factory
        SOAPConnection connection = conFactory.createConnection();

        // All SOAP messages are created by using a message factory
        MessageFactory msgFactory = MessageFactory.newInstance();

        // Now we can create the SOAP message object
        SOAPMessage msg = msgFactory.createMessage();

        // Get the SOAP part from the SOAP message object
        SOAPPart soapPart = msg.getSOAPPart();

        // The SOAP part object will automatically contain the SOAP envelope
        SOAPEnvelope envelope = soapPart.getEnvelope();
        //envelope.addNamespaceDeclaration("", operation.getNamespaceURI());

        if (isRPC) {
            // Add namespace declarations to the envelope, usually only required for RPC/encoded
            envelope.addNamespaceDeclaration(XSI_NAMESPACE_PREFIX, XSI_NAMESPACE_URI);
            envelope.addNamespaceDeclaration(XSD_NAMESPACE_PREFIX, XSD_NAMESPACE_URI);
        }

        // Get the SOAP header from the envelope
        SOAPHeader header = envelope.getHeader();

        // The client does not yet support SOAP headers
        header.detachNode();

        // Get the SOAP body from the envelope and populate it
        SOAPBody body = envelope.getBody();

        // Create the default namespace for the SOAP body
        //body.addNamespaceDeclaration("", operation.getNamespaceURI());

        // Add the service information
        String targetObjectURI = operation.getTargetObjectURI();

        if (targetObjectURI == null) {
            // The target object URI should not be null
            targetObjectURI = "";
        }

        // Add the service information
        //Name svcInfo = envelope.createName(operation.getTargetMethodName(), "", targetObjectURI);
        Name svcInfo = envelope.createName(operation.getTargetMethodName(), "ns2", operation.getNamespaceURI());
        SOAPElement svcElem = body.addChildElement(svcInfo);

        if (isRPC) {
            // Set the encoding style of the service element
            svcElem.setEncodingStyle(operation.getEncodingStyle());
        }

        // Add the message contents to the SOAP body
        Document doc = XMLSupport.readXML(operation.getInputMessageText());

        if (doc.hasRootElement()) {
            // Begin building content
            buildSoapElement(envelope, svcElem, doc.getRootElement(), isRPC);
        }

        //svcElem.addTextNode(operation.getInputMessageText());
        //svcElem.

        // Check for a SOAPAction
        String soapActionURI = operation.getSoapActionURI();

        if (soapActionURI != null && soapActionURI.length() > 0) {
            // Add the SOAPAction value as a MIME header
            MimeHeaders mimeHeaders = msg.getMimeHeaders();
            mimeHeaders.setHeader("SOAPAction", "\"" + operation.getSoapActionURI() + "\"");
        }

        // Save changes to the message we just populated
        msg.saveChanges();

        // Get ready for the invocation
        URLEndpoint endpoint = new URLEndpoint(operation.getTargetURL());

        // Show the URL endpoint message in the log
        ByteArrayOutputStream msgStream = new ByteArrayOutputStream();
        msg.writeTo(msgStream);

        log.debug("SOAP Message MeasurementTarget URL: " + endpoint.getURL());
        log.debug("SOAP Request: " + msgStream.toString());

        // Make the call
        SOAPMessage response = connection.call(msg, endpoint);

        // Close the connection, we are done with it
        connection.close();

        // Get the content of the SOAP response
        Source responseContent = response.getSOAPPart().getContent();

        // Convert the SOAP response into a JDOM
        TransformerFactory tFact = TransformerFactory.newInstance();
        Transformer transformer = tFact.newTransformer();

        JDOMResult jdomResult = new JDOMResult();
        transformer.transform(responseContent, jdomResult);

        // Get the document created by the transform operation
        Document responseDoc = jdomResult.getDocument();

        // Send the response to the Log
        String strResponse = XMLSupport.outputString(responseDoc);
        log.debug("SOAP Response from: " + operation.getTargetMethodName() + ": " + strResponse);

        // Set the response as the output message
        operation.setOutputMessageText(strResponse);

        // Return the response generated
        //return strResponse;
    }

    catch (Throwable ex) {
        log.error("Error invoking operation:");
        log.error(ex.getMessage());
    }

    //return "";
}

From source file:eu.planets_project.tb.gui.backing.admin.wsclient.util.WSClient.java

/**
 * Invokes an operation using SAAJ//from   w  w  w  .j a va2s  . c o m
 *
 * @param operation The operation to invoke
 */
public static String invokeOperation(OperationInfo operation) throws Exception {
    try {
        // Determine if the operation style is RPC
        boolean isRPC = false;
        if (operation.getStyle() != null)
            isRPC = operation.getStyle().equalsIgnoreCase("rpc");
        else
            ;

        // All connections are created by using a connection factory
        SOAPConnectionFactory conFactory = SOAPConnectionFactory.newInstance();

        // Now we can create a SOAPConnection object using the connection factory
        SOAPConnection connection = conFactory.createConnection();

        // All SOAP messages are created by using a message factory
        MessageFactory msgFactory = MessageFactory.newInstance();

        // Now we can create the SOAP message object
        SOAPMessage msg = msgFactory.createMessage();

        // Get the SOAP part from the SOAP message object
        SOAPPart soapPart = msg.getSOAPPart();

        // The SOAP part object will automatically contain the SOAP envelope
        SOAPEnvelope envelope = soapPart.getEnvelope();
        //my extension - START
        //envelope.addNamespaceDeclaration("_ns1", operation.getNamespaceURI());
        //my extension - END

        if (isRPC) {
            // Add namespace declarations to the envelope, usually only required for RPC/encoded
            envelope.addNamespaceDeclaration(XSI_NAMESPACE_PREFIX, XSI_NAMESPACE_URI);
            envelope.addNamespaceDeclaration(XSD_NAMESPACE_PREFIX, XSD_NAMESPACE_URI);
        }

        // Get the SOAP header from the envelope
        SOAPHeader header = envelope.getHeader();

        // The client does not yet support SOAP headers
        header.detachNode();

        // Get the SOAP body from the envelope and populate it
        SOAPBody body = envelope.getBody();

        // Create the default namespace for the SOAP body
        //body.addNamespaceDeclaration("", operation.getNamespaceURI());

        // Add the service information
        String targetObjectURI = operation.getTargetObjectURI();

        if (targetObjectURI == null) {
            // The target object URI should not be null
            targetObjectURI = "";
        }

        // Add the service information         
        //Name svcInfo = envelope.createName(operation.getTargetMethodName(), "", targetObjectURI);
        Name svcInfo = envelope.createName(operation.getTargetMethodName(), "ns1", operation.getNamespaceURI());
        SOAPElement svcElem = body.addChildElement(svcInfo);

        if (isRPC) {
            // Set the encoding style of the service element
            svcElem.setEncodingStyle(operation.getEncodingStyle());
        }

        // Add the message contents to the SOAP body
        Document doc = XMLSupport.readXML(operation.getInputMessageText());

        if (doc.hasRootElement()) {
            // Begin building content
            buildSoapElement(envelope, svcElem, doc.getRootElement(), isRPC);
        }

        //svcElem.addTextNode(operation.getInputMessageText());
        //svcElem.

        // Check for a SOAPAction
        String soapActionURI = operation.getSoapActionURI();

        if (soapActionURI != null && soapActionURI.length() > 0) {
            // Add the SOAPAction value as a MIME header
            MimeHeaders mimeHeaders = msg.getMimeHeaders();
            mimeHeaders.setHeader("SOAPAction", "\"" + operation.getSoapActionURI() + "\"");
        }

        // Save changes to the message we just populated
        msg.saveChanges();

        // Get ready for the invocation
        URLEndpoint endpoint = new URLEndpoint(operation.getTargetURL());

        // Show the URL endpoint message in the log
        ByteArrayOutputStream msgStream = new ByteArrayOutputStream();
        msg.writeTo(msgStream);

        log.debug("SOAP Message MeasurementTarget URL: " + endpoint.getURL());
        log.debug("SOAP Request: " + msgStream.toString());

        // Make the call
        SOAPMessage response = connection.call(msg, endpoint);

        // Close the connection, we are done with it
        connection.close();

        // Get the content of the SOAP response
        Source responseContent = response.getSOAPPart().getContent();

        // Convert the SOAP response into a JDOM
        TransformerFactory tFact = TransformerFactory.newInstance();
        Transformer transformer = tFact.newTransformer();

        JDOMResult jdomResult = new JDOMResult();
        transformer.transform(responseContent, jdomResult);

        // Get the document created by the transform operation
        Document responseDoc = jdomResult.getDocument();

        // Send the response to the Log
        String strResponse = XMLSupport.outputString(responseDoc);
        log.debug("SOAP Response from: " + operation.getTargetMethodName() + ": " + strResponse);

        // Set the response as the output message
        operation.setOutputMessageText(strResponse);

        // Return the response generated
        return strResponse;
    }

    catch (Throwable ex) {
        throw new Exception("Error invoking operation", ex);
    }

}

From source file:cl.nic.dte.net.ConexionSii.java

@SuppressWarnings("unchecked")
private String getSemilla()
        throws UnsupportedOperationException, SOAPException, IOException, XmlException, ConexionSiiException {
    SOAPConnectionFactory scFactory = SOAPConnectionFactory.newInstance();
    SOAPConnection con = scFactory.createConnection();
    MessageFactory factory = MessageFactory.newInstance();
    SOAPMessage message = factory.createMessage();
    SOAPPart soapPart = message.getSOAPPart();
    SOAPEnvelope envelope = soapPart.getEnvelope();
    SOAPHeader header = envelope.getHeader();
    SOAPBody body = envelope.getBody();
    header.detachNode();

    String urlSolicitud = Utilities.netLabels.getString("URL_SOLICITUD_SEMILLA");

    Name bodyName = envelope.createName("getSeed", "m", urlSolicitud);

    message.getMimeHeaders().addHeader("SOAPAction", "");

    body.addBodyElement(bodyName);/*from w w  w  .j av  a  2  s. com*/

    URL endpoint = new URL(urlSolicitud);

    SOAPMessage responseSII = con.call(message, endpoint);

    SOAPPart sp = responseSII.getSOAPPart();
    SOAPBody b = sp.getEnvelope().getBody();

    cl.sii.xmlSchema.RESPUESTADocument resp = null;
    for (Iterator<SOAPBodyElement> res = b.getChildElements(
            sp.getEnvelope().createName("getSeedResponse", "ns1", urlSolicitud)); res.hasNext();) {
        for (Iterator<SOAPBodyElement> ret = res.next().getChildElements(
                sp.getEnvelope().createName("getSeedReturn", "ns1", urlSolicitud)); ret.hasNext();) {

            HashMap<String, String> namespaces = new HashMap<String, String>();
            namespaces.put("", "http://www.sii.cl/XMLSchema");
            XmlOptions opts = new XmlOptions();
            opts.setLoadSubstituteNamespaces(namespaces);

            resp = RESPUESTADocument.Factory.parse(ret.next().getValue(), opts);

        }
    }

    if (resp != null && resp.getRESPUESTA().getRESPHDR().getESTADO() == 0) {
        return resp.getRESPUESTA().getRESPBODY().getSEMILLA();
    } else {
        throw new ConexionSiiException(
                "No obtuvo Semilla: Codigo: " + resp.getRESPUESTA().getRESPHDR().getESTADO() + "; Glosa: "
                        + resp.getRESPUESTA().getRESPHDR().getGLOSA());
    }
}

From source file:cl.nic.dte.net.ConexionSii.java

@SuppressWarnings("unchecked")
public String getToken(PrivateKey pKey, X509Certificate cert)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyException, MarshalException,
        XMLSignatureException, SAXException, IOException, ParserConfigurationException, XmlException,
        UnsupportedOperationException, SOAPException, ConexionSiiException {

    String urlSolicitud = Utilities.netLabels.getString("URL_SOLICITUD_TOKEN");

    String semilla = getSemilla();

    GetTokenDocument req = GetTokenDocument.Factory.newInstance();

    req.addNewGetToken().addNewItem().setSemilla(semilla);

    HashMap<String, String> namespaces = new HashMap<String, String>();
    namespaces.put("", "http://www.sii.cl/SiiDte");
    XmlOptions opts = new XmlOptions();

    opts = new XmlOptions();
    opts.setSaveImplicitNamespaces(namespaces);
    opts.setLoadSubstituteNamespaces(namespaces);
    opts.setSavePrettyPrint();//from   ww  w. ja  va 2  s  .c o m
    opts.setSavePrettyPrintIndent(0);

    req = GetTokenDocument.Factory.parse(req.newInputStream(opts), opts);

    // firmo
    req.sign(pKey, cert);

    SOAPConnectionFactory scFactory = SOAPConnectionFactory.newInstance();
    SOAPConnection con = scFactory.createConnection();
    MessageFactory factory = MessageFactory.newInstance();
    SOAPMessage message = factory.createMessage();
    SOAPPart soapPart = message.getSOAPPart();
    SOAPEnvelope envelope = soapPart.getEnvelope();
    SOAPHeader header = envelope.getHeader();
    SOAPBody body = envelope.getBody();
    header.detachNode();

    Name bodyName = envelope.createName("getToken", "m", urlSolicitud);
    SOAPBodyElement gltp = body.addBodyElement(bodyName);

    Name toKname = envelope.createName("pszXml");

    SOAPElement toKsymbol = gltp.addChildElement(toKname);

    opts = new XmlOptions();
    opts.setCharacterEncoding("ISO-8859-1");
    opts.setSaveImplicitNamespaces(namespaces);

    toKsymbol.addTextNode(req.xmlText(opts));

    message.getMimeHeaders().addHeader("SOAPAction", "");

    URL endpoint = new URL(urlSolicitud);

    message.writeTo(System.out);

    SOAPMessage responseSII = con.call(message, endpoint);

    SOAPPart sp = responseSII.getSOAPPart();
    SOAPBody b = sp.getEnvelope().getBody();

    cl.sii.xmlSchema.RESPUESTADocument resp = null;
    for (Iterator<SOAPBodyElement> res = b.getChildElements(
            sp.getEnvelope().createName("getTokenResponse", "ns1", urlSolicitud)); res.hasNext();) {
        for (Iterator<SOAPBodyElement> ret = res.next().getChildElements(
                sp.getEnvelope().createName("getTokenReturn", "ns1", urlSolicitud)); ret.hasNext();) {

            namespaces = new HashMap<String, String>();
            namespaces.put("", "http://www.sii.cl/XMLSchema");
            opts.setLoadSubstituteNamespaces(namespaces);

            resp = RESPUESTADocument.Factory.parse(ret.next().getValue(), opts);
        }
    }

    if (resp != null && resp.getRESPUESTA().getRESPHDR().getESTADO() == 0) {
        return resp.getRESPUESTA().getRESPBODY().getTOKEN();
    } else {
        throw new ConexionSiiException(
                "No obtuvo Semilla: Codigo: " + resp.getRESPUESTA().getRESPHDR().getESTADO() + "; Glosa: "
                        + resp.getRESPUESTA().getRESPHDR().getGLOSA());
    }

}

From source file:cl.nic.dte.net.ConexionSii.java

@SuppressWarnings("unchecked")
private RESPUESTADocument getEstadoDTE(String rutConsultante, Documento dte, String token, String urlSolicitud)
        throws UnsupportedOperationException, SOAPException, MalformedURLException, XmlException {

    String rutEmisor = dte.getEncabezado().getEmisor().getRUTEmisor();
    String rutReceptor = dte.getEncabezado().getReceptor().getRUTRecep();
    Integer tipoDTE = dte.getEncabezado().getIdDoc().getTipoDTE().intValue();
    long folioDTE = dte.getEncabezado().getIdDoc().getFolio();
    String fechaEmision = Utilities.fechaEstadoDte
            .format(dte.getEncabezado().getIdDoc().getFchEmis().getTime());
    long montoTotal = dte.getEncabezado().getTotales().getMntTotal();

    SOAPConnectionFactory scFactory = SOAPConnectionFactory.newInstance();
    SOAPConnection con = scFactory.createConnection();
    MessageFactory factory = MessageFactory.newInstance();
    SOAPMessage message = factory.createMessage();
    SOAPPart soapPart = message.getSOAPPart();
    SOAPEnvelope envelope = soapPart.getEnvelope();
    SOAPHeader header = envelope.getHeader();
    SOAPBody body = envelope.getBody();
    header.detachNode();

    Name bodyName = envelope.createName("getEstDte", "m", urlSolicitud);
    SOAPBodyElement gltp = body.addBodyElement(bodyName);

    Name toKname = envelope.createName("RutConsultante");
    SOAPElement toKsymbol = gltp.addChildElement(toKname);
    toKsymbol.addTextNode(rutConsultante.substring(0, rutConsultante.length() - 2));

    toKname = envelope.createName("DvConsultante");
    toKsymbol = gltp.addChildElement(toKname);
    toKsymbol.addTextNode(rutConsultante.substring(rutConsultante.length() - 1, rutConsultante.length()));

    toKname = envelope.createName("RutCompania");
    toKsymbol = gltp.addChildElement(toKname);
    toKsymbol.addTextNode(rutEmisor.substring(0, rutEmisor.length() - 2));

    toKname = envelope.createName("DvCompania");
    toKsymbol = gltp.addChildElement(toKname);
    toKsymbol.addTextNode(rutEmisor.substring(rutEmisor.length() - 1, rutEmisor.length()));

    toKname = envelope.createName("RutReceptor");
    toKsymbol = gltp.addChildElement(toKname);
    toKsymbol.addTextNode(rutReceptor.substring(0, rutReceptor.length() - 2));

    toKname = envelope.createName("DvReceptor");
    toKsymbol = gltp.addChildElement(toKname);
    toKsymbol.addTextNode(rutReceptor.substring(rutReceptor.length() - 1, rutReceptor.length()));

    toKname = envelope.createName("TipoDte");
    toKsymbol = gltp.addChildElement(toKname);
    toKsymbol.addTextNode(Integer.toString(tipoDTE));

    toKname = envelope.createName("FolioDte");
    toKsymbol = gltp.addChildElement(toKname);
    toKsymbol.addTextNode(Long.toString(folioDTE));

    toKname = envelope.createName("FechaEmisionDte");
    toKsymbol = gltp.addChildElement(toKname);
    toKsymbol.addTextNode(fechaEmision);

    toKname = envelope.createName("MontoDte");
    toKsymbol = gltp.addChildElement(toKname);
    toKsymbol.addTextNode(Long.toString(montoTotal));

    toKname = envelope.createName("Token");
    toKsymbol = gltp.addChildElement(toKname);
    toKsymbol.addTextNode(token);/* w  w w  .java 2  s  .co  m*/

    message.getMimeHeaders().addHeader("SOAPAction", "");

    URL endpoint = new URL(urlSolicitud);

    SOAPMessage responseSII = con.call(message, endpoint);

    SOAPPart sp = responseSII.getSOAPPart();
    SOAPBody b = sp.getEnvelope().getBody();

    for (Iterator<SOAPBodyElement> res = b.getChildElements(
            sp.getEnvelope().createName("getEstDteResponse", "ns1", urlSolicitud)); res.hasNext();) {
        for (Iterator<SOAPBodyElement> ret = res.next().getChildElements(
                sp.getEnvelope().createName("getEstDteReturn", "ns1", urlSolicitud)); ret.hasNext();) {

            HashMap<String, String> namespaces = new HashMap<String, String>();
            namespaces.put("", "http://www.sii.cl/XMLSchema");
            XmlOptions opts = new XmlOptions();
            opts.setLoadSubstituteNamespaces(namespaces);

            return RESPUESTADocument.Factory.parse(ret.next().getValue(), opts);
        }
    }

    return null;

}

From source file:com.novartis.opensource.yada.adaptor.SOAPAdaptor.java

/**
 * Constructs and executes a SOAP message.  For {@code basic} authentication, YADA uses the 
 * java soap api, and the {@link SOAPConnection} object stored in the query object.  For 
 * NTLM, which was never successful using the java api, YADA calls out to {@link #CURL_EXEC}
 * in {@link #YADA_BIN}. //from w  w  w .ja v a2  s  .c  o m
 * @see com.novartis.opensource.yada.adaptor.Adaptor#execute(com.novartis.opensource.yada.YADAQuery)
 */
@Override
public void execute(YADAQuery yq) throws YADAAdaptorExecutionException {
    String result = "";
    resetCountParameter(yq);
    SOAPConnection connection = (SOAPConnection) yq.getConnection();
    for (int row = 0; row < yq.getData().size(); row++) {
        yq.setResult();
        YADAQueryResult yqr = yq.getResult();
        String soapUrl = yq.getSoap(row);

        try {
            this.endpoint = new URL(soapUrl);
            MessageFactory factory = MessageFactory.newInstance();
            SOAPMessage message = factory.createMessage();

            byte[] authenticationToken = Base64.encodeBase64((this.soapUser + ":" + this.soapPass).getBytes());

            // Assume a SOAP message was built previously
            MimeHeaders mimeHeaders = message.getMimeHeaders();
            if ("basic".equals(this.soapAuth.toLowerCase())) {
                mimeHeaders.addHeader("Authorization", this.soapAuth + " " + new String(authenticationToken));
                mimeHeaders.addHeader("SOAPAction", this.soapAction);
                mimeHeaders.addHeader("Content-Type", "text/xml");
                SOAPHeader header = message.getSOAPHeader();
                SOAPBody body = message.getSOAPBody();
                header.detachNode();

                l.debug("query:\n" + this.queryString);

                try {
                    Document xml = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                            .parse(new ByteArrayInputStream(this.soapData.getBytes()));

                    //SOAPBodyElement docElement = 
                    body.addDocument(xml);

                    Authenticator.setDefault(new YadaSoapAuthenticator(this.soapUser, this.soapPass));

                    SOAPMessage response = connection.call(message, this.endpoint);
                    try (ByteArrayOutputStream responseOutputStream = new ByteArrayOutputStream()) {
                        response.writeTo(responseOutputStream);
                        result = responseOutputStream.toString();
                    }
                } catch (IOException e) {
                    String msg = "Unable to process input or output stream for SOAP message with Basic Authentication. This is an I/O problem, not an authentication issue.";
                    throw new YADAAdaptorExecutionException(msg, e);
                }
                l.debug("SOAP Body:\n" + result);
            } else if (AUTH_NTLM.equals(this.soapAuth.toLowerCase())
                    || "negotiate".equals(this.soapAuth.toLowerCase())) {
                ArrayList<String> args = new ArrayList<>();
                args.add(Finder.getEnv(YADA_BIN) + CURL_EXEC);
                args.add("-X");
                args.add("-s");
                args.add(this.soapSource + this.soapPath);
                args.add("-u");
                args.add(this.soapDomain + "\\" + this.soapUser);
                args.add("-p");
                args.add(this.soapPass);
                args.add("-a");
                args.add(this.soapAuth);
                args.add("-q");
                args.add(this.soapData);
                args.add("-t");
                args.add(this.soapAction);
                String[] cmds = args.toArray(new String[0]);
                l.debug("Executing soap request via script: " + Arrays.toString(cmds));
                String s = null;
                try {
                    ProcessBuilder pb = new ProcessBuilder(args);
                    l.debug(pb.environment().toString());
                    pb.redirectErrorStream(true);
                    Process p = pb.start();
                    try (BufferedReader si = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
                        while ((s = si.readLine()) != null) {
                            l.debug(s);
                            if (null == result) {
                                result = "";
                            }
                            result += s;
                        }
                    }
                } catch (IOException e) {
                    String msg = "Unable to execute NTLM-authenticated SOAP call using system call to 'curl'.  Make sure the curl executable is still accessible.";
                    throw new YADAAdaptorExecutionException(msg, e);
                }
            }
        } catch (SOAPException e) {
            String msg = "There was a problem creating or executing the SOAP message, or receiving the response.";
            throw new YADAAdaptorExecutionException(msg, e);
        } catch (SAXException e) {
            String msg = "Unable to parse SOAP message body.";
            throw new YADAAdaptorExecutionException(msg, e);
        } catch (ParserConfigurationException e) {
            String msg = "There was a problem creating the xml document for the SOAP message body.";
            throw new YADAAdaptorExecutionException(msg, e);
        } catch (YADAResourceException e) {
            String msg = "Cannot find 'curl' executable at specified JNDI path " + YADA_BIN + CURL_EXEC;
            throw new YADAAdaptorExecutionException(msg, e);
        } catch (MalformedURLException e) {
            String msg = "Can't create URL from provided source and path.";
            throw new YADAAdaptorExecutionException(msg, e);
        } finally {
            try {
                ConnectionFactory.releaseResources(connection, yq.getSoap().get(0));
            } catch (YADAConnectionException e) {
                l.error(e.getMessage());
            }
        }

        yqr.addResult(row, result);

    }

}

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   w w w. j  av a 2s  .c  om

    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;
}