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:test.integ.be.fedict.hsm.ws.WSS4JTestSOAPHandler.java

private void handleOutboundMessage(SOAPMessageContext context)
        throws WSSecurityException, ConfigurationException, MarshallingException {
    SOAPMessage soapMessage = context.getMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();

    WSSecHeader wsSecHeader = new WSSecHeader();
    wsSecHeader.insertSecurityHeader(soapPart);

    WSSecTimestamp wsSecTimeStamp = new WSSecTimestamp();
    wsSecTimeStamp.setTimeToLive(60);//from  w ww.j  av a 2s. c  o m
    wsSecTimeStamp.build(soapPart, wsSecHeader);

    WSSecSAMLToken wsSecSAMLToken = new WSSecSAMLToken();

    Assertion assertion = buildObject(Assertion.DEFAULT_ELEMENT_NAME, Assertion.class);
    assertion.setID("assertion-" + UUID.randomUUID().toString());
    Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(assertion);
    marshaller.marshall(assertion);

    AssertionWrapper assertionWrapper = new AssertionWrapper(assertion);
    wsSecSAMLToken.build(soapPart, assertionWrapper, wsSecHeader);
}

From source file:test.integ.be.fedict.hsm.ws.WSSecurityTestSOAPHandler.java

private void handleOutboundMessage(SOAPMessageContext context) throws SOAPException,
        DatatypeConfigurationException, CertificateEncodingException, DOMException, NoSuchAlgorithmException,
        InvalidAlgorithmParameterException, MarshalException, XMLSignatureException, NoSuchProviderException {
    SOAPMessage soapMessage = context.getMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();

    Element soapEnvelopeElement = soapPart.getDocumentElement();
    String soapPrefix = soapEnvelopeElement.getPrefix();
    LOG.debug("SOAP prefix: " + soapPrefix);
    Element soapHeaderElement = soapPart.createElementNS(SOAP_NAMESPACE, soapPrefix + ":Header");
    Element soapBodyElement = (Element) soapEnvelopeElement.getFirstChild();
    soapBodyElement.setAttributeNS(XMLNS_NS, "xmlns:wsu", WSU_NAMESPACE);
    soapBodyElement.setAttributeNS(WSU_NAMESPACE, "wsu:Id", "Body");
    soapEnvelopeElement.insertBefore(soapHeaderElement, soapBodyElement);

    LOG.debug("adding WS-Security SOAP header");
    Element wsSecurityHeaderElement = soapPart.createElementNS(WSSE_NAMESPACE, "wsse:Security");
    soapHeaderElement.appendChild(wsSecurityHeaderElement);
    wsSecurityHeaderElement.setAttributeNS(XMLNS_NS, "xmlns:wsse", WSSE_NAMESPACE);
    wsSecurityHeaderElement.setAttributeNS(XMLNS_NS, "xmlns:wsu", WSU_NAMESPACE);
    wsSecurityHeaderElement.setAttributeNS(SOAP_NAMESPACE, soapPrefix + ":mustUnderstand", "true");

    Element tsElement = addTimestamp(wsSecurityHeaderElement);
    addBinarySecurityToken(wsSecurityHeaderElement);
    addSignature(wsSecurityHeaderElement, tsElement, soapBodyElement);
}

From source file:test.integ.be.fedict.trust.WSSecurityTest.java

@Test
public void testWSSecurity() throws Exception {

    // Setup/*from   ww  w  . ja v a2 s.  com*/
    KeyPair keyPair = TestUtils.generateKeyPair();
    X509Certificate certificate = TestUtils.generateSelfSignedCertificate(keyPair, "CN=Test");
    KeyPair fooKeyPair = TestUtils.generateKeyPair();
    X509Certificate fooCertificate = TestUtils.generateSelfSignedCertificate(fooKeyPair, "CN=F00");

    this.wsSecurityClientHandler.setServerCertificate(certificate);

    KeyStoreType keyStoreType = KeyStoreType.PKCS12;
    String keyStorePassword = "secret";
    String keyEntryPassword = "secret";
    String alias = "alias";
    File tmpP12File = File.createTempFile("keystore-", ".p12");
    tmpP12File.deleteOnExit();
    TestUtils.persistInKeyStore(tmpP12File, "pkcs12", keyPair.getPrivate(), certificate, keyStorePassword,
            keyEntryPassword, alias);
    String keyStorePath = tmpP12File.getAbsolutePath();

    MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL);
    InputStream testSoapMessageInputStream = WSSecurityTest.class.getResourceAsStream("/test-soap-message.xml");
    assertNotNull(testSoapMessageInputStream);

    SOAPMessage message = messageFactory.createMessage(null, testSoapMessageInputStream);

    SOAPMessageContext soapMessageContext = new TestSOAPMessageContext(message, true);
    soapMessageContext.put(MessageContext.SERVLET_CONTEXT, this.mockServletContext);

    // Expectations
    expect(this.mockServletContext.getAttribute(TrustService.class.getName())).andReturn(mockTrustService);
    expect(this.mockTrustService.getWsSecurityConfig()).andReturn(new WSSecurityConfigEntity("test", true,
            keyStoreType, keyStorePath, keyStorePassword, keyEntryPassword, alias));

    // Replay
    replay(this.mockObjects);

    // Operate : Let WSSecurityServerHandler sign the SOAP message
    assertTrue(this.wsSecurityServerHandler.handleMessage(soapMessageContext));

    // Verify message is signed
    verify(this.mockObjects);

    SOAPMessage resultMessage = soapMessageContext.getMessage();
    SOAPPart resultSoapPart = resultMessage.getSOAPPart();
    LOG.debug("signed SOAP part:" + TestUtils.domToString(resultSoapPart));

    Element nsElement = resultSoapPart.createElement("nsElement");
    nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:soap",
            "http://schemas.xmlsoap.org/soap/envelope/");
    nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:wsse",
            "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
    nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:ds", "http://www.w3.org/2000/09/xmldsig#");
    nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:wsu",
            "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");

    Node resultNode = XPathAPI.selectSingleNode(resultSoapPart,
            "/soap:Envelope/soap:Header/wsse:Security[@soap:mustUnderstand = '1']", nsElement);
    assertNotNull(resultNode);

    assertNotNull("missing WS-Security timestamp", XPathAPI.selectSingleNode(resultSoapPart,
            "/soap:Envelope/soap:Header/wsse:Security/wsu:Timestamp/wsu:Created", nsElement));

    assertEquals(2.0, XPathAPI.eval(resultSoapPart, "count(//ds:Reference)", nsElement).num());

    // Setup
    soapMessageContext.put(MessageContext.MESSAGE_OUTBOUND_PROPERTY, false);

    // Operate : pass on signed message to WSSecurityClientHandler for
    // validation
    assertTrue(this.wsSecurityClientHandler.handleMessage(soapMessageContext));

    // Operate : pass on signed message to WSSecurityClient handler
    // configured with wrong server certificate
    this.wsSecurityClientHandler.setServerCertificate(fooCertificate);
    try {
        this.wsSecurityClientHandler.handleMessage(soapMessageContext);
        fail();
    } catch (SOAPFaultException e) {
        // expected
        LOG.debug("SOAPFaultException: " + e.getMessage());
    }
}

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);/* w  w w.j  av a  2 s  . c o  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.saaj.TestAttachmentSerialization.java

public int loadMsgWithAttachments(InputStream is) throws Exception {
    MimeHeaders headers = new MimeHeaders();
    headers.setHeader("Content-Type", MIME_MULTIPART_RELATED);
    MessageFactory mf = MessageFactory.newInstance();
    SOAPMessage msg = mf.createMessage(headers, is);
    SOAPPart sp = msg.getSOAPPart();
    SOAPEnvelope envelope = sp.getEnvelope();
    assertTrue(sp != null);//from ww  w  .ja v  a  2s .  c  o m
    assertTrue(envelope != null);
    return msg.countAttachments();
}

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

@Test
public void testVerifyTimestamp() throws Exception {
    // setup/*from   w ww .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.FALSE);

    SOAPMessage soapMessage = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL).createMessage();

    SOAPBody soapBody = soapMessage.getSOAPBody();
    soapBody.addBodyElement(new QName("test"));

    SOAPPart soapPart = soapMessage.getSOAPPart();
    WSSecHeader secHeader = new WSSecHeader();
    secHeader.insertSecurityHeader(soapPart);
    WSSecTimestamp timestamp = new WSSecTimestamp();
    timestamp.build(soapPart, secHeader);

    LOG.debug("SOAP message: " + toString(soapMessage.getSOAPPart()));
    EasyMock.expect(mockContext.getMessage()).andStubReturn(soapMessage);

    // prepare
    EasyMock.replay(mockContext);

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

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

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

@Test
public void testVerifyTimestampMissing() throws Exception {
    // setup/*from www  .j  av  a 2 s.c o  m*/
    SOAPMessageContext mockContext = EasyMock.createMock(SOAPMessageContext.class);

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

    SOAPMessage soapMessage = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL).createMessage();

    SOAPBody soapBody = soapMessage.getSOAPBody();
    soapBody.addBodyElement(new QName("test"));

    LOG.debug("SOAP message: " + toString(soapMessage.getSOAPPart()));
    EasyMock.expect(mockContext.getMessage()).andStubReturn(soapMessage);

    // prepare
    EasyMock.replay(mockContext);

    // operate
    try {
        this.testedInstance.handleMessage(mockContext);
        fail();
    } catch (ProtocolException e) {
        // verify
        EasyMock.verify(mockContext);
    }
}

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

@Test
public void testUsernameToken() throws Exception {
    // setup/*from   w ww  .j  av  a 2  s.com*/
    WSSecurityHandler testedInstance = new WSSecurityHandler();

    SOAPMessageContext mockContext = EasyMock.createMock(SOAPMessageContext.class);

    EasyMock.expect(mockContext.get("javax.xml.ws.handler.message.outbound")).andStubReturn(Boolean.TRUE);
    String testUsername = "username-" + UUID.randomUUID().toString();

    testedInstance.setCredentials(testUsername, "password");

    SOAPMessage soapMessage = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL).createMessage(null,
            new ByteArrayInputStream(
                    "<Envelope xmlns=\"http://schemas.xmlsoap.org/soap/envelope/\"><Body>test</Body></Envelope>"
                            .getBytes()));

    LOG.debug("SOAP message: " + toString(soapMessage.getSOAPPart()));
    EasyMock.expect(mockContext.getMessage()).andStubReturn(soapMessage);

    // prepare
    EasyMock.replay(mockContext);

    // operate
    testedInstance.handleMessage(mockContext);

    // verify
    EasyMock.verify(mockContext);
    LOG.debug("SOAP message after handleMessage: " + toString(soapMessage.getSOAPPart()));

    Element nsElement = getNSElement(soapMessage.getSOAPPart());
    String resultUsername = XPathAPI.selectSingleNode(soapMessage.getSOAPPart(),
            "soap:Envelope/soap:Header/wsse:Security/wsse:UsernameToken/wsse:Username/text()", nsElement)
            .getNodeValue();
    assertEquals(testUsername, resultUsername);
}

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

@Test
public void testWSSecurityWithoutInitialHeader() throws Exception {
    // setup/*from  ww w. j ava  2  s .c om*/
    SOAPMessageContext mockContext = EasyMock.createMock(SOAPMessageContext.class);

    EasyMock.expect(mockContext.get("javax.xml.ws.handler.message.outbound")).andStubReturn(Boolean.TRUE);
    EasyMock.expect(mockContext.get("be.agiv.security.handler.WSSecurityHandler.token")).andStubReturn(null);
    EasyMock.expect(mockContext.get("be.agiv.security.handler.WSSecurityHandler.username"))
            .andStubReturn("username");
    EasyMock.expect(mockContext.get("be.agiv.security.handler.WSSecurityHandler.password"))
            .andStubReturn("password");
    EasyMock.expect(mockContext.get("be.agiv.security.handler.WSSecurityHandler.key")).andStubReturn(null);

    SOAPMessage soapMessage = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL).createMessage(null,
            new ByteArrayInputStream(
                    "<Envelope xmlns=\"http://www.w3.org/2003/05/soap-envelope\"><Body>test</Body></Envelope>"
                            .getBytes()));

    LOG.debug("SOAP message: " + toString(soapMessage.getSOAPPart()));
    EasyMock.expect(mockContext.getMessage()).andStubReturn(soapMessage);

    EasyMock.expect(mockContext.get(WSSecurityHandler.class.getName() + ".certificate")).andStubReturn(null);

    // prepare
    EasyMock.replay(mockContext);

    // operate
    this.testedInstance.handleMessage(mockContext);

    // verify
    EasyMock.verify(mockContext);
}

From source file:test.unit.be.e_contract.dssp.client.WSSecuritySOAPHandler.java

private void handleInboundMessage(SOAPMessageContext context) throws WSSecurityException, SOAPException {
    SOAPMessage soapMessage = context.getMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();

    WSSecurityEngine secEngine = new WSSecurityEngine();
    WSSConfig wssConfig = new WSSConfig();
    secEngine.setWssConfig(wssConfig);//from  w  w  w.j a va 2 s  .c  o  m
    CallbackHandler callbackHandler = new CallbackTestHandler();
    List<WSSecurityEngineResult> results = secEngine.processSecurityHeader(soapPart, null, callbackHandler,
            null);
    if (null == results) {
        LOG.debug("no WS-Security results");
        return;
    }
    for (WSSecurityEngineResult result : results) {
        LOG.debug("result key set: " + result.keySet());
    }
}