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:org.keycloak.testsuite.adapter.servlet.SAMLServletAdapterTest.java

@Test
public void testSuccessfulEcpFlow() throws Exception {
    Response authnRequestResponse = ClientBuilder.newClient().target(ecpSPPage.toString()).request()
            .header("Accept", "text/html; application/vnd.paos+xml")
            .header("PAOS", "ver='urn:liberty:paos:2003-08' ;'urn:oasis:names:tc:SAML:2.0:profiles:SSO:ecp'")
            .get();// www .  jav a  2 s .c om

    SOAPMessage authnRequestMessage = MessageFactory.newInstance().createMessage(null,
            new ByteArrayInputStream(authnRequestResponse.readEntity(byte[].class)));

    //printDocument(authnRequestMessage.getSOAPPart().getContent(), System.out);

    Iterator<SOAPHeaderElement> it = authnRequestMessage.getSOAPHeader().<SOAPHeaderElement>getChildElements(
            new QName("urn:oasis:names:tc:SAML:2.0:profiles:SSO:ecp", "Request"));
    SOAPHeaderElement ecpRequestHeader = it.next();
    NodeList idpList = ecpRequestHeader.getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:protocol",
            "IDPList");

    Assert.assertThat("No IDPList returned from Service Provider", idpList.getLength(), is(1));

    NodeList idpEntries = idpList.item(0).getChildNodes();

    Assert.assertThat("No IDPEntry returned from Service Provider", idpEntries.getLength(), is(1));

    String singleSignOnService = null;

    for (int i = 0; i < idpEntries.getLength(); i++) {
        Node item = idpEntries.item(i);
        NamedNodeMap attributes = item.getAttributes();
        Node location = attributes.getNamedItem("Loc");

        singleSignOnService = location.getNodeValue();
    }

    Assert.assertThat("Could not obtain SSO Service URL", singleSignOnService, notNullValue());

    Document authenticationRequest = authnRequestMessage.getSOAPBody().getFirstChild().getOwnerDocument();
    String username = "pedroigor";
    String password = "password";
    String pair = username + ":" + password;
    String authHeader = "Basic " + Base64.encodeBytes(pair.getBytes());

    Response authenticationResponse = ClientBuilder.newClient().target(singleSignOnService).request()
            .header(HttpHeaders.AUTHORIZATION, authHeader)
            .post(Entity.entity(DocumentUtil.asString(authenticationRequest), "text/xml"));

    Assert.assertThat(authenticationResponse.getStatus(), is(OK.getStatusCode()));

    SOAPMessage responseMessage = MessageFactory.newInstance().createMessage(null,
            new ByteArrayInputStream(authenticationResponse.readEntity(byte[].class)));

    //printDocument(responseMessage.getSOAPPart().getContent(), System.out);

    SOAPHeader responseMessageHeaders = responseMessage.getSOAPHeader();

    NodeList ecpResponse = responseMessageHeaders.getElementsByTagNameNS(
            JBossSAMLURIConstants.ECP_PROFILE.get(), JBossSAMLConstants.RESPONSE__ECP.get());

    Assert.assertThat("No ECP Response", ecpResponse.getLength(), is(1));

    Node samlResponse = responseMessage.getSOAPBody().getFirstChild();

    Assert.assertThat(samlResponse, notNullValue());

    ResponseType responseType = (ResponseType) SAMLParser.getInstance().parse(samlResponse);
    StatusCodeType statusCode = responseType.getStatus().getStatusCode();

    Assert.assertThat(statusCode.getValue().toString(), is(JBossSAMLURIConstants.STATUS_SUCCESS.get()));
    Assert.assertThat(responseType.getDestination(), is(ecpSPPage.toString() + "/"));
    Assert.assertThat(responseType.getSignature(), notNullValue());
    Assert.assertThat(responseType.getAssertions().size(), is(1));

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

    samlResponseRequest.getSOAPBody().addDocument(responseMessage.getSOAPBody().extractContentAsDocument());

    ByteArrayOutputStream os = new ByteArrayOutputStream();

    samlResponseRequest.writeTo(os);

    Response serviceProviderFinalResponse = ClientBuilder.newClient().target(responseType.getDestination())
            .request().post(Entity.entity(os.toByteArray(), "application/vnd.paos+xml"));

    Map<String, NewCookie> cookies = serviceProviderFinalResponse.getCookies();

    Invocation.Builder resourceRequest = ClientBuilder.newClient().target(responseType.getDestination())
            .request();

    for (NewCookie cookie : cookies.values()) {
        resourceRequest.cookie(cookie);
    }

    Response resourceResponse = resourceRequest.get();
    Assert.assertThat(resourceResponse.readEntity(String.class), containsString("pedroigor"));
}

From source file:it.cnr.icar.eric.server.interfaces.soap.RegistrySAMLServlet.java

@SuppressWarnings("unchecked")
public SOAPMessage onMessage(SOAPMessage msg, HttpServletRequest req, HttpServletResponse resp) {

    SOAPMessage soapResponse = null;
    SOAPHeader soapHeader = null;

    try {/*from   ww  w . j av  a 2s .c  om*/

        // extract SOAP related parts from incoming SOAP message

        // set 'soapHeader' variable ASAP (before "firstly")
        SOAPPart soapPart = msg.getSOAPPart();
        SOAPEnvelope soapEnvelope = soapPart.getEnvelope();
        SOAPBody soapBody = soapEnvelope.getBody();
        soapHeader = soapEnvelope.getHeader();

        /****************************************************************
         * 
         * REPOSITORY ITEM HANDLING (IN) REPOSITORY ITEM HANDLING (IN)
         * 
         ***************************************************************/

        // Firstly we put save the attached repository items in a map

        HashMap<String, Object> idToRepositoryItemMap = new HashMap<String, Object>();
        Iterator<AttachmentPart> apIter = msg.getAttachments();

        while (apIter.hasNext()) {
            AttachmentPart ap = apIter.next();

            // Get the content for the attachment
            RepositoryItem ri = processIncomingAttachment(ap);
            idToRepositoryItemMap.put(ri.getId(), ri);
        }

        /****************************************************************
         * 
         * LOGGING (IN) LOGGING (IN) LOGGING (IN) LOGGING (IN)
         * 
         ***************************************************************/

        // Log received message

        if (log.isTraceEnabled()) {
            // Warning! BAOS.toString() uses platform's default encoding
            ByteArrayOutputStream msgOs = new ByteArrayOutputStream();
            msg.writeTo(msgOs);
            msgOs.close();
            log.trace("incoming message:\n" + msgOs.toString());
        }

        /****************************************************************
         * 
         * MESSAGE VERIFICATION (IN) MESSAGE VERIFICATION (IN)
         * 
         ***************************************************************/
        CredentialInfo credentialInfo = new CredentialInfo();

        WSS4JSecurityUtilSAML.verifySOAPEnvelopeOnServerSAML(soapEnvelope, credentialInfo);

        /****************************************************************
         * 
         * RS:REQUEST HANDLING RS:REQUEST HANDLING RS:REQUEST
         * 
         ***************************************************************/

        // The ebXML registry request is the only element in the SOAPBody

        StringWriter requestXML = new StringWriter(); // The request as an
        // XML String
        String requestRootElement = null;

        Iterator<?> iter = soapBody.getChildElements();
        int i = 0;

        while (iter.hasNext()) {
            Object obj = iter.next();

            if (!(obj instanceof SOAPElement)) {
                continue;
            }

            if (i++ == 0) {
                SOAPElement elem = (SOAPElement) obj;
                Name name = elem.getElementName();
                requestRootElement = name.getLocalName();

                StreamResult result = new StreamResult(requestXML);
                TransformerFactory tf = TransformerFactory.newInstance();
                Transformer trans = tf.newTransformer();
                trans.transform(new DOMSource(elem), result);
            } else {
                throw new RegistryException(
                        ServerResourceBundle.getInstance().getString("message.invalidRequest"));
            }
        }

        if (requestRootElement == null) {
            throw new RegistryException(
                    ServerResourceBundle.getInstance().getString("message.noebXMLRegistryRequest"));
        }

        // unmarshalling request to message
        Object message = bu.getRequestObject(requestRootElement, requestXML.toString());

        if (message instanceof JAXBElement<?>) {
            // If Element; take ComplexType from Element
            message = ((JAXBElement<?>) message).getValue();
        }

        SAMLRequest request = new SAMLRequest(req, credentialInfo.assertion, message, idToRepositoryItemMap);

        Response response = request.process();

        /****************************************************************
         * 
         * RESPONSE HANDLING RESPONSE HANDLING RESPONSE HANDLING
         * 
         ***************************************************************/

        soapResponse = createResponseSOAPMessage(response);

        if (response.getIdToRepositoryItemMap().size() > 0 && (response.getMessage().getStatus()
                .equals(BindingUtility.CANONICAL_RESPONSE_STATUS_TYPE_ID_Success))) {

            idToRepositoryItemMap = response.getIdToRepositoryItemMap();
            Iterator<String> mapKeysIter = idToRepositoryItemMap.keySet().iterator();

            while (mapKeysIter.hasNext()) {
                String id = mapKeysIter.next();
                RepositoryItem repositoryItem = (RepositoryItem) idToRepositoryItemMap.get(id);

                String cid = WSS4JSecurityUtilSAML.convertUUIDToContentId(id);
                DataHandler dh = repositoryItem.getDataHandler();
                AttachmentPart ap = soapResponse.createAttachmentPart(dh);
                ap.setContentId(cid);
                soapResponse.addAttachmentPart(ap);

                if (log.isTraceEnabled()) {
                    log.trace("adding attachment: contentId=" + id);
                }
            }
        }

    } catch (Throwable t) {
        // Do not log ObjectNotFoundException as it clutters the log
        if (!(t instanceof ObjectNotFoundException)) {
            log.error(ServerResourceBundle.getInstance().getString("message.CaughtException",
                    new Object[] { t.getMessage() }), t);
            Throwable cause = t.getCause();
            while (cause != null) {
                log.error(ServerResourceBundle.getInstance().getString("message.CausedBy",
                        new Object[] { cause.getMessage() }), cause);
                cause = cause.getCause();
            }
        }

        soapResponse = createFaultSOAPMessage(t, soapHeader);
    }

    if (log.isTraceEnabled()) {
        try {
            ByteArrayOutputStream rspOs = new ByteArrayOutputStream();
            soapResponse.writeTo(rspOs);
            rspOs.close();
            // Warning! BAOS.toString() uses platform's default encoding
            log.trace("response message:\n" + rspOs.toString());
        } catch (Exception e) {
            log.error(ServerResourceBundle.getInstance().getString("message.FailedToLogResponseMessage",
                    new Object[] { e.getMessage() }), e);
        }
    }
    return soapResponse;
}

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

/**
 * Invokes an operation using SAAJ//from  ww  w . j  av  a  2 s.  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:it.cnr.icar.eric.server.interfaces.soap.RegistryBSTServlet.java

public SOAPMessage onMessage(SOAPMessage msg, HttpServletRequest req, HttpServletResponse resp) {
    //System.err.println("onMessage called for RegistrySOAPServlet");
    SOAPMessage soapResponse = null;
    SOAPHeader sh = null;// w ww  .  jav a2 s.  c om

    try {
        // set 'sh' variable ASAP (before "firstly")
        SOAPPart sp = msg.getSOAPPart();
        SOAPEnvelope se = sp.getEnvelope();
        SOAPBody sb = se.getBody();
        sh = se.getHeader();

        // Firstly we put save the attached repository items in a map
        HashMap<String, Object> idToRepositoryItemMap = new HashMap<String, Object>();
        Iterator<?> apIter = msg.getAttachments();
        while (apIter.hasNext()) {
            AttachmentPart ap = (AttachmentPart) apIter.next();

            //Get the content for the attachment
            RepositoryItem ri = processIncomingAttachment(ap);
            idToRepositoryItemMap.put(ri.getId(), ri);
        }

        // Log received message
        //if (log.isTraceEnabled()) {
        // Warning! BAOS.toString() uses platform's default encoding
        /*
        ByteArrayOutputStream msgOs = new ByteArrayOutputStream();
        msg.writeTo(msgOs);
        msgOs.close();
        System.err.println(msgOs.toString());
        */
        //System.err.println(sb.getTextContent());
        //    log.trace("incoming message:\n" + msgOs.toString());
        //}

        // verify signature
        // returns false if no security header, throws exception if invalid
        CredentialInfo credentialInfo = new CredentialInfo();

        boolean noRegRequired = Boolean.valueOf(
                CommonProperties.getInstance().getProperty("eric.common.noUserRegistrationRequired", "false"))
                .booleanValue();

        if (!noRegRequired) {
            WSS4JSecurityUtilBST.verifySOAPEnvelopeOnServerBST(se, credentialInfo);
        }

        //The ebXML registry request is the only element in the SOAPBody
        StringWriter requestXML = new StringWriter(); //The request as an XML String
        String requestRootElement = null;
        Iterator<?> iter = sb.getChildElements();
        int i = 0;

        while (iter.hasNext()) {
            Object obj = iter.next();

            if (!(obj instanceof SOAPElement)) {
                continue;
            }

            if (i++ == 0) {
                SOAPElement elem = (SOAPElement) obj;
                Name name = elem.getElementName();
                requestRootElement = name.getLocalName();

                StreamResult result = new StreamResult(requestXML);

                TransformerFactory tf = TransformerFactory.newInstance();
                Transformer trans = tf.newTransformer();
                trans.transform(new DOMSource(elem), result);
            } else {
                throw new RegistryException(
                        ServerResourceBundle.getInstance().getString("message.invalidRequest"));
            }
        }

        if (requestRootElement == null) {
            throw new RegistryException(
                    ServerResourceBundle.getInstance().getString("message.noebXMLRegistryRequest"));
        }

        // unmarshalling request to message
        Object message = bu.getRequestObject(requestRootElement, requestXML.toString());

        if (message instanceof JAXBElement<?>) {
            // If Element; take ComplexType from Element
            message = ((JAXBElement<?>) message).getValue();

        }

        // request sets ServerContext with ComplexType: RegistryObjectType
        BSTRequest request = new BSTRequest(req, credentialInfo, message, idToRepositoryItemMap);

        Response response = request.process();

        // response.getMessage() is ComplexType again

        soapResponse = createResponseSOAPMessage(response);

        if (response.getIdToRepositoryItemMap().size() > 0 && (response.getMessage().getStatus()
                .equals(BindingUtility.CANONICAL_RESPONSE_STATUS_TYPE_ID_Success))) {

            idToRepositoryItemMap = response.getIdToRepositoryItemMap();
            Iterator<?> mapKeysIter = idToRepositoryItemMap.keySet().iterator();

            while (mapKeysIter.hasNext()) {
                String id = (String) mapKeysIter.next();
                RepositoryItem repositoryItem = (RepositoryItem) idToRepositoryItemMap.get(id);

                String cid = WSS4JSecurityUtilBST.convertUUIDToContentId(id);
                DataHandler dh = repositoryItem.getDataHandler();
                AttachmentPart ap = soapResponse.createAttachmentPart(dh);
                ap.setMimeHeader("Content-Type", "text/xml");
                ap.setContentId(cid);
                soapResponse.addAttachmentPart(ap);

                if (log.isTraceEnabled()) {
                    log.trace("adding attachment: contentId=" + id);
                }
            }

        }

    } catch (Throwable t) {
        //Do not log ObjectNotFoundException as it clutters the log
        if (!(t instanceof ObjectNotFoundException)) {
            log.error(ServerResourceBundle.getInstance().getString("message.CaughtException",
                    new Object[] { t.getMessage() }), t);
            Throwable cause = t.getCause();
            while (cause != null) {
                log.error(ServerResourceBundle.getInstance().getString("message.CausedBy",
                        new Object[] { cause.getMessage() }), cause);
                cause = cause.getCause();
            }
        }

        soapResponse = createFaultSOAPMessage(t, sh);
    }

    if (log.isTraceEnabled()) {
        try {
            ByteArrayOutputStream rspOs = new ByteArrayOutputStream();
            soapResponse.writeTo(rspOs);
            rspOs.close();
            // Warning! BAOS.toString() uses platform's default encoding
            log.trace("response message:\n" + rspOs.toString());
        } catch (Exception e) {
            log.error(ServerResourceBundle.getInstance().getString("message.FailedToLogResponseMessage",
                    new Object[] { e.getMessage() }), e);
        }
    }
    return soapResponse;
}

From source file:org.apache.camel.component.cxf.converter.CxfConverter.java

@Converter
public static String soapMessageToString(final SOAPMessage soapMessage) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {//  www  . ja  va2  s  .c  om
        soapMessage.writeTo(baos);
    } catch (Exception e) {
        LOG.error("Get the exception when converting the SOAPMessage into String, the exception is " + e);
    }
    return baos.toString();
}

From source file:org.cerberus.service.soap.impl.SoapService.java

@Override
public AnswerItem<SOAPExecution> callSOAP(String envelope, String servicePath, String method,
        String attachmentUrl) {/*from   www . j  av  a  2s.  c  om*/
    AnswerItem result = new AnswerItem();
    SOAPExecution executionSOAP = new SOAPExecution();
    ByteArrayOutputStream out = null;
    MessageEvent message = null;

    if (StringUtils.isNullOrEmpty(servicePath)) {
        message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSOAP_SERVICEPATHMISSING);
        result.setResultMessage(message);
        return result;
    }
    if (StringUtils.isNullOrEmpty(method)) {
        message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSOAP_METHODMISSING);
        result.setResultMessage(message);
        return result;
    }
    if (StringUtils.isNullOrEmpty(envelope)) {
        message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSOAP_ENVELOPEMISSING);
        result.setResultMessage(message);
        return result;
    }

    SOAPConnectionFactory soapConnectionFactory;
    SOAPConnection soapConnection = null;
    try {
        //Initialize SOAP Connection
        soapConnectionFactory = SOAPConnectionFactory.newInstance();
        soapConnection = soapConnectionFactory.createConnection();
        MyLogger.log(SoapService.class.getName(), Level.DEBUG, "Connection opened");

        // Create SOAP Request
        MyLogger.log(SoapService.class.getName(), Level.DEBUG, "Create request");
        SOAPMessage input = createSoapRequest(envelope, method);

        //Add attachment File if specified
        //TODO: this feature is not implemented yet therefore is always empty!
        if (!StringUtils.isNullOrEmpty(attachmentUrl)) {
            this.addAttachmentPart(input, attachmentUrl);
        }

        // Store the SOAP Call
        out = new ByteArrayOutputStream();
        input.writeTo(out);
        MyLogger.log(SoapService.class.getName(), Level.DEBUG, "WS call : " + out.toString());
        executionSOAP.setSOAPRequest(input);
        result.setItem(executionSOAP);

        // Call the WS
        MyLogger.log(SoapService.class.getName(), Level.DEBUG, "Calling WS");
        SOAPMessage soapResponse = soapConnection.call(input, servicePath);
        MyLogger.log(SoapService.class.getName(), Level.DEBUG, "Called WS");
        out = new ByteArrayOutputStream();

        // Store the response
        soapResponse.writeTo(out);
        MyLogger.log(SoapService.class.getName(), Level.DEBUG, "WS response received");
        MyLogger.log(SoapService.class.getName(), Level.DEBUG, "WS response : " + out.toString());
        executionSOAP.setSOAPResponse(soapResponse);

        message = new MessageEvent(MessageEventEnum.ACTION_SUCCESS_CALLSOAP);
        message.setDescription(
                message.getDescription().replace("%SERVICEPATH%", servicePath).replace("%SOAPMETHOD%", method));
        result.setItem(executionSOAP);

    } catch (SOAPException | UnsupportedOperationException | IOException | SAXException
            | ParserConfigurationException | CerberusException e) {
        MyLogger.log(SoapService.class.getName(), Level.ERROR, e.toString());
        message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSOAP);
        message.setDescription(message.getDescription().replace("%SERVICEPATH%", servicePath)
                .replace("%SOAPMETHOD%", method).replace("%DESCRIPTION%", e.getMessage()));
        result.setResultMessage(message);
        return result;
    } finally {
        try {
            if (soapConnection != null) {
                soapConnection.close();
            }
            if (out != null) {
                out.close();
            }
        } catch (SOAPException | IOException ex) {
            Logger.getLogger(SoapService.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } finally {
            result.setResultMessage(message);
        }
    }

    return result;
}

From source file:org.jboss.jaxr.juddi.transport.WS4EESaajTransport.java

public Element send(Element request, URL endpointURL) throws RegistryException {
    log.debug("Request message:" + XMLUtils.toString(request));
    if ("true".equalsIgnoreCase(debugProp))
        System.out.println("Request Element:" + XMLUtils.toString(request));

    Element response = null;/*from   www.ja v a2  s .co  m*/
    try {
        MessageFactory msgFactory = MessageFactory.newInstance();
        SOAPMessage message = msgFactory.createMessage();
        message.getSOAPHeader().detachNode();
        SOAPPart soapPart = message.getSOAPPart();
        SOAPBody soapBody = soapPart.getEnvelope().getBody();
        soapBody.addChildElement(getSOAPElement(soapBody, request));
        //There seems to be a bug in the Saaj/Axis implementation that requires
        //message to be written to an output stream
        ByteArrayOutputStream by = new ByteArrayOutputStream();
        message.writeTo(by); //Does not do anything
        by.close();
        if ("true".equalsIgnoreCase(debugProp))
            message.writeTo(System.out);

        //Make the SAAJ Call now
        SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
        SOAPConnection connection = soapConnectionFactory.createConnection();
        SOAPMessage soapResponse = connection.call(message, endpointURL);
        if ("true".equalsIgnoreCase(debugProp)) {
            System.out.println("Response is:");
            soapResponse.writeTo(System.out);
        }

        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) {
        ex.printStackTrace();
        log.error(ex);
        throw new RegistryException(ex);
    }

    log.debug("Response message:" + XMLUtils.getText(response));

    return response;
}

From source file:org.jbpm.bpel.integration.soap.SoapUtilTest.java

private static SOAPMessage writeAndRead(SOAPMessage soapMessage) throws SOAPException, IOException {
    // write to memory sink
    ByteArrayOutputStream soapSink = new ByteArrayOutputStream();
    soapMessage.writeTo(soapSink);
    soapSink.writeTo(System.out);
    System.out.println();/*from   w w w  . j  a  v  a 2 s  . c  o m*/
    // read from memory source
    return MessageFactory.newInstance().createMessage(null, new ByteArrayInputStream(soapSink.toByteArray()));
}

From source file:org.openhab.binding.fritzboxtr064.internal.Tr064Comm.java

/**
 * Converts SOAP message into string.//ww w  .  j a va  2s.c o m
 *
 * @param sm
 * @return
 */
public static String soapToString(SOAPMessage sm) {
    String strMsg = "";
    try {
        ByteArrayOutputStream xmlStream = new ByteArrayOutputStream();
        sm.writeTo(xmlStream);
        strMsg = new String(xmlStream.toByteArray());
    } catch (Exception e) {
        logger.debug("Not able to parse SOAP message: {}", sm, e);
    }
    return strMsg;
}