Example usage for javax.xml.soap SOAPConnection call

List of usage examples for javax.xml.soap SOAPConnection call

Introduction

In this page you can find the example usage for javax.xml.soap SOAPConnection call.

Prototype

public abstract SOAPMessage call(SOAPMessage request, Object to) throws SOAPException;

Source Link

Document

Sends the given message to the specified endpoint and blocks until it has returned the response.

Usage

From source file:com.betfair.testing.utils.cougar.helpers.CougarHelpers.java

public HttpResponseBean makeCougarSOAPCall(SOAPMessage message, String serviceName, String version,
        HttpCallBean httpBean) {/*w w  w .j  av  a  2s.c  o m*/
    try {

        //Debugging code
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        message.writeTo(outStream);
        SOAPConnectionFactory connectionFactory = SOAPConnectionFactory.newInstance();
        SOAPConnection connection = connectionFactory.createConnection();

        // this can either be a SOAPException or SOAPMessage
        HttpResponseBean responseBean = new HttpResponseBean();
        Object response;

        String host = httpBean.getHost();
        String port = httpBean.getPort();

        String endPoint = "http://" + host + ":" + port + "/" + serviceName + "Service/" + version;

        try {

            response = connection.call(message, endPoint);

        } catch (SOAPException e) {
            response = e;
        } finally {
            connection.close();
        }

        responseBean.setResponseObject(handleResponse(response, responseBean));

        return responseBean;

    } catch (SOAPException | IOException | ParserConfigurationException | TransformerException e) {
        throw new RuntimeException(SOAP_CALL_TEXT + e, e);
    }

}

From source file:edu.unc.lib.dl.services.TripleStoreManagerMulgaraImpl.java

private String sendTQL(String query) {
    log.info(query);// ww w. ja  va2  s .c o  m
    String result = null;
    try {
        // First create the connection
        SOAPConnectionFactory soapConnFactory = SOAPConnectionFactory.newInstance();
        SOAPConnection connection = soapConnFactory.createConnection();

        // Next, create the actual message
        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage message = messageFactory.createMessage();
        message.getMimeHeaders().setHeader("SOAPAction", "itqlbean:executeQueryToString");
        SOAPBody soapBody = message.getSOAPPart().getEnvelope().getBody();
        soapBody.addNamespaceDeclaration("xsd", JDOMNamespaceUtil.XSD_NS.getURI());
        soapBody.addNamespaceDeclaration("xsi", JDOMNamespaceUtil.XSI_NS.getURI());
        soapBody.addNamespaceDeclaration("itqlbean", this.getItqlEndpointURL());
        SOAPElement eqts = soapBody.addChildElement("executeQueryToString", "itqlbean");
        SOAPElement queryStr = eqts.addChildElement("queryString", "itqlbean");
        queryStr.setAttributeNS(JDOMNamespaceUtil.XSI_NS.getURI(), "xsi:type", "xsd:string");
        CDATASection queryCDATA = message.getSOAPPart().createCDATASection(query);
        queryStr.appendChild(queryCDATA);
        message.saveChanges();
        SOAPMessage reply = connection.call(message, this.getItqlEndpointURL());

        if (reply.getSOAPBody().hasFault()) {
            reportSOAPFault(reply);
            if (log.isDebugEnabled()) {
                // log the full soap body response
                DOMBuilder builder = new DOMBuilder();
                org.jdom.Document jdomDoc = builder.build(reply.getSOAPBody().getOwnerDocument());
                log.info(new XMLOutputter().outputString(jdomDoc));
            }
        } else {
            NodeList nl = reply.getSOAPPart().getEnvelope().getBody().getElementsByTagNameNS("*",
                    "executeQueryToStringReturn");
            if (nl.getLength() > 0) {
                result = nl.item(0).getTextContent();
            }
            log.debug(result);
        }
    } catch (SOAPException e) {
        throw new Error("Cannot query triple store at " + this.getItqlEndpointURL(), e);
    }
    return result;
}

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   w w  w.  j  av  a2 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: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}. /*  w  w w.ja v  a  2 s .c  om*/
 * @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:edu.unc.lib.dl.util.TripleStoreQueryServiceMulgaraImpl.java

private String sendTQL(String query) {
    log.debug(query);/*from ww  w. ja  v a2 s  .  co  m*/
    String result = null;
    SOAPMessage reply = null;
    SOAPConnection connection = null;
    try {
        // Next, create the actual message
        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage message = messageFactory.createMessage();
        message.getMimeHeaders().setHeader("SOAPAction", "itqlbean:executeQueryToString");
        SOAPBody soapBody = message.getSOAPPart().getEnvelope().getBody();
        soapBody.addNamespaceDeclaration("xsd", JDOMNamespaceUtil.XSD_NS.getURI());
        soapBody.addNamespaceDeclaration("xsi", JDOMNamespaceUtil.XSI_NS.getURI());
        soapBody.addNamespaceDeclaration("itqlbean", this.getItqlEndpointURL());
        SOAPElement eqts = soapBody.addChildElement("executeQueryToString", "itqlbean");
        SOAPElement queryStr = eqts.addChildElement("queryString", "itqlbean");
        queryStr.setAttributeNS(JDOMNamespaceUtil.XSI_NS.getURI(), "xsi:type", "xsd:string");
        CDATASection queryCDATA = message.getSOAPPart().createCDATASection(query);
        queryStr.appendChild(queryCDATA);
        message.saveChanges();

        // First create the connection
        SOAPConnectionFactory soapConnFactory = SOAPConnectionFactory.newInstance();
        connection = soapConnFactory.createConnection();
        reply = connection.call(message, this.getItqlEndpointURL());

        if (reply.getSOAPBody().hasFault()) {
            reportSOAPFault(reply);
            if (log.isDebugEnabled()) {
                // log the full soap body response
                DOMBuilder builder = new DOMBuilder();
                org.jdom2.Document jdomDoc = builder.build(reply.getSOAPBody().getOwnerDocument());
                log.debug(new XMLOutputter().outputString(jdomDoc));
            }
        } else {
            NodeList nl = reply.getSOAPPart().getEnvelope().getBody().getElementsByTagNameNS("*",
                    "executeQueryToStringReturn");
            if (nl.getLength() > 0) {
                result = nl.item(0).getFirstChild().getNodeValue();
            }
            log.debug(result);
        }
    } catch (SOAPException e) {
        log.error("Failed to prepare or send iTQL via SOAP", e);
        throw new RuntimeException("Cannot query triple store at " + this.getItqlEndpointURL(), e);
    } finally {
        try {
            connection.close();
        } catch (SOAPException e) {
            log.error("Failed to close SOAP connection", e);
            throw new RuntimeException(
                    "Failed to close SOAP connection for triple store at " + this.getItqlEndpointURL(), e);
        }
    }
    return result;
}

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();//w ww  . j  av a 2s . c  om

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

    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:eu.planets_project.tb.gui.backing.admin.wsclient.util.WSClient.java

/**
 * Invokes an operation using SAAJ//from   w ww .ja  va  2s  .  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:com.cisco.dvbu.ps.common.adapters.connect.SoapHttpConnector.java

private Document send(SoapHttpConnectorCallback cb, String requestXml) throws AdapterException {
    log.debug("Entered send: " + cb.getName());

    // set up the factories and create a SOAP factory
    SOAPConnection soapConnection;
    Document doc = null;/*from  www . jav  a2 s .  c o m*/
    URL endpoint = null;
    try {
        soapConnection = SOAPConnectionFactory.newInstance().createConnection();
        MessageFactory messageFactory = MessageFactory.newInstance();

        // Create a message from the message factory.
        SOAPMessage soapMessage = messageFactory.createMessage();

        // Set the SOAP Action here
        MimeHeaders headers = soapMessage.getMimeHeaders();
        headers.addHeader("SOAPAction", cb.getAction());

        // set credentials
        //         String authorization = new sun.misc.BASE64Encoder().encode((shConfig.getUser() + "@" + shConfig.getDomain() + ":" + shConfig.getPassword()).getBytes());
        String authorization = new String(org.apache.commons.codec.binary.Base64.encodeBase64(
                (shConfig.getUser() + "@" + shConfig.getDomain() + ":" + shConfig.getPassword()).getBytes()));
        headers.addHeader("Authorization", "Basic " + authorization);
        log.debug("Authentication: " + authorization);

        // create a SOAP part have populate the envelope
        SOAPPart soapPart = soapMessage.getSOAPPart();
        SOAPEnvelope envelope = soapPart.getEnvelope();
        envelope.setEncodingStyle(SOAPConstants.URI_NS_SOAP_ENCODING);

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

        // create a SOAP body
        SOAPBody body = envelope.getBody();

        log.debug("Request XSL Style Sheet:\n"
                + XMLUtils.getPrettyXml(XMLUtils.getDocumentFromString(cb.getRequestBodyXsl())));

        // convert request string to document and then transform
        body.addDocument(XmlUtils.xslTransform(XmlUtils.stringToDocument(requestXml), cb.getRequestBodyXsl()));

        // build the request structure
        soapMessage.saveChanges();
        log.debug("Soap request successfully built: ");
        log.debug("  Body:\n"
                + XMLUtils.getPrettyXml(XMLUtils.getDocumentFromString(XmlUtils.nodeToString(body))));

        if (shConfig.useProxy()) {
            System.setProperty("http.proxySet", "true");
            System.setProperty("http.proxyHost", shConfig.getProxyHost());
            System.setProperty("http.proxyPort", "" + shConfig.getProxyPort());
            if (shConfig.useProxyCredentials()) {
                System.setProperty("http.proxyUser", shConfig.getProxyUser());
                System.setProperty("http.proxyPassword", shConfig.getProxyPassword());
            }
        }

        endpoint = new URL(shConfig.getEndpoint(cb.getEndpoint()));

        // now make that call over the SOAP connection
        SOAPMessage reply = null;
        AdapterException ae = null;

        for (int i = 1; (i <= shConfig.getRetryAttempts() && reply == null); i++) {
            log.debug("Attempt " + i + ": sending request to endpoint: " + endpoint);
            try {
                reply = soapConnection.call(soapMessage, endpoint);
                log.debug("Attempt " + i + ": received response: " + reply);
            } catch (Exception e) {
                ae = new AdapterException(502, String.format(AdapterConstants.ADAPTER_EM_CONNECTION, endpoint),
                        e);
                Thread.sleep(100);
            }
        }

        // close down the connection
        soapConnection.close();

        if (reply == null)
            throw ae;

        SOAPFault fault = reply.getSOAPBody().getFault();
        if (fault == null) {
            doc = reply.getSOAPBody().extractContentAsDocument();
        } else {
            // Extracts the entire Soap Fault message coming back from CIS
            String faultString = XmlUtils.nodeToString(fault);
            throw new AdapterException(503, faultString, null);
        }
    } catch (AdapterException e) {
        throw e;
    } catch (Exception e) {
        throw new AdapterException(504,
                String.format(AdapterConstants.ADAPTER_EM_CONNECTION, shConfig.getEndpoint(cb.getEndpoint())),
                e);
    } finally {
        if (shConfig.useProxy()) {
            System.setProperty("http.proxySet", "false");
        }
    }
    log.debug("Exiting send: " + cb.getName());

    return doc;
}

From source file:org.apache.axis2.saaj.SOAPConnectionTest.java

public void testCallOnCloseConnection() {
    SOAPConnectionFactory soapConnectionFactory = null;
    try {//from  w  ww  .j  av a  2 s .  c o m
        soapConnectionFactory = SOAPConnectionFactory.newInstance();
    } catch (SOAPException e) {
        fail("Unexpected Exception " + e);
    }

    SOAPConnection sCon = null;
    try {
        sCon = soapConnectionFactory.createConnection();
        sCon.close();
    } catch (SOAPException e) {
        fail("Unexpected Exception " + e);
    }

    try {
        sCon.call(null, new Object());
        fail("Expected Exception did not occur");
    } catch (SOAPException e) {
        assertTrue(true);
    }
}

From source file:org.apache.ws.scout.transport.SaajTransport.java

public Element send(Element request, URI endpointURL) throws TransportException {
    if (log.isDebugEnabled()) {
        String requestMessage = XMLUtils.convertNodeToXMLString(request);
        log.debug("Request message: %s\n%s" + endpointURL + ":" + requestMessage);
    }/*from w ww.  java2  s  . com*/

    Element response = null;
    try {
        SOAPMessage message = this.createSOAPMessage(request);
        //Make the SAAJ Call now
        SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
        SOAPConnection connection = soapConnectionFactory.createConnection();
        SOAPMessage soapResponse = connection.call(message, endpointURL.toURL());

        SOAPBody soapBody = soapResponse.getSOAPBody();
        boolean hasFault = soapBody.hasFault();
        if (hasFault) {
            SOAPFault soapFault = soapBody.getFault();
            String faultStr = soapFault.getFaultCode() + "::" + soapFault.getFaultString();
            throw new RegistryException(faultStr);
        }
        response = getFirstChildElement(soapBody);
    } catch (Exception ex) {
        log.error("Exception::" + ex.getMessage(), ex);
        throw new TransportException(ex);
    }
    if (log.isDebugEnabled()) {
        String responseMessage = XMLUtils.convertNodeToXMLString(response);
        log.debug("Response message: %s" + responseMessage);
    }

    return response;
}