Example usage for javax.xml.soap SOAPMessage getSOAPPart

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

Introduction

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

Prototype

public abstract SOAPPart getSOAPPart();

Source Link

Document

Gets the SOAP part of this SOAPMessage object.

Usage

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

@Validated
@Test/*  w w  w  .j  ava 2 s  .  c o m*/
public void testWriteToWithAttachment() throws Exception {
    SOAPMessage message = getFactory().createMessage();
    message.getSOAPPart().getEnvelope().getBody().addBodyElement(new QName("urn:ns", "test", "p"));
    AttachmentPart attachment = message.createAttachmentPart();
    attachment.setDataHandler(new DataHandler("This is a test", "text/plain; charset=iso-8859-15"));
    message.addAttachmentPart(attachment);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    message.writeTo(baos);
    System.out.write(baos.toByteArray());
    MimeMultipart mp = new MimeMultipart(new ByteArrayDataSource(baos.toByteArray(), "multipart/related"));
    assertEquals(2, mp.getCount());
    BodyPart part1 = mp.getBodyPart(0);
    // TODO
    //        assertEquals(messageSet.getVersion().getContentType(), part1.getContentType());
    BodyPart part2 = mp.getBodyPart(1);
    // Note: text/plain is the default content type, so we need to include the parameters in the assertion
    assertEquals("text/plain; charset=iso-8859-15", part2.getContentType());
}

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

/**
 * Tests that {@link SOAPMessage#writeTo(java.io.OutputStream)} performs namespace repairing.
 * /*from w w w .  j  ava 2 s .c  om*/
 * @throws Exception
 */
@Validated
@Test
public void testWriteToNamespaceRepairing() throws Exception {
    SOAPMessage message = getFactory().createMessage();
    SOAPPart part = message.getSOAPPart();
    SOAPBody body = part.getEnvelope().getBody();
    body.appendChild(part.createElementNS("urn:ns", "p:test"));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    message.writeTo(baos);
    String content = baos.toString("UTF-8");
    assertTrue(content.contains("<p:test xmlns:p=\"urn:ns\"/>"));
}

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);//from  w ww  .ja  v a2  s  . co 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:ee.sk.hwcrypto.demo.controller.SigningController.java

private SOAPMessage SOAPQuery(String req) {
    try {/*from  ww w  . jav  a2  s  .  c om*/
        SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
        SOAPConnection soapConnection = soapConnectionFactory.createConnection();

        String url = "http://www.sk.ee/DigiDocService/DigiDocService_2_3.wsdl";

        MessageFactory messageFactory = MessageFactory.newInstance();
        InputStream is = new ByteArrayInputStream(req.getBytes());
        SOAPMessage soapMessage = messageFactory.createMessage(null, is);
        SOAPPart soapPart = soapMessage.getSOAPPart();

        String serverURI = "https://www.openxades.org:8443/DigiDocService/";

        // SOAP Envelope
        SOAPEnvelope envelope = soapPart.getEnvelope();
        envelope.addNamespaceDeclaration("", url);
        MimeHeaders headers = soapMessage.getMimeHeaders();
        headers.addHeader("SOAPAction", "");
        soapMessage.saveChanges();

        SOAPMessage soapResponse = soapConnection.call(soapMessage, serverURI);

        return soapResponse;
    } catch (Exception e) {
        log.error("SOAP Exception " + e);
    }
    return null;
}

From source file:com.qubit.solution.fenixedu.bennu.webservices.services.server.BennuWebServiceHandler.java

@Override
public boolean handleMessage(SOAPMessageContext context) {
    Boolean isRequest = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);

    //for response message only, true for outbound messages, false for inbound
    if (!isRequest) {
        try {//www  .jav  a 2 s  .c o  m

            WebServiceServerConfiguration configuration = getWebServiceServerConfiguration(
                    ((com.sun.xml.ws.api.server.WSEndpoint) context.get("com.sun.xml.ws.api.server.WSEndpoint"))
                            .getImplementationClass().getName());

            SOAPMessage soapMsg = context.getMessage();
            SOAPEnvelope soapEnv = soapMsg.getSOAPPart().getEnvelope();
            SOAPHeader soapHeader = soapEnv.getHeader();

            if (!configuration.isActive()) {
                generateSOAPErrorMessage(soapMsg, "Sorry webservice is disabled at application level!");
            }

            if (configuration.isAuthenticatioNeeded()) {

                if (configuration.isUsingWSSecurity()) {
                    if (soapHeader == null) {
                        generateSOAPErrorMessage(soapMsg,
                                "No header in message, unabled to validate security credentials");
                    }

                    String username = null;
                    String password = null;
                    String nonce = null;
                    String created = null;

                    Iterator<SOAPElement> childElements = soapHeader.getChildElements(QNAME_WSSE_SECURITY);
                    if (childElements.hasNext()) {
                        SOAPElement securityElement = childElements.next();
                        Iterator<SOAPElement> usernameTokens = securityElement
                                .getChildElements(QNAME_WSSE_USERNAME_TOKEN);
                        if (usernameTokens.hasNext()) {
                            SOAPElement usernameToken = usernameTokens.next();
                            username = ((SOAPElement) usernameToken.getChildElements(QNAME_WSSE_USERNAME)
                                    .next()).getValue();
                            password = ((SOAPElement) usernameToken.getChildElements(QNAME_WSSE_PASSWORD)
                                    .next()).getValue();
                            nonce = ((SOAPElement) usernameToken.getChildElements(QNAME_WSSE_NONCE).next())
                                    .getValue();
                            created = ((SOAPElement) usernameToken.getChildElements(QNAME_WSSE_CREATED).next())
                                    .getValue();
                        }
                    }
                    if (username == null || password == null || nonce == null || created == null) {
                        generateSOAPErrorMessage(soapMsg,
                                "Missing information, unabled to validate security credentials");
                    }

                    SecurityHeader securityHeader = new SecurityHeader(configuration, username, password, nonce,
                            created);
                    if (!securityHeader.isValid()) {
                        generateSOAPErrorMessage(soapMsg, "Invalid credentials");
                    } else {
                        context.put(BennuWebService.SECURITY_HEADER, securityHeader);
                        context.setScope(BennuWebService.SECURITY_HEADER, Scope.APPLICATION);
                    }
                } else {
                    com.sun.xml.ws.transport.Headers httpHeader = (Headers) context
                            .get(MessageContext.HTTP_REQUEST_HEADERS);
                    String username = null;
                    String password = null;
                    List<String> list = httpHeader.get("authorization");
                    if (list != null) {
                        for (String value : list) {
                            if (value.startsWith("Basic")) {
                                String[] split = value.split(" ");
                                try {
                                    String decoded = new String(Base64.decodeBase64(split[1]), "UTF-8");
                                    String[] split2 = decoded.split(":");
                                    if (split2.length == 2) {
                                        username = split2[0];
                                        password = split2[1];
                                    }
                                } catch (UnsupportedEncodingException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }

                    if (username == null || password == null) {
                        generateSOAPErrorMessage(soapMsg,
                                "Missing information, unabled to validate security credentials");
                    }

                    if (!configuration.validate(username, password)) {
                        generateSOAPErrorMessage(soapMsg, "Invalid credentials");
                    }
                }
            }

        } catch (SOAPException e) {
            System.err.println(e);
        }
    }

    //continue other handler chain
    return true;
}

From source file:eu.payzen.webservices.sdk.handler.soap.HeaderHandler.java

/**
 * Takes the outgoing SOAP message and modifies it adding the header 
 * information/*from  w  w  w  . j a  v a2s. co  m*/
 * 
 * @param smc SOAP message context
 * @return boolean indicating outbound property
 */
public boolean handleMessage(SOAPMessageContext smc) {

    Boolean outboundProperty = (Boolean) smc.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);

    if (Boolean.TRUE.equals(outboundProperty)) {

        SOAPMessage message = smc.getMessage();

        try {
            SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();

            //Creates header into SOAP envelope
            SOAPHeader header = envelope.getHeader();
            if (header == null) {
                header = envelope.addHeader();
            }

            // Add shopId
            addHeaderField(header, "shopId", this.shopId);

            // Add User name
            if (wsUser != null) {
                addHeaderField(header, "wsUser", this.wsUser);
            }

            // Add return url
            if (returnUrl != null) {
                addHeaderField(header, "returnUrl", this.returnUrl);
            }

            // Add ecsPaymentId
            if (ecsPaymentId != null) {
                addHeaderField(header, "ecsPaymentId", this.ecsPaymentId);
            }

            // Add remoteId
            if (remoteId != null) {
                addHeaderField(header, "remoteId", this.remoteId);
            }

            //DynamicHeaders
            if (dynamicHeaders != null) {
                for (String key : dynamicHeaders.keySet()) {
                    String value = dynamicHeaders.get(key);
                    if (value != null) {
                        addHeaderField(header, key, value);
                    }
                }
            }

            // Timestamp
            TimeZone tz = TimeZone.getTimeZone("UTC");
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
            df.setTimeZone(tz);
            String nowAsISO = df.format(new Date());
            addHeaderField(header, "timestamp", nowAsISO);

            // Mode
            addHeaderField(header, "mode", this.mode);

            // Add requestId
            String requestId = UUID.randomUUID().toString();
            addHeaderField(header, "requestId", requestId);

            // Authentication token
            String tokenString = requestId + nowAsISO;
            addHeaderField(header, "authToken", sign(tokenString, shopKey));

        } catch (SOAPException e) {
            logger.error("Error sending header", e);
        }
    }

    return outboundProperty;

}

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

/**
 * Tests the behavior of {@link SOAPMessage#getSOAPHeader()} after removing the header from the
 * message. Note that the SAAJ specification requires the implementation to throw an exception
 * in this case. However, the reference implementation simply returns <code>null</code> (see
 * also <a href="http://java.net/jira/browse/SAAJ-15">SAAJ-15</a>). We stick to the behavior of
 * the reference implementation.//from   w  ww. j  ava2s  . c om
 * 
 * @throws Exception
 */
@Validated
@Test
public void testGetSOAPHeaderWithNoHeader() throws Exception {
    SOAPMessage message = getFactory().createMessage();
    SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();
    // Remove the SOAP header (created by default by MessageFactory) using plain DOM methods
    Node child = envelope.getFirstChild();
    while (child != null) {
        if (child instanceof Element && ((Element) child).getLocalName().equals("Header")) {
            envelope.removeChild(child);
            break;
        }
    }
    assertNull(message.getSOAPHeader());
}

From source file:com.usps.UspsServlet.java

private SOAPMessage createSOAPRequest(String parameter) {
    SOAPMessage soapMessage = null;
    try {/*from w ww .  j  a va2  s.c  o m*/
        MessageFactory messageFactory = MessageFactory.newInstance();
        soapMessage = messageFactory.createMessage();
        SOAPPart soapPart = soapMessage.getSOAPPart();

        // SOAP Envelope
        SOAPEnvelope envelope = soapPart.getEnvelope();
        envelope.addNamespaceDeclaration("xsd", "http://www.w3.org/2001/XMLSchema");
        envelope.addNamespaceDeclaration("upss", "http://www.ups.com/XMLSchema/XOLTWS/UPSS/v1.0");
        envelope.addNamespaceDeclaration("wsf", "http://www.ups.com/schema/wsf");
        envelope.addNamespaceDeclaration("xsi", "http://www.w3.org/2001/XMLSchema-instance");
        envelope.addNamespaceDeclaration("common", "http://www.ups.com/XMLSchema/XOLTWS/Common/v1.0");

        // SOAP Body Generated Here
        // all of the nodes below are mandatory
        // if any optional nodes are desired refer to the ECHO API or SOAPUI for
        // exact Node names
        SOAPBody soapBody = envelope.getBody();

        MimeHeaders headers = soapMessage.getMimeHeaders();
        headers.addHeader("Security", "wsse");

        soapMessage.saveChanges();

        /* Print the request message */
        System.out.print("Request SOAP Message:");
        soapMessage.writeTo(System.out);

    } catch (SOAPException | IOException ex) {
        Logger.getLogger(UspsServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
    return soapMessage;
}

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  a  v  a2 s  .c  o m

        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:com.wandrell.example.swss.test.util.test.integration.endpoint.AbstractITEndpoint.java

/**
 * Tests that an invalid message returns a fault.
 *
 * @throws Exception/*from www . j  a  va2  s . c  om*/
 *             never, this is a required declaration
 */
@Test
public final void testEndpoint_Invalid_ReturnsFault() throws Exception {
    final SOAPMessage message; // Response message

    message = callWebService(getInvalidSoapMessage());

    Assert.assertNotNull(message.getSOAPPart().getEnvelope().getBody().getFault());
}