Example usage for javax.xml.soap SOAPMessage writeTo

List of usage examples for javax.xml.soap SOAPMessage writeTo

Introduction

In this page you can find the example usage for javax.xml.soap SOAPMessage writeTo.

Prototype

public abstract void writeTo(OutputStream out) throws SOAPException, IOException;

Source Link

Document

Writes this SOAPMessage object to the given output stream.

Usage

From source file:SendSOAPMessage.java

/**
 * send a simple soap message with JAXM API.
 *///from  w  ww  . ja  va2 s.com
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:it.cnr.icar.eric.common.soap.SOAPSender.java

void dumpMessage(String info, SOAPMessage msg) throws SOAPException {
    //if (log.isTraceEnabled()) {
    if (info != null) {
        System.err.print(info);//from   w w w.java 2 s .  c o  m
    }

    try {
        msg.writeTo(System.err);
        System.err.println();
    } catch (IOException x) {
        return;
    }
    //}
}

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

/**
 * Calcule d'une proprit depuis une requte SOAP.
 *
 * @param envelope/*from   w  ww.  j a  v  a2 s . c  o 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.hiperium.integration.access.control.SoapSignatureHandler.java

@SuppressWarnings("unchecked")
@Override//from  w  w  w  . j a v a  2s .  c o  m
public boolean handleMessage(SOAPMessageContext context) {
    LOGGER.debug("handleMessage - BEGIN");
    // Only message arriving from the client. Not processing responses.
    Boolean outbound = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
    if (!outbound) {
        // Get the sessionId from the entire HTTP Message
        StringBuffer sessionIdBuffer = new StringBuffer();
        Map<String, List<String>> map = (Map<String, List<String>>) context
                .get(MessageContext.HTTP_REQUEST_HEADERS);
        for (String session : this.getHTTPHeader(map, CommonsUtil.SESSIONID)) {
            sessionIdBuffer.append(session);
        }
        // Try to get SOAP header values from the SOAP message
        try {
            SOAPMessage msg = context.getMessage();
            if (LOGGER.isDebugEnabled()) {
                System.out.println("REQUEST:");
                msg.writeTo(System.out);
                System.out.println();
            }
            Node node = msg.getSOAPHeader().getFirstChild();

            // Header values
            NodeList nodeList = node.getChildNodes(); // Name, TimeStamp, Signature.
            if (nodeList.getLength() < 3) {
                this.generateFault(msg, "Too few header nodes!");
            }

            // Extract the required attributes.
            Long homeId = Long.valueOf(nodeList.item(0).getFirstChild().getNodeValue());
            String signature = nodeList.item(1).getFirstChild().getNodeValue();
            String timestamp = nodeList.item(2).getFirstChild().getNodeValue();
            if (StringUtils.isBlank(timestamp) || StringUtils.isBlank(signature)) {
                this.generateFault(msg, "Missing header key/value pairs!");
            }

            // Validates that the user Token exists in the DB for valid registered external Application.
            String token = this.securityBusinessDelegate.getHomeGatewayBO().findTokenInSession(homeId,
                    sessionIdBuffer.toString());
            if (StringUtils.isBlank(token)) {
                this.generateFault(msg, homeId.toString().concat(" not registered!"));
            }

            // Generate comparison signature and compare against what's sent.
            byte[] secretBytes = Signature.getBytes(token);
            String localSignature = Signature.createSignature(homeId, timestamp, secretBytes);
            if (!this.verify(signature, localSignature)) {
                this.generateFault(msg, "HMAC signatures do not match.");
            }
        } catch (Exception e) {
            throw new RuntimeException("SOAPException thrown.", e);
        }
    }
    LOGGER.debug("handleMessage - END");
    return true; //continue other handler chain
}

From source file:com.googlecode.ddom.saaj.SOAPMessageTest.java

/**
 * Tests the behavior of {@link SOAPMessage#writeTo(java.io.OutputStream)} on a message for
 * which no content has been specified.// www  .  j a v a2s .c o  m
 * 
 * @throws Exception
 */
@Validated
@Test
public void testWriteToEmpty() throws Exception {
    SOAPMessage message = getFactory().createMessage();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    message.writeTo(baos);
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    Document doc = dbf.newDocumentBuilder().parse(new ByteArrayInputStream(baos.toByteArray()));
    Element envelope = doc.getDocumentElement();
    assertEquals("Envelope", envelope.getLocalName());
    NodeList children = envelope.getElementsByTagNameNS("*", "*");
    assertEquals(2, children.getLength());
    assertEquals("Header", children.item(0).getLocalName());
    assertEquals("Body", children.item(1).getLocalName());
}

From source file:com.usps.UspsServlet.java

private void generateUSPSsoapRequest(String parameter) {
    try {// ww w.jav a  2  s . c  o 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:net.bpelunit.framework.control.ws.WebServiceHandler.java

private void sendResponse(HttpServletResponse response, int code, SOAPMessage body) throws IOException {
    // TODO Refactor all message serializations into an own utility method
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    try {/*  w  w  w. ja  v a2  s.com*/
        body.writeTo(out);
        sendResponse(response, code, out.toString());
    } catch (SOAPException e) {
        sendResponse(response, code, "");
    }
}

From source file:be.fedict.eid.dss.client.LoggingSoapHandler.java

public boolean handleMessage(SOAPMessageContext context) {
    LOG.debug("handle message");
    Boolean outboundProperty = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
    LOG.debug("outbound message: " + outboundProperty);
    SOAPMessage soapMessage = context.getMessage();
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    try {//ww  w. j a  va 2  s .c o m
        if (this.logToFile) {
            File tmpFile = File.createTempFile(
                    "eid-dss-soap-" + (outboundProperty ? "outbound" : "inbound") + "-", ".xml");
            FileOutputStream fileOutputStream = new FileOutputStream(tmpFile);
            soapMessage.writeTo(fileOutputStream);
            fileOutputStream.close();
            LOG.debug("tmp file: " + tmpFile.getAbsolutePath());
        }
        soapMessage.writeTo(output);
    } catch (Exception e) {
        LOG.error("SOAP error: " + e.getMessage());
    }
    LOG.debug("SOAP message: " + output.toString());
    return true;
}

From source file:net.bpelunit.framework.control.deploy.ode.ODERequestEntityFactory.java

private void prepareUndeploySOAP(String packageId) throws SOAPException, IOException {
    MessageFactory mFactory = MessageFactory.newInstance();
    SOAPMessage message = mFactory.createMessage();
    SOAPBody body = message.getSOAPBody();

    SOAPElement xmlUndeploy = body.addChildElement(ODE_ELEMENT_UNDEPLOY);
    SOAPElement xmlPackageName = xmlUndeploy.addChildElement(ODE_ELEMENT_PACKAGENAME);
    xmlPackageName.setTextContent(packageId);

    ByteArrayOutputStream b = new ByteArrayOutputStream();
    message.writeTo(b);
    fContent = b.toString();// w w  w .  java  2  s . co  m
}

From source file:com.googlecode.ddom.saaj.SOAPMessageTest.java

/**
 * Tests the behavior of {@link SOAPPart#getContent()} for a plain SOAP message created from an
 * input stream.//from w  w w  .j  a va2  s  .co  m
 * 
 * @throws Exception
 * 
 * @see SOAPPartTest#testGetContent()
 */
@Validated
@Test
public void testWriteTo() throws Exception {
    MimeHeaders headers = new MimeHeaders();
    headers.addHeader("Content-Type", messageSet.getVersion().getContentType() + "; charset=utf-8");
    InputStream in = messageSet.getTestMessage("message.xml");
    byte[] orgContent = IOUtils.toByteArray(in);
    SOAPMessage message = getFactory().createMessage(headers, new ByteArrayInputStream(orgContent));

    // Get the content before accessing the SOAP part
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    message.writeTo(baos);
    byte[] content1 = baos.toByteArray();
    assertTrue(Arrays.equals(orgContent, content1));

    // Now access the SOAP part and get the content again
    message.getSOAPPart().getEnvelope();
    baos = new ByteArrayOutputStream();
    message.writeTo(baos);
    byte[] content2 = baos.toByteArray();
    // The content is equivalent, but not exactly the same
    assertFalse(Arrays.equals(orgContent, content2));
}