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.wso2.carbon.identity.sso.saml.servlet.SAMLArtifactResolveServlet.java

/**
 * All requests are handled by this handleRequest method. Request should come with a soap envelop that
 * wraps an ArtifactResolve object. First we try to extract resolve object and if successful, call
 * handle artifact method./*from   w  ww.  j  av a2  s. c o m*/
 *
 * @param req  HttpServletRequest object received.
 * @param resp HttpServletResponse object to be sent.
 * @throws ServletException
 * @throws IOException
 */
private void handleRequest(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    try {
        ArtifactResolve artifactResolve = null;
        try {
            MessageFactory messageFactory = MessageFactory.newInstance();
            InputStream inStream = req.getInputStream();
            SOAPMessage soapMessage = messageFactory.createMessage(new MimeHeaders(), inStream);
            if (log.isDebugEnabled()) {
                OutputStream outputStream = new ByteArrayOutputStream();
                soapMessage.writeTo(outputStream);
                log.debug("SAML2 Artifact Resolve request received: " + outputStream.toString());
            }
            SOAPBody soapBody = soapMessage.getSOAPBody();
            Iterator iterator = soapBody.getChildElements();

            while (iterator.hasNext()) {
                SOAPBodyElement artifactResolveElement = (SOAPBodyElement) iterator.next();

                if (StringUtils.equals(SAMLConstants.SAML20P_NS, artifactResolveElement.getNamespaceURI())
                        && StringUtils.equals(ArtifactResolve.DEFAULT_ELEMENT_LOCAL_NAME,
                                artifactResolveElement.getLocalName())) {

                    DOMSource source = new DOMSource(artifactResolveElement);
                    StringWriter stringResult = new StringWriter();
                    TransformerFactory.newInstance().newTransformer().transform(source,
                            new StreamResult(stringResult));
                    artifactResolve = (ArtifactResolve) SAMLSSOUtil.unmarshall(stringResult.toString());
                }
            }
        } catch (SOAPException e) {
            throw new ServletException("Error while extracting SOAP body from the request.", e);
        } catch (TransformerException e) {
            throw new ServletException("Error while extracting ArtifactResponse from the request.", e);
        } catch (IdentityException e) {
            throw new ServletException("Error while unmarshalling ArtifactResponse  from the request.", e);
        }

        if (artifactResolve != null) {
            handleArtifact(req, resp, artifactResolve);
        } else {
            log.error("Invalid SAML Artifact Resolve request received.");
        }

    } finally {
        SAMLSSOUtil.removeSaaSApplicationThreaLocal();
        SAMLSSOUtil.removeUserTenantDomainThreaLocal();
        SAMLSSOUtil.removeTenantDomainFromThreadLocal();
    }
}

From source file:org.wso2.carbon.identity.sso.saml.servlet.SAMLECPProviderServlet.java

/**
 * This method converts SOAPMessage to OutputStream and return the String.
 * @param soapMessage SOAPMessage from the InputStream.
 * @return/*  w  w w  .ja v a  2  s .  com*/
 * @throws SOAPException
 * @throws IOException
 */
private String convertSOAPMsgToOutputStream(SOAPMessage soapMessage) throws SOAPException, IOException {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    soapMessage.writeTo(outputStream);
    String strMsg = new String(outputStream.toByteArray(), StandardCharsets.UTF_8);
    outputStream.close();
    return strMsg;
}

From source file:org.wso2.carbon.mdm.mobileservices.windowspc.services.wstep.util.MessageHandler.java

/**
 * This method adds Timestamp for SOAP header, and adds Content-length for HTTP header for
 * avoiding HTTP chunking./*from  w w w.  j av  a 2 s .  c  o m*/
 *
 * @param context
 */
@Override
public boolean handleMessage(SOAPMessageContext context) {

    Boolean outBoundProperty = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);

    if (outBoundProperty) {

        SOAPMessage message = context.getMessage();
        SOAPHeader header = null;
        SOAPEnvelope envelope = null;

        try {
            header = message.getSOAPHeader();
            envelope = message.getSOAPPart().getEnvelope();
        } catch (SOAPException e) {
            Response.serverError().build();
        }

        if (header == null) {
            try {
                header = envelope.addHeader();
            } catch (SOAPException e) {
                Response.serverError().build();
            }
        }
        SOAPFactory soapFactory = null;

        try {
            soapFactory = SOAPFactory.newInstance();
        } catch (SOAPException e) {
            Response.serverError().build();
        }

        QName qNamesSecurity = new QName(Constants.CertificateEnrollment.WS_SECURITY_TARGET_NAMESPACE,
                Constants.CertificateEnrollment.SECURITY);

        SOAPHeaderElement Security = null;

        try {
            Security = header.addHeaderElement(qNamesSecurity);
        } catch (SOAPException e) {
            Response.serverError().build();
        }

        Name attributeName = null;
        try {
            attributeName = soapFactory.createName(Constants.CertificateEnrollment.TIMESTAMP_ID,
                    Constants.CertificateEnrollment.TIMESTAMP_U,
                    Constants.CertificateEnrollment.WSS_SECURITY_UTILITY);
        } catch (SOAPException e) {
            Response.serverError().build();
        }

        QName qNameTimestamp = new QName(Constants.CertificateEnrollment.WSS_SECURITY_UTILITY,
                Constants.CertificateEnrollment.TIMESTAMP);
        SOAPHeaderElement timestamp = null;

        try {
            timestamp = header.addHeaderElement(qNameTimestamp);
            timestamp.addAttribute(attributeName, Constants.CertificateEnrollment.TIMESTAMP_0);
        } catch (SOAPException e) {
            Response.serverError().build();
        }

        DateTime dateTime = new DateTime();
        DateTime expiredDateTime = dateTime.plusMinutes(5);
        String createdISOTime = dateTime.toString(ISODateTimeFormat.dateTime());
        String expiredISOTime = expiredDateTime.toString(ISODateTimeFormat.dateTime());
        createdISOTime = createdISOTime.substring(0, createdISOTime.length() - 6);
        createdISOTime = createdISOTime + "Z";
        expiredISOTime = expiredISOTime.substring(0, expiredISOTime.length() - 6);
        expiredISOTime = expiredISOTime + "Z";

        QName qNameCreated = new QName(Constants.CertificateEnrollment.WSS_SECURITY_UTILITY,
                Constants.CertificateEnrollment.CREATED);
        SOAPHeaderElement SOAPHeaderCreated = null;

        try {
            SOAPHeaderCreated = header.addHeaderElement(qNameCreated);
            SOAPHeaderCreated.addTextNode(createdISOTime);
        } catch (SOAPException e) {
            Response.serverError().build();
        }

        QName qNameExpires = new QName(Constants.CertificateEnrollment.WSS_SECURITY_UTILITY,
                Constants.CertificateEnrollment.EXPIRES);
        SOAPHeaderElement SOAPHeaderExpires = null;

        try {
            SOAPHeaderExpires = header.addHeaderElement(qNameExpires);
            SOAPHeaderExpires.addTextNode(expiredISOTime);
        } catch (SOAPException e) {
            Response.serverError().build();
        }

        try {
            timestamp.addChildElement(SOAPHeaderCreated);
            timestamp.addChildElement(SOAPHeaderExpires);
            Security.addChildElement(timestamp);
        } catch (SOAPException e) {
            Response.serverError().build();
        }

        try {
            message.saveChanges();
        } catch (SOAPException e) {
            Response.serverError().build();
        }

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        try {
            message.writeTo(outputStream);
        } catch (IOException e) {
            Response.serverError().build();
        } catch (SOAPException e) {
            Response.serverError().build();
        }

        String messageString = null;
        try {
            messageString = new String(outputStream.toByteArray(), Constants.CertificateEnrollment.UTF_8);
        } catch (UnsupportedEncodingException e) {
            Response.serverError().build();
        }

        Map<String, List<String>> headers = (Map<String, List<String>>) context
                .get(MessageContext.HTTP_REQUEST_HEADERS);
        headers = new HashMap<String, List<String>>();
        headers.put(Constants.CertificateEnrollment.CONTENT_LENGTH,
                Arrays.asList(String.valueOf(messageString.length())));
        context.put(MessageContext.HTTP_REQUEST_HEADERS, headers);

    }
    return true;
}

From source file:test.saaj.TestAttachmentSerialization.java

public int saveMsgWithAttachments(OutputStream os) throws Exception {
    MessageFactory mf = MessageFactory.newInstance();
    SOAPMessage msg = mf.createMessage();

    SOAPPart sp = msg.getSOAPPart();
    SOAPEnvelope envelope = sp.getEnvelope();
    SOAPHeader header = envelope.getHeader();
    SOAPBody body = envelope.getBody();

    SOAPElement el = header.addHeaderElement(envelope.createName("field4", NS_PREFIX, NS_URI));
    SOAPElement el2 = el.addChildElement("field4b", NS_PREFIX);
    SOAPElement el3 = el2.addTextNode("field4value");

    el = body.addBodyElement(envelope.createName("bodyfield3", NS_PREFIX, NS_URI));
    el2 = el.addChildElement("bodyfield3a", NS_PREFIX);
    el2.addTextNode("bodyvalue3a");
    el2 = el.addChildElement("bodyfield3b", NS_PREFIX);
    el2.addTextNode("bodyvalue3b");
    el2 = el.addChildElement("datefield", NS_PREFIX);

    AttachmentPart ap = msg.createAttachmentPart();
    ap.setContent("some attachment text...", "text/plain");
    msg.addAttachmentPart(ap);/*from   w  ww.  j  a  v  a 2 s.  co m*/

    String jpgfilename = "docs/images/axis.jpg";
    File myfile = new File(jpgfilename);
    FileDataSource fds = new FileDataSource(myfile);
    DataHandler dh = new DataHandler(fds);
    AttachmentPart ap2 = msg.createAttachmentPart(dh);
    ap2.setContentType("image/jpg");
    msg.addAttachmentPart(ap2);

    // Test for Bug #17664
    if (msg.saveRequired()) {
        msg.saveChanges();
    }
    MimeHeaders headers = msg.getMimeHeaders();
    assertTrue(headers != null);
    String[] contentType = headers.getHeader("Content-Type");
    assertTrue(contentType != null);

    msg.writeTo(os);
    os.flush();
    return msg.countAttachments();
}

From source file:test.unit.be.agiv.security.handler.WSSecurityHandlerTest.java

@Test
public void testSignature() throws Exception {
    // setup/*from   ww  w.  j a v a 2 s.co  m*/
    SOAPMessageContext mockContext = EasyMock.createMock(SOAPMessageContext.class);

    EasyMock.expect(mockContext.get("javax.xml.ws.handler.message.outbound")).andStubReturn(Boolean.TRUE);

    byte[] secret = new byte[256 / 8];
    SecureRandom secureRandom = new SecureRandom();
    secureRandom.nextBytes(secret);

    String tokenIdentifier = "#saml-token-test";
    this.testedInstance.setKey(secret, tokenIdentifier, null, false);

    InputStream requestInputStream = WSSecurityHandlerTest.class
            .getResourceAsStream("/r-sts-request-before-signing.xml");
    SOAPMessage soapMessage = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL).createMessage(null,
            requestInputStream);
    EasyMock.expect(mockContext.getMessage()).andStubReturn(soapMessage);

    // prepare
    EasyMock.replay(mockContext);

    // operate
    boolean result = this.testedInstance.handleMessage(mockContext);

    // verify
    EasyMock.verify(mockContext);
    assertTrue(result);

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    soapMessage.writeTo(outputStream);
    LOG.debug("SOAP message: " + new String(outputStream.toByteArray()));

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(outputStream.toByteArray());
    Document resultDocument = documentBuilder.parse(byteArrayInputStream);
    TestUtils.markAllIdAttributesAsId(resultDocument);

    NodeList signatureNodeList = resultDocument.getElementsByTagNameNS(Constants.SignatureSpecNS, "Signature");
    assertEquals(1, signatureNodeList.getLength());
    Element signatureElement = (Element) signatureNodeList.item(0);

    XMLSignature xmlSignature = new XMLSignature(signatureElement, null);
    Key key = WSSecurityUtil.prepareSecretKey(SignatureMethod.HMAC_SHA1, secret);
    boolean signatureResult = xmlSignature.checkSignatureValue(key);
    assertTrue(signatureResult);

    LOG.debug("signed SOAP: " + toString(resultDocument));
}

From source file:test.unit.be.agiv.security.handler.WSSecurityHandlerTest.java

@Test
public void testCertificateSignature() throws Exception {
    // setup//www . ja v  a  2  s. c om
    SOAPMessageContext mockContext = EasyMock.createMock(SOAPMessageContext.class);

    EasyMock.expect(mockContext.get("javax.xml.ws.handler.message.outbound")).andStubReturn(Boolean.TRUE);

    SOAPMessage soapMessage = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL).createMessage(null,
            new ByteArrayInputStream(
                    ("<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:wsa=\"http://www.w3.org/2005/08/addressing\" xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">"
                            + "<soap:Header>"
                            + "<wsa:To soap:mustUnderstand=\"1\" wsu:Id=\"toId\">destination</wsa:To>"
                            + "</soap:Header>" + "<soap:Body>test</soap:Body>" + "</soap:Envelope>")
                                    .getBytes()));
    EasyMock.expect(mockContext.getMessage()).andStubReturn(soapMessage);

    EasyMock.expect(mockContext.get(WSAddressingHandler.class.getName() + ".toId")).andStubReturn("toId");

    KeyPair keyPair = generateKeyPair();
    PrivateKey privateKey = keyPair.getPrivate();

    X509Certificate certificate = generateSelfSignedCertificate(keyPair);
    this.testedInstance.setCredentials(privateKey, certificate);

    // prepare
    EasyMock.replay(mockContext);

    // operate
    boolean result = this.testedInstance.handleMessage(mockContext);

    // verify
    EasyMock.verify(mockContext);
    assertTrue(result);

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    soapMessage.writeTo(outputStream);
    LOG.debug("SOAP message: " + new String(outputStream.toByteArray()));

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(outputStream.toByteArray());
    Document resultDocument = documentBuilder.parse(byteArrayInputStream);
    TestUtils.markAllIdAttributesAsId(resultDocument);

    NodeList signatureNodeList = resultDocument.getElementsByTagNameNS(Constants.SignatureSpecNS, "Signature");
    assertEquals(1, signatureNodeList.getLength());
    Element signatureElement = (Element) signatureNodeList.item(0);

    XMLSignature xmlSignature = new XMLSignature(signatureElement, null);
    boolean signatureResult = xmlSignature.checkSignatureValue(certificate);
    assertTrue(signatureResult);

    LOG.debug("signed SOAP: " + toString(resultDocument));
}