Example usage for javax.xml.soap MessageFactory newInstance

List of usage examples for javax.xml.soap MessageFactory newInstance

Introduction

In this page you can find the example usage for javax.xml.soap MessageFactory newInstance.

Prototype

public static MessageFactory newInstance(String protocol) throws SOAPException 

Source Link

Document

Creates a new MessageFactory object that is an instance of the specified implementation.

Usage

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

@Test
public void testWSSecurity() throws Exception {

    // Setup/*w  w w.jav a 2 s  . c  om*/
    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.unit.be.agiv.security.handler.WSSecurityHandlerTest.java

@Test
public void testVerifyTimestampExpired() throws Exception {
    // setup/*  w  w  w  . j a  v  a2s  .co  m*/
    SOAPMessageContext mockContext = EasyMock.createMock(SOAPMessageContext.class);

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

    InputStream requestInputStream = WSSecurityHandlerTest.class.getResourceAsStream("/ip-sts-response.xml");
    SOAPMessage soapMessage = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL).createMessage(null,
            requestInputStream);
    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 testVerifyTimestamp() throws Exception {
    // setup//from w  ww  .  ja va 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   w w w  .  j  a  va2 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"));

    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 testSignature() throws Exception {
    // setup//  w  w w .  j a  va  2s .c  o 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 .  j  a  va 2s .co  m
    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));
}

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

@Test
public void testUsernameToken() throws Exception {
    // setup//from   w w w .  j av  a 2 s  .  co m
    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//w w  w.  j a  v a  2s . co m
    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);
}