Example usage for javax.xml.soap SOAPConnection close

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

Introduction

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

Prototype

public abstract void close() throws SOAPException;

Source Link

Document

Closes this SOAPConnection object.

Usage

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

/**
 * Invokes an operation using SAAJ//w w  w  .  j a va 2 s  .  co 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:au.com.ors.rest.controller.AutoCheckController.java

@RequestMapping(method = RequestMethod.POST)
@ResponseBody/*from  w ww. ja  v  a  2 s .com*/
public ResponseEntity<AutoCheckRes> autoCheck(@RequestBody AutoCheckReq req) throws Exception {
    AutoCheckRes autoCheckRes = new AutoCheckRes(null, null);

    SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
    SOAPConnection soapConnection = soapConnectionFactory.createConnection();

    String url = "http://localhost:6060/ode/processes/AutoCheck";
    SOAPMessage soapResponse = soapConnection
            .call(createSOAPRequest(req.getDriverLicenseNumber(), req.getFullName(), req.getPostCode()), url);

    soapConnection.close();

    SOAPBody body = soapResponse.getSOAPBody();
    Node rootnode = body.getChildNodes().item(0);
    NodeList nodeList = rootnode.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); ++i) {
        Node currentNode = nodeList.item(i);
        if (currentNode.getNodeName().equals("ns:pdvResult")) {
            autoCheckRes.setPdvResult(currentNode.getTextContent());
        } else if (currentNode.getNodeName().equals("ns:crvResult")) {
            autoCheckRes.setCrvResult(currentNode.getTextContent());
        }
    }
    return new ResponseEntity<AutoCheckRes>(autoCheckRes, HttpStatus.OK);
}

From source file:SendSOAPMessage.java

/**
 * send a simple soap message with JAXM API.
 *//*  w  w  w.  j a v a2s  .  co m*/
public void sendMessage(String url) {

    try {
        /**
         * Construct a default SOAP message factory.
         */
        MessageFactory mf = MessageFactory.newInstance();
        /**
         * Create a SOAP message object.
         */
        SOAPMessage soapMessage = mf.createMessage();
        /**
         * Get SOAP part.
         */
        SOAPPart soapPart = soapMessage.getSOAPPart();
        /**
         * Get SOAP envelope.
         */
        SOAPEnvelope soapEnvelope = soapPart.getEnvelope();

        /**
         * Get SOAP body.
         */
        SOAPBody soapBody = soapEnvelope.getBody();

        /**
         * Add child element with the specified name.
         */
        SOAPElement element = soapBody.addChildElement("HelloWorld");

        /**
         * Add text message
         */
        element.addTextNode("Welcome to SunOne Web Services!");

        soapMessage.saveChanges();

        /**
         * Construct a default SOAP connection factory.
         */
        SOAPConnectionFactory connectionFactory = SOAPConnectionFactory.newInstance();

        /**
         * Get SOAP connection.
         */
        SOAPConnection soapConnection = connectionFactory.createConnection();

        /**
         * Construct endpoint object.
         */
        URLEndpoint endpoint = new URLEndpoint(url);

        /**
         * Send SOAP message.
         */
        SOAPMessage resp = soapConnection.call(soapMessage, endpoint);

        /**
         * Print response to the std output.
         */
        resp.writeTo(System.out);

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

    } catch (java.io.IOException ioe) {
        ioe.printStackTrace();
    } catch (SOAPException soape) {
        soape.printStackTrace();
    }
}

From source file:com.usps.UspsServlet.java

private void generateUSPSsoapRequest(String parameter) {
    try {//from   ww w.j  av a2 s. co m
        // Create SOAP Connection
        SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
        SOAPConnection soapConnection = soapConnectionFactory.createConnection();

        // Send SOAP Message to SOAP Server
        String url = "https://www.ups.com/ups.app/xml/Rate";
        SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(parameter), url);
        // print SOAP Response
        System.out.print("Response SOAP Message:");
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        soapResponse.writeTo(out);
        InputStream inStream = new ByteArrayInputStream(out.toByteArray());

        //if the response xml is desired in the String
        String strMsg = new String(out.toByteArray());
        System.out.println(strMsg);
        soapConnection.close();
    } catch (SOAPException ex) {
        Logger.getLogger(UspsServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(UspsServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.polivoto.networking.SoapClient.java

public String start() throws SOAPException, IOException {
    String resp = "NaN";
    // Create SOAP Connection
    SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
    SOAPConnection soapConnection = soapConnectionFactory.createConnection();

    // Send SOAP Message to SOAP Server
    String url = "http://" + host
            + "/FistVotingServiceBank/services/ServAvailableVoteProcesses.ServAvailableVoteProcessesHttpSoap11Endpoint/";
    SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url);

    SOAPBody body = soapResponse.getSOAPBody();
    java.util.Iterator updates = body.getChildElements();
    // El siguiente ciclo funciona slo porque el cuerpo contiene 
    // un elemento y ste a suvez nicamente contiene un elemento.
    while (updates.hasNext()) {
        System.out.println();//www  .j a v  a  2  s .co  m
        // The listing and its ID
        SOAPElement update = (SOAPElement) updates.next();
        java.util.Iterator i = update.getChildElements();
        while (i.hasNext()) {
            SOAPElement e = (SOAPElement) i.next();
            String name = e.getLocalName();
            String value = e.getValue();
            resp = value; // Am I getting last response?
            System.out.println(name + ": " + value);
        }
    }
    soapConnection.close();
    return resp;
}

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

public HttpResponseBean makeCougarSOAPCall(SOAPMessage message, String serviceName, String version,
        HttpCallBean httpBean) {//  ww w  . j a v a  2  s . 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:com.inbravo.scribe.rest.service.crm.ms.auth.SOAPExecutor.java

/**
 * Executes SOAP message/*from   ww w .j  a  v  a2  s. co  m*/
 * 
 * @param endpointUrl SOAP endpoint
 * @param message SOAP request
 * @return SOAP response message
 * @throws SOAPException in case of a SOAP issue
 * @throws IOException in case of an IO issue
 */
private final SOAPMessage execute(final String endpointUrl, final SOAPMessage message) throws Exception {
    SOAPConnection conn = null;
    try {

        /* Create new SOAP connection */
        conn = SOAPConnectionFactory.newInstance().createConnection();

        if (logger.isDebugEnabled()) {
            logger.debug("----Inside execute, going to execute SOAP message : "
                    + message.getSOAPBody().getTextContent());
        }

        /* Call SOAP service */
        final SOAPMessage response = conn.call(message, endpointUrl);

        /* Get SOAP response body */
        final SOAPBody body = response.getSOAPBody();

        if (logger.isDebugEnabled()) {
            logger.debug("----Inside execute, has fault? :  " + body.hasFault());
        }

        if (body.hasFault() && body.getFault() != null) {

            logger.error("----Inside execute, fault :  " + body.getFault().getTextContent()
                    + ", fault reason : " + body.getFault().getFaultString());

            /* Throw error */
            throw new SOAPException(body.getFault().getTextContent());
        }
        return response;
    } catch (final Exception e) {

        logger.error("----Inside execute, error recieved :  " + e.getMessage() + ", error : " + e);

        /* Throw user error */
        throw new SOAPException(e);
    } finally {
        if (conn != null) {
            conn.close();
        }
    }
}

From source file:org.soapfromhttp.service.CallSOAP.java

/**
 * Calcule d'une proprit depuis une requte SOAP.
 *
 * @param envelope/*  w w w.  j av  a2 s . co  m*/
 * @param servicePath
 * @param method
 * @thorw CerberusException
 * @return String
 */
public String calculatePropertyFromSOAPResponse(final String envelope, final String servicePath,
        final String method) {
    String result = null;
    ByteArrayOutputStream out = null;
    // Test des inputs ncessaires.
    if (envelope != null && servicePath != null && method != null) {

        SOAPConnectionFactory soapConnectionFactory;
        SOAPConnection soapConnection = null;
        try {
            soapConnectionFactory = SOAPConnectionFactory.newInstance();
            soapConnection = soapConnectionFactory.createConnection();
            MyLogger.log(CallSOAP.class.getName(), Level.INFO, "Connection opened");

            // Cration de la requete SOAP
            MyLogger.log(CallSOAP.class.getName(), Level.INFO, "Create request");
            SOAPMessage input = createSOAPRequest(envelope, method);

            // Appel du WS
            MyLogger.log(CallSOAP.class.getName(), Level.INFO, "Calling WS");
            MyLogger.log(CallSOAP.class.getName(), Level.INFO, "Input :" + input);
            SOAPMessage soapResponse = soapConnection.call(input, servicePath);

            out = new ByteArrayOutputStream();

            soapResponse.writeTo(out);
            MyLogger.log(CallSOAP.class.getName(), Level.INFO, "WS response received");
            MyLogger.log(CallSOAP.class.getName(), Level.DEBUG, "WS response : " + out.toString());
            result = out.toString();

        } catch (SOAPException e) {
            MyLogger.log(CallSOAP.class.getName(), Level.ERROR, e.toString());
        } catch (IOException e) {
            MyLogger.log(CallSOAP.class.getName(), Level.ERROR, e.toString());
        } catch (ParserConfigurationException e) {
            MyLogger.log(CallSOAP.class.getName(), Level.ERROR, e.toString());
        } catch (SAXException e) {
            MyLogger.log(CallSOAP.class.getName(), Level.ERROR, e.toString());
        } finally {
            try {
                if (soapConnection != null) {
                    soapConnection.close();
                }
                if (out != null) {
                    out.close();
                }
                MyLogger.log(CallSOAP.class.getName(), Level.INFO, "Connection and ByteArray closed");
            } catch (SOAPException ex) {
                Logger.getLogger(CallSOAP.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(CallSOAP.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
        }
    }
    return result;
}

From source file:com.maxl.java.aips2sqlite.AllDown.java

public void downSwissindexXml(String language, String file_refdata_pharma_xml) {
    boolean disp = false;
    ProgressBar pb = new ProgressBar();

    try {//www  .ja  v a  2 s.  com
        // Start timer 
        long startTime = System.currentTimeMillis();
        if (disp)
            System.out.print("- Downloading Swissindex (" + language + ") file... ");
        else {
            pb.init("- Downloading Swissindex (" + language + ") file... ");
            pb.start();
        }

        SOAPMessage soapRequest = MessageFactory.newInstance().createMessage();

        // Setting SOAPAction header line
        MimeHeaders headers = soapRequest.getMimeHeaders();
        headers.addHeader("SOAPAction", "http://swissindex.e-mediat.net/SwissindexPharma_out_V101/DownloadAll");

        SOAPPart soapPart = soapRequest.getSOAPPart();
        SOAPEnvelope envelope = soapPart.getEnvelope();
        SOAPBody soapBody = envelope.getBody();
        // Construct SOAP request message
        SOAPElement soapBodyElement1 = soapBody.addChildElement("pharmacode");
        soapBodyElement1.addNamespaceDeclaration("",
                "http://swissindex.e-mediat.net/SwissindexPharma_out_V101");
        soapBodyElement1.addTextNode("DownloadAll");
        SOAPElement soapBodyElement2 = soapBody.addChildElement("lang");
        soapBodyElement2.addNamespaceDeclaration("",
                "http://swissindex.e-mediat.net/SwissindexPharma_out_V101");
        if (language.equals("DE"))
            soapBodyElement2.addTextNode("DE");
        else if (language.equals("FR"))
            soapBodyElement2.addTextNode("FR");
        else {
            System.err.println("down_swissindex_xml: wrong language!");
            return;
        }
        soapRequest.saveChanges();

        SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
        SOAPConnection connection = soapConnectionFactory.createConnection();
        String wsURL = "https://swissindex.refdata.ch/Swissindex/Pharma/ws_Pharma_V101.asmx?WSDL";
        SOAPMessage soapResponse = connection.call(soapRequest, wsURL);

        Document doc = soapResponse.getSOAPBody().extractContentAsDocument();
        String strBody = getStringFromDoc(doc);
        String xmlBody = prettyFormat(strBody);
        // Note: parsing the Document tree and using the removeAttribute function is hopeless! 
        xmlBody = xmlBody.replaceAll("xmlns.*?\".*?\" ", "");
        long len = writeToFile(xmlBody, file_refdata_pharma_xml);

        if (!disp)
            pb.stopp();
        long stopTime = System.currentTimeMillis();
        System.out.println("\r- Downloading Swissindex (" + language + ") file... " + len / 1024 + " kB in "
                + (stopTime - startTime) / 1000.0f + " sec");

        connection.close();

    } catch (Exception e) {
        if (!disp)
            pb.stopp();
        System.err.println(" Exception: in 'downSwissindexXml'");
        e.printStackTrace();
    }
}

From source file:com.maxl.java.aips2sqlite.AllDown.java

public void downRefdataPharmaXml(String file_refdata_pharma_xml) {
    boolean disp = false;
    ProgressBar pb = new ProgressBar();

    try {// w  ww. j av a  2  s. com
        // Start timer 
        long startTime = System.currentTimeMillis();
        if (disp)
            System.out.print("- Downloading Refdatabase pharma file... ");
        else {
            pb.init("- Downloading Refdatabase pharma file... ");
            pb.start();
        }

        // Create soaprequest
        SOAPMessage soapRequest = MessageFactory.newInstance().createMessage();
        // Set SOAPAction header line
        MimeHeaders headers = soapRequest.getMimeHeaders();
        headers.addHeader("SOAPAction", "http://refdatabase.refdata.ch/Pharma/Download");
        // Set SOAP main request part
        SOAPPart soapPart = soapRequest.getSOAPPart();
        SOAPEnvelope envelope = soapPart.getEnvelope();
        SOAPBody soapBody = envelope.getBody();
        // Construct SOAP request message
        SOAPElement soapBodyElement1 = soapBody.addChildElement("DownloadArticleInput");
        soapBodyElement1.addNamespaceDeclaration("", "http://refdatabase.refdata.ch/");
        SOAPElement soapBodyElement2 = soapBodyElement1.addChildElement("ATYPE");
        soapBodyElement2.addNamespaceDeclaration("", "http://refdatabase.refdata.ch/Article_in");
        soapBodyElement2.addTextNode("ALL");
        soapRequest.saveChanges();
        // If needed print out soapRequest in a pretty format
        // System.out.println(prettyFormatSoapXml(soapRequest));
        // Create connection to SOAP server
        SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
        SOAPConnection connection = soapConnectionFactory.createConnection();
        // wsURL contains service end point
        String wsURL = "http://refdatabase.refdata.ch/Service/Article.asmx?WSDL";
        SOAPMessage soapResponse = connection.call(soapRequest, wsURL);
        // Extract response
        Document doc = soapResponse.getSOAPBody().extractContentAsDocument();
        String strBody = getStringFromDoc(doc);
        String xmlBody = prettyFormat(strBody);
        // Note: parsing the Document tree and using the removeAttribute function is hopeless!          
        xmlBody = xmlBody.replaceAll("xmlns.*?\".*?\" ", "");

        long len = writeToFile(xmlBody, file_refdata_pharma_xml);

        if (!disp)
            pb.stopp();
        long stopTime = System.currentTimeMillis();
        System.out.println("\r- Downloading Refdata pharma file... " + len / 1024 + " kB in "
                + (stopTime - startTime) / 1000.0f + " sec");

        connection.close();

    } catch (Exception e) {
        if (!disp)
            pb.stopp();
        System.err.println(" Exception: in 'downRefdataPharmaXml'");
        e.printStackTrace();
    }
}