Example usage for javax.xml.ws.handler MessageContext MESSAGE_OUTBOUND_PROPERTY

List of usage examples for javax.xml.ws.handler MessageContext MESSAGE_OUTBOUND_PROPERTY

Introduction

In this page you can find the example usage for javax.xml.ws.handler MessageContext MESSAGE_OUTBOUND_PROPERTY.

Prototype

String MESSAGE_OUTBOUND_PROPERTY

To view the source code for javax.xml.ws.handler MessageContext MESSAGE_OUTBOUND_PROPERTY.

Click Source Link

Document

Standard property: message direction, true for outbound messages, false for inbound.

Usage

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  ww .  ja  v  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.integ.be.fedict.hsm.ws.WSS4JTestSOAPHandler.java

@Override
public boolean handleMessage(SOAPMessageContext context) {
    Boolean outboundProperty = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
    if (true == outboundProperty.booleanValue()) {
        try {/*from   w w  w.j  av  a  2  s  . co m*/
            handleOutboundMessage(context);
        } catch (Exception e) {
            LOG.debug("error adding WS-Security header: " + e.getMessage(), e);
            throw new ProtocolException(e);
        }
    }
    return true;
}

From source file:test.integ.be.fedict.trust.util.TestSOAPMessageContext.java

public TestSOAPMessageContext(SOAPMessage message, boolean outbound) {

    this.message = message;
    this.properties = new HashMap<String, Object>();
    this.properties.put(MessageContext.MESSAGE_OUTBOUND_PROPERTY, outbound);
}

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

@Test
public void testWSSecurity() throws Exception {

    // Setup//from   w ww.ja  v a  2  s . c o  m
    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.e_contract.dssp.client.WSSecuritySOAPHandler.java

@Override
public boolean handleMessage(SOAPMessageContext context) {
    Boolean outboundProperty = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
    if (false == outboundProperty.booleanValue()) {
        try {/*  w  w  w . j a v  a2 s  .com*/
            handleInboundMessage(context);
        } catch (Exception e) {
            throw new ProtocolException(e);
        }
    }
    return true;
}

From source file:unit.test.be.e_contract.mycarenet.ehealth.common.WSSecuritySOAPHandlerTest.java

@Test
public void testHandleMessage() throws Exception {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    PrivateKey privateKey = keyPair.getPrivate();

    String samlAssertion = "<Assertion xmlns=\"urn:oasis:names:tc:SAML:1.0:assertion\""
            + " AssertionID=\"_42e7a00652420d86ee884f295a3fbf02\">" + "</Assertion>";

    WSSecuritySOAPHandler testedInstance = new WSSecuritySOAPHandler();
    testedInstance.setPrivateKey(privateKey);
    testedInstance.setAssertion(samlAssertion);

    SOAPMessageContext mockSoapMessageContext = EasyMock.createMock(SOAPMessageContext.class);
    EasyMock.expect(mockSoapMessageContext.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY)).andReturn(true);

    MessageFactory messageFactory = MessageFactory.newInstance();
    SOAPMessage soapMessage = messageFactory.createMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();
    SOAPEnvelope soapEnvelope = soapPart.getEnvelope();
    SOAPBody soapBody = soapEnvelope.getBody();
    soapBody.addBodyElement(new QName("http://www.example.com", "Test"));

    EasyMock.expect(mockSoapMessageContext.getMessage()).andReturn(soapMessage);

    // prepare//from  w w w  . j a  v a2  s . c o  m
    EasyMock.replay(mockSoapMessageContext);

    // operate
    testedInstance.handleMessage(mockSoapMessageContext);

    // verify
    EasyMock.verify(mockSoapMessageContext);
    LOG.debug(toString(soapPart));
}