Example usage for javax.xml.soap SOAPEnvelope getBody

List of usage examples for javax.xml.soap SOAPEnvelope getBody

Introduction

In this page you can find the example usage for javax.xml.soap SOAPEnvelope getBody.

Prototype

public SOAPBody getBody() throws SOAPException;

Source Link

Document

Returns the SOAPBody object associated with this SOAPEnvelope object.

Usage

From source file:au.com.ors.rest.controller.AutoCheckController.java

private SOAPMessage createSOAPRequest(String driverLicenseNumber, String fullName, String postCode)
        throws Exception {
    MessageFactory messageFactory = MessageFactory.newInstance();
    SOAPMessage soapMessage = messageFactory.createMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();

    String serverURI = "http://soap.ors.com.au/pdv";

    SOAPEnvelope envelope = soapPart.getEnvelope();
    envelope.addNamespaceDeclaration("pdv", serverURI);

    SOAPBody soapBody = envelope.getBody();
    SOAPElement soapElement = soapBody.addChildElement("PDVCheckRequestMsg", "pdv");
    SOAPElement soapElementChild1 = soapElement.addChildElement("driverLicenseNumber", "pdv");
    soapElementChild1.addTextNode(driverLicenseNumber);
    SOAPElement soapElementChild2 = soapElement.addChildElement("fullName", "pdv");
    soapElementChild2.addTextNode(fullName);
    SOAPElement soapElementChild3 = soapElement.addChildElement("postCode", "pdv");
    soapElementChild3.addTextNode(postCode);

    // MimeHeaders headers = soapMessage.getMimeHeaders();
    // headers.addHeader(S, value);
    soapMessage.saveChanges();//from ww  w . jav  a2 s  . c  om

    System.out.println("Request SOAP Message:");
    soapMessage.writeTo(System.out);
    return soapMessage;
}

From source file:cn.com.ttblog.ssmbootstrap_table.webservice.LicenseHandler.java

@SuppressWarnings("unchecked")
@Override//  w ww .  j  av  a2s.  c  om
public boolean handleMessage(SOAPMessageContext context) {
    try {
        Boolean out = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
        logger.debug("LicenseHandler:{}", out);
        if (!out) {
            SOAPMessage message = context.getMessage();
            logger.debug("SOAPMessage:{}", ToStringBuilder.reflectionToString(message));
            SOAPEnvelope enve = message.getSOAPPart().getEnvelope();
            SOAPHeader header = enve.getHeader();
            SOAPBody body = enve.getBody();
            Node bn = body.getChildNodes().item(0);
            String partname = bn.getLocalName();
            if ("getUser".equals(partname)) {
                if (header == null) {
                    // ?
                    SOAPFault fault = body.addFault();
                    fault.setFaultString("??!");
                    throw new SOAPFaultException(fault);
                }
                Iterator<SOAPHeaderElement> iterator = header.extractAllHeaderElements();
                if (!iterator.hasNext()) {
                    // ?
                    SOAPFault fault = body.addFault();
                    fault.setFaultString("??!");
                    throw new SOAPFaultException(fault);
                }
                while (iterator.hasNext()) {
                    SOAPHeaderElement ele = iterator.next();
                    System.out.println(ele.getTextContent());
                }
            }
        }
    } catch (SOAPException e) {
        e.printStackTrace();
    }
    return true;
}

From source file:com.konakart.bl.modules.ordertotal.thomson.HeaderSecrityHandler.java

public boolean handleMessage(SOAPMessageContext smc) {
    Boolean outboundProperty = (Boolean) smc.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);

    if (outboundProperty.booleanValue()) {
        SOAPMessage message = smc.getMessage();

        if (log.isInfoEnabled()) {
            log.info("Adding Credentials : " + getUName() + "/" + getPWord());
        }/*w w  w. j  ava2s  .  c om*/

        try {
            SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();
            envelope.setPrefix("soapenv");
            envelope.getBody().setPrefix("soapenv");

            SOAPHeader header = envelope.addHeader();
            SOAPElement security = header.addChildElement("Security", "wsse",
                    "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");

            SOAPElement usernameToken = security.addChildElement("UsernameToken", "wsse");
            usernameToken.addAttribute(new QName("wsu:Id"), "UsernameToken-1");
            usernameToken.setAttribute("wsu:Id", "UsernameToken-1");

            usernameToken.addAttribute(new QName("xmlns:wsu"),
                    "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");

            SOAPElement username = usernameToken.addChildElement("Username", "wsse");
            username.addTextNode(getUName());

            SOAPElement password = usernameToken.addChildElement("Password", "wsse");
            password.setAttribute("Type",
                    "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText");
            password.addTextNode(getPWord());

            SOAPElement encodingType = usernameToken.addChildElement("Nonce", "wsse");
            encodingType.setAttribute("EncodingType",
                    "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary");
            encodingType.addTextNode("Encoding");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    return outboundProperty;
}

From source file:SendSOAPMessage.java

/**
 * send a simple soap message with JAXM API.
 *//* www .j av a  2 s  .c  o 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:backend.Weather.java

private SOAPMessage createSOAPRequest() throws Exception {
    MessageFactory messageFactory = MessageFactory.newInstance();
    SOAPMessage soapMessage = messageFactory.createMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();
    String serverURI = "http://ws.cdyne.com/";
    SOAPEnvelope envelope = soapPart.getEnvelope();

    SOAPBody soapBody = envelope.getBody();
    SOAPElement soapBodyElem = soapBody.addChildElement("GetCityWeatherByZIP");
    QName attributeName = new QName("xmlns");
    soapBodyElem.addAttribute(attributeName, "http://ws.cdyne.com/WeatherWS/");
    SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("ZIP");
    soapBodyElem1.addTextNode("02215");
    soapMessage.saveChanges();//www .j a va  2 s .  c o m
    return soapMessage;

}

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

/**
 * Invokes an operation using SAAJ/*w w w.  j  a v  a2  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:be.fedict.hsm.ws.impl.WSSecuritySOAPHandler.java

private void handleInboundMessage(SOAPMessageContext context) throws WSSecurityException, SOAPException {
    LOG.debug("checking WS-Security header");
    SOAPMessage soapMessage = context.getMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();

    WSSecurityEngine secEngine = new WSSecurityEngine();
    Crypto crypto = new WSSecurityCrypto();
    WSSConfig wssConfig = new WSSConfig();
    wssConfig.setWsiBSPCompliant(true);/*  w w  w  .ja v a 2  s  .  c  o  m*/
    secEngine.setWssConfig(wssConfig);
    List<WSSecurityEngineResult> results = secEngine.processSecurityHeader(soapPart, null, null, crypto);
    if (null == results) {
        this.securityAuditGeneratorBean.webServiceAuthenticationError();
        throw new SecurityException("no WS-Security results");
    }

    WSSecurityEngineResult timeStampActionResult = WSSecurityUtil.fetchActionResult(results, WSConstants.TS);
    if (null == timeStampActionResult) {
        this.securityAuditGeneratorBean.webServiceAuthenticationError();
        throw new SecurityException("no WS-Security timestamp result");
    }

    Timestamp receivedTimestamp = (Timestamp) timeStampActionResult.get(WSSecurityEngineResult.TAG_TIMESTAMP);
    if (null == receivedTimestamp) {
        this.securityAuditGeneratorBean.webServiceAuthenticationError();
        throw new SecurityException("no WS-Security timestamp");
    }

    LOG.debug("WS-Security timestamp created: " + receivedTimestamp.getCreated());
    LOG.debug("WS-Security timestamp expires: " + receivedTimestamp.getExpires());
    String timeStampIdRef = "#" + receivedTimestamp.getID();

    WSSecurityEngineResult bstActionResult = WSSecurityUtil.fetchActionResult(results, WSConstants.BST);
    if (null == bstActionResult) {
        this.securityAuditGeneratorBean.webServiceAuthenticationError();
        throw new SecurityException("no WS-Security BinarySecurityToken");
    }
    BinarySecurity binarySecurityToken = (BinarySecurity) bstActionResult
            .get(WSSecurityEngineResult.TAG_BINARY_SECURITY_TOKEN);

    WSSecurityEngineResult signActionResult = WSSecurityUtil.fetchActionResult(results, WSConstants.SIGN);
    if (null == signActionResult) {
        this.securityAuditGeneratorBean.webServiceAuthenticationError();
        throw new SecurityException("no valid XML signature");
    }
    String signatureMethod = (String) signActionResult.get(WSSecurityEngineResult.TAG_SIGNATURE_METHOD);
    LOG.debug("signature method: " + signatureMethod);
    if (false == "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256".equals(signatureMethod)) {
        this.securityAuditGeneratorBean.webServiceAuthenticationError();
        throw new SecurityException("signature algo should be RSA-SHA256");
    }
    X509Certificate certificate = (X509Certificate) signActionResult
            .get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);
    LOG.debug("certificate subject: " + certificate.getSubjectX500Principal());
    List<WSDataRef> wsDataRefs = (List<WSDataRef>) signActionResult
            .get(WSSecurityEngineResult.TAG_DATA_REF_URIS);

    SOAPEnvelope soapEnvelope = soapPart.getEnvelope();
    SOAPBody soapBody = soapEnvelope.getBody();
    String bodyIdRef = "#" + soapBody.getAttributeNS(WSU_NAMESPACE, "Id");
    String bstIdRef = "#" + binarySecurityToken.getID();

    boolean timestampDigested = false;
    boolean bodyDigested = false;
    boolean tokenDigested = false;
    for (WSDataRef wsDataRef : wsDataRefs) {
        String wsuId = wsDataRef.getWsuId();
        LOG.debug("signed wsu:Id: " + wsuId);
        LOG.debug("digest algorithm: " + wsDataRef.getDigestAlgorithm());
        if (false == "http://www.w3.org/2001/04/xmlenc#sha256".equals(wsDataRef.getDigestAlgorithm())) {
            this.securityAuditGeneratorBean.webServiceAuthenticationError(certificate);
            throw new SecurityException("digest algorithm should be SHA256");
        }
        if (timeStampIdRef.equals(wsuId)) {
            timestampDigested = true;
        } else if (bodyIdRef.equals(wsuId)) {
            bodyDigested = true;
        } else if (bstIdRef.equals(wsuId)) {
            tokenDigested = true;
        }
    }
    if (false == timestampDigested) {
        this.securityAuditGeneratorBean.webServiceAuthenticationError(certificate);
        throw new SecurityException("timestamp not digested");
    }
    if (false == bodyDigested) {
        this.securityAuditGeneratorBean.webServiceAuthenticationError(certificate);
        throw new SecurityException("SOAP Body not digested");
    }
    if (false == tokenDigested) {
        this.securityAuditGeneratorBean.webServiceAuthenticationError(certificate);
        throw new SecurityException("BinarySecurityToken not digested");
    }

    context.put(X509_ATTRIBUTE, certificate);
}

From source file:com.inbravo.scribe.rest.service.crm.ms.auth.SOAPExecutor.java

/**
 * Constructs XPath query over the SOAP message
 * /*from   www .j a v a2 s  .c  om*/
 * @param query XPath query
 * @param response SOAP message
 * @return XPath query
 * @throws SOAPException in case of SOAP issue
 * @throws JaxenException XPath problem
 */
public final XPath createXPath(final String query, final SOAPMessage response)
        throws SOAPException, JaxenException {

    /* Uses DOM to XPath mapping */
    final XPath xpath = new DOMXPath(query);

    /* Define a namespaces used in response */
    final SimpleNamespaceContext nsContext = new SimpleNamespaceContext();
    final SOAPPart sp = response.getSOAPPart();
    final SOAPEnvelope env = sp.getEnvelope();
    final SOAPBody bdy = env.getBody();

    /* Add namespaces from SOAP envelope */
    addNamespaces(nsContext, env);

    /* Add namespaces of top body element */
    final Iterator<?> bodyElements = bdy.getChildElements();
    while (bodyElements.hasNext()) {
        SOAPElement element = (SOAPElement) bodyElements.next();
        addNamespaces(nsContext, element);
    }
    xpath.setNamespaceContext(nsContext);
    return xpath;
}

From source file:com.fortify.bugtracker.tgt.archer.connection.ArcherAuthenticatingRestConnection.java

public Long addValueToValuesList(Long valueListId, String value) {
    LOG.info("[Archer] Adding value '" + value + "' to value list id " + valueListId);
    // Adding items to value lists is not supported via REST API, so we need to revert to SOAP API
    // TODO Simplify this method?
    // TODO Make this method more fail-safe (like checking for the correct response element)?
    Long result = null;/*  www  .  j  a  v  a 2 s  .c  om*/
    try {
        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage message = messageFactory.createMessage();
        SOAPPart soapPart = message.getSOAPPart();
        SOAPEnvelope envelope = soapPart.getEnvelope();
        SOAPBody body = envelope.getBody();
        SOAPElement bodyElement = body.addChildElement(
                envelope.createName("CreateValuesListValue", "", "http://archer-tech.com/webservices/"));
        bodyElement.addChildElement("sessionToken").addTextNode(tokenProviderRest.getToken());
        bodyElement.addChildElement("valuesListId").addTextNode(valueListId + "");
        bodyElement.addChildElement("valuesListValueName").addTextNode(value);
        message.saveChanges();

        SOAPMessage response = executeRequest(HttpMethod.POST,
                getBaseResource().path("/ws/field.asmx").request()
                        .header("SOAPAction", "\"http://archer-tech.com/webservices/CreateValuesListValue\"")
                        .accept("text/xml"),
                Entity.entity(message, "text/xml"), SOAPMessage.class);
        @SuppressWarnings("unchecked")
        Iterator<Object> it = response.getSOAPBody().getChildElements();
        while (it.hasNext()) {
            Object o = it.next();
            if (o instanceof SOAPElement) {
                result = new Long(((SOAPElement) o).getTextContent());
            }
        }
        System.out.println(response);
    } catch (SOAPException e) {
        throw new RuntimeException("Error executing SOAP request", e);
    }
    return result;
}

From source file:edu.duke.cabig.c3pr.webservice.integration.StudyImportExportWebServiceTest.java

private void verifySuccessulImportResponse(SOAPMessage respMsg) throws SOAPException {
    SOAPPart part = respMsg.getSOAPPart();
    SOAPEnvelope env = part.getEnvelope();
    SOAPBody body = env.getBody();
    NodeList nodes = body.getElementsByTagNameNS(SERVICE_NS, "ImportStudyResponse");
    assertEquals(1, nodes.getLength());/*w  w  w  .  j  a v  a2  s.  c  o m*/
    // element should be empty
    Element responseEl = (Element) nodes.item(0);
    assertEquals(0, responseEl.getChildNodes().getLength());
}