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

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

Introduction

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

Prototype

String SERVLET_CONTEXT

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

Click Source Link

Document

Standard property: servlet context object.

Usage

From source file:org.wso2.carbon.device.mgt.mobile.windows.api.services.enrollment.impl.EnrollmentServiceImpl.java

@Override
public void requestSecurityToken(String tokenType, String requestType, String binarySecurityToken,
        AdditionalContext additionalContext, Holder<RequestSecurityTokenResponse> response)
        throws WindowsDeviceEnrolmentException, UnsupportedEncodingException, WAPProvisioningException {
    String headerBinarySecurityToken = null;
    String headerTo = null;/*from   www.j ava2s. c om*/
    String encodedWap;
    List<Header> headers = getHeaders();
    for (Header headerElement : headers) {
        String nodeName = headerElement.getName().getLocalPart();
        if (PluginConstants.SECURITY.equals(nodeName)) {
            Element element = (Element) headerElement.getObject();
            headerBinarySecurityToken = element.getFirstChild().getFirstChild().getTextContent();
        }
        if (PluginConstants.TO.equals(nodeName)) {
            Element toElement = (Element) headerElement.getObject();
            headerTo = toElement.getFirstChild().getTextContent();
        }
    }
    try {
        enrollDevice(additionalContext, headerBinarySecurityToken);
    } catch (DeviceManagementException e) {
        throw new WindowsDeviceEnrolmentException("Error occurred while enrolling the device.");
    } catch (PolicyManagementException e) {
        throw new WindowsDeviceEnrolmentException("Error occurred while enforcing windows policies.");
    }
    String[] splitEmail = headerTo.split("(/ENROLLMENTSERVER)");
    String email = splitEmail[PluginConstants.CertificateEnrolment.EMAIL_SEGMENT];

    String[] splitDomain = email.split("(EnterpriseEnrollment.)");
    domain = splitDomain[PluginConstants.CertificateEnrolment.DOMAIN_SEGMENT];
    provisioningURL = PluginConstants.CertificateEnrolment.ENROLL_SUBDOMAIN + domain
            + PluginConstants.CertificateEnrolment.SYNCML_PROVISIONING_WIN10_SERVICE_URL;

    List<ConfigurationEntry> tenantConfigurations;
    try {
        if ((tenantConfigurations = WindowsAPIUtils.getTenantConfigurationData()) != null) {
            for (ConfigurationEntry configurationEntry : tenantConfigurations) {
                if ((PluginConstants.TenantConfigProperties.NOTIFIER_FREQUENCY
                        .equals(configurationEntry.getName()))) {
                    pollingFrequency = configurationEntry.getValue().toString();
                } else {
                    pollingFrequency = PluginConstants.TenantConfigProperties.DEFAULT_FREQUENCY;
                }
            }
        } else {
            pollingFrequency = PluginConstants.TenantConfigProperties.DEFAULT_FREQUENCY;
            String msg = "Tenant configurations are not initialized yet.";
            log.error(msg);
        }
        ServletContext ctx = (ServletContext) context.getMessageContext().get(MessageContext.SERVLET_CONTEXT);
        File wapProvisioningFile = (File) ctx.getAttribute(PluginConstants.CONTEXT_WAP_PROVISIONING_FILE);
        if (log.isDebugEnabled()) {
            log.debug("Received CSR from Device:" + binarySecurityToken);
        }

        String wapProvisioningFilePath = wapProvisioningFile.getPath();
        RequestSecurityTokenResponse requestSecurityTokenResponse = new RequestSecurityTokenResponse();
        requestSecurityTokenResponse.setTokenType(PluginConstants.CertificateEnrolment.TOKEN_TYPE);

        encodedWap = prepareWapProvisioningXML(binarySecurityToken, wapProvisioningFilePath,
                headerBinarySecurityToken);
        RequestedSecurityToken requestedSecurityToken = new RequestedSecurityToken();
        BinarySecurityToken binarySecToken = new BinarySecurityToken();
        binarySecToken.setValueType(PluginConstants.CertificateEnrolment.VALUE_TYPE);
        binarySecToken.setEncodingType(PluginConstants.CertificateEnrolment.ENCODING_TYPE);
        binarySecToken.setToken(encodedWap);
        requestedSecurityToken.setBinarySecurityToken(binarySecToken);
        requestSecurityTokenResponse.setRequestedSecurityToken(requestedSecurityToken);
        requestSecurityTokenResponse.setRequestID(PluginConstants.CertificateEnrolment.REQUEST_ID);
        response.value = requestSecurityTokenResponse;
    } catch (CertificateGenerationException e) {
        String msg = "Problem occurred while generating certificate.";
        log.error(msg, e);
        throw new WindowsDeviceEnrolmentException(msg, e);
    } catch (WAPProvisioningException e) {
        String msg = "Problem occurred while generating wap-provisioning file.";
        log.error(msg, e);
        throw new WindowsDeviceEnrolmentException(msg, e);
    } catch (DeviceManagementException e) {
        String msg = "Error occurred while getting tenant configurations.";
        log.error(msg);
        throw new WindowsDeviceEnrolmentException(msg, e);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();

    }
}

From source file:org.wso2.carbon.device.mgt.mobile.windows.api.services.wstep.impl.CertificateEnrollmentServiceImpl.java

/**
 * This method implements MS-WSTEP for Certificate Enrollment Service.
 *
 * @param tokenType           - Device Enrolment Token type is received via device
 * @param requestType         - WS-Trust request type
 * @param binarySecurityToken - CSR from device
 * @param additionalContext   - Device type and OS version is received
 * @param response            - Response will include wap-provisioning xml
 * @WindowsDeviceEnrolmentException -/*w ww  .j  a  v  a  2  s. c o  m*/
 */
@Override
public void requestSecurityToken(String tokenType, String requestType, String binarySecurityToken,
        AdditionalContext additionalContext, Holder<RequestSecurityTokenResponse> response)
        throws WindowsDeviceEnrolmentException {

    String headerBinarySecurityToken = null;
    String headerTo = null;
    String encodedWap;
    List<Header> headers = getHeaders();
    for (Header headerElement : headers) {
        String nodeName = headerElement.getName().getLocalPart();
        if (PluginConstants.SECURITY.equals(nodeName)) {
            Element element = (Element) headerElement.getObject();
            headerBinarySecurityToken = element.getFirstChild().getNextSibling().getFirstChild()
                    .getTextContent();
        }
        if (PluginConstants.TO.equals(nodeName)) {
            Element toElement = (Element) headerElement.getObject();
            headerTo = toElement.getFirstChild().getTextContent();
        }
    }

    String[] splitEmail = headerTo.split("(/ENROLLMENTSERVER)");
    String email = splitEmail[PluginConstants.CertificateEnrolment.EMAIL_SEGMENT];

    String[] splitDomain = email.split("(EnterpriseEnrollment.)");
    domain = splitDomain[PluginConstants.CertificateEnrolment.DOMAIN_SEGMENT];
    provisioningURL = PluginConstants.CertificateEnrolment.ENROLL_SUBDOMAIN + domain
            + PluginConstants.CertificateEnrolment.SYNCML_PROVISIONING_SERVICE_URL;

    List<ConfigurationEntry> tenantConfigurations;
    try {
        if ((tenantConfigurations = WindowsAPIUtils.getTenantConfigurationData()) != null) {
            for (ConfigurationEntry configurationEntry : tenantConfigurations) {
                if ((PluginConstants.TenantConfigProperties.NOTIFIER_FREQUENCY
                        .equals(configurationEntry.getName()))) {
                    pollingFrequency = configurationEntry.getValue().toString();
                } else {
                    pollingFrequency = PluginConstants.TenantConfigProperties.DEFAULT_FREQUENCY;
                }
            }
        } else {
            pollingFrequency = PluginConstants.TenantConfigProperties.DEFAULT_FREQUENCY;
            String msg = "Tenant configurations are not initialized yet.";
            log.error(msg);
        }
        ServletContext ctx = (ServletContext) context.getMessageContext().get(MessageContext.SERVLET_CONTEXT);
        File wapProvisioningFile = (File) ctx.getAttribute(PluginConstants.CONTEXT_WAP_PROVISIONING_FILE);
        if (log.isDebugEnabled()) {
            log.debug("Received CSR from Device:" + binarySecurityToken);
        }

        String wapProvisioningFilePath = wapProvisioningFile.getPath();
        RequestSecurityTokenResponse requestSecurityTokenResponse = new RequestSecurityTokenResponse();
        requestSecurityTokenResponse.setTokenType(PluginConstants.CertificateEnrolment.TOKEN_TYPE);

        encodedWap = prepareWapProvisioningXML(binarySecurityToken, wapProvisioningFilePath,
                headerBinarySecurityToken);
        RequestedSecurityToken requestedSecurityToken = new RequestedSecurityToken();
        BinarySecurityToken binarySecToken = new BinarySecurityToken();
        binarySecToken.setValueType(PluginConstants.CertificateEnrolment.VALUE_TYPE);
        binarySecToken.setEncodingType(PluginConstants.CertificateEnrolment.ENCODING_TYPE);
        binarySecToken.setToken(encodedWap);
        requestedSecurityToken.setBinarySecurityToken(binarySecToken);
        requestSecurityTokenResponse.setRequestedSecurityToken(requestedSecurityToken);
        requestSecurityTokenResponse.setRequestID(PluginConstants.CertificateEnrolment.REQUEST_ID);
        response.value = requestSecurityTokenResponse;
    } catch (CertificateGenerationException e) {
        String msg = "Problem occurred while generating certificate.";
        log.error(msg, e);
        throw new WindowsDeviceEnrolmentException(msg, e);
    } catch (WAPProvisioningException e) {
        String msg = "Problem occurred while generating wap-provisioning file.";
        log.error(msg, e);
        throw new WindowsDeviceEnrolmentException(msg, e);
    } catch (DeviceManagementException e) {
        String msg = "Error occurred while getting tenant configurations.";
        log.error(msg);
        throw new WindowsDeviceEnrolmentException(msg, e);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}

From source file:org.wso2.carbon.mdm.mobileservices.windows.services.discovery.impl.DiscoveryServiceImpl.java

/**
 * This method returns the OnPremise AuthPolicy and next two endpoint the mobile device should
 * call if this response to received successfully at the device end. This method is called by
 * device immediately after the first GET method calling for the same endpoint.
 *
 * @param discoveryRequest - Request bean comes via mobile phone
 * @param response         - DiscoveryResponse bean for response
 *//*w w  w . j a v  a  2 s  . c  o m*/
@Override
public void discover(DiscoveryRequest discoveryRequest, Holder<DiscoveryResponse> response) {

    ServletContext ctx = (ServletContext) context.getMessageContext().get(MessageContext.SERVLET_CONTEXT);
    WindowsPluginProperties windowsPluginProperties = (WindowsPluginProperties) ctx
            .getAttribute(PluginConstants.WINDOWS_PLUGIN_PROPERTIES);

    DiscoveryResponse discoveryResponse = new DiscoveryResponse();
    if (FEDERATED.equals(windowsPluginProperties.getAuthPolicy())) {
        discoveryResponse.setAuthPolicy(windowsPluginProperties.getAuthPolicy());
        discoveryResponse.setEnrollmentPolicyServiceUrl(
                PluginConstants.Discovery.ENROLL_SUBDOMAIN + windowsPluginProperties.getDomain()
                        + PluginConstants.Discovery.CERTIFICATE_ENROLLMENT_POLICY_SERVICE_URL);
        discoveryResponse.setEnrollmentServiceUrl(
                PluginConstants.Discovery.ENROLL_SUBDOMAIN + windowsPluginProperties.getDomain()
                        + PluginConstants.Discovery.CERTIFICATE_ENROLLMENT_SERVICE_URL);
        discoveryResponse.setAuthenticationServiceUrl(PluginConstants.Discovery.ENROLL_SUBDOMAIN
                + windowsPluginProperties.getDomain() + PluginConstants.Discovery.WAB_URL);
    } else {
        discoveryResponse.setAuthPolicy(windowsPluginProperties.getAuthPolicy());
        discoveryResponse.setEnrollmentPolicyServiceUrl(
                PluginConstants.Discovery.ENROLL_SUBDOMAIN + windowsPluginProperties.getDomain()
                        + PluginConstants.Discovery.ONPREMISE_CERTIFICATE_ENROLLMENT_POLICY);
        discoveryResponse.setEnrollmentServiceUrl(
                PluginConstants.Discovery.ENROLL_SUBDOMAIN + windowsPluginProperties.getDomain()
                        + PluginConstants.Discovery.ONPREMISE_CERTIFICATE_ENROLLMENT_SERVICE_URL);
        discoveryResponse.setAuthenticationServiceUrl(null);
    }
    response.value = discoveryResponse;

    if (log.isDebugEnabled()) {
        log.debug("Discovery service end point was triggered via POST method");
    }
}

From source file:org.wso2.carbon.mdm.mobileservices.windows.services.wstep.impl.CertificateEnrollmentServiceImpl.java

/**
 * This method implements MS-WSTEP for Certificate Enrollment Service.
 *
 * @param tokenType           - Device Enrolment Token type is received via device
 * @param requestType         - WS-Trust request type
 * @param binarySecurityToken - CSR from device
 * @param additionalContext   - Device type and OS version is received
 * @param response            - Response will include wap-provisioning xml
 *//*from  w w w .  j  a  va 2s  .c  o  m*/
@Override
public void requestSecurityToken(String tokenType, String requestType, String binarySecurityToken,
        AdditionalContext additionalContext, Holder<RequestSecurityTokenResponse> response)
        throws WindowsDeviceEnrolmentException, UnsupportedEncodingException, WAPProvisioningException {

    String headerBinarySecurityToken = null;
    List<Header> headers = getHeaders();
    for (Header headerElement : headers != null ? headers : null) {
        String nodeName = headerElement.getName().getLocalPart();
        if (nodeName.equals(PluginConstants.SECURITY)) {
            Element element = (Element) headerElement.getObject();
            headerBinarySecurityToken = element.getFirstChild().getNextSibling().getFirstChild()
                    .getTextContent();
        }
    }
    List<ConfigurationEntry> tenantConfigurations = null;
    try {
        if (getTenantConfigurationData() != null) {
            tenantConfigurations = getTenantConfigurationData();
            for (ConfigurationEntry configurationEntry : tenantConfigurations) {
                if (configurationEntry.getName()
                        .equals(PluginConstants.TenantConfigProperties.NOTIFIER_FREQUENCY)) {
                    pollingFrequency = configurationEntry.getValue().toString();
                } else {
                    pollingFrequency = PluginConstants.TenantConfigProperties.DEFAULT_FREQUENCY;
                }
            }
        } else {
            pollingFrequency = PluginConstants.TenantConfigProperties.DEFAULT_FREQUENCY;
            String msg = "Tenant configurations are not initialized yet.";
            log.error(msg);
        }
    } catch (DeviceManagementException e) {
        String msg = "Error occurred in while getting tenant configurations.";
        log.error(msg);
        throw new WindowsDeviceEnrolmentException(msg, e);
    }
    ServletContext ctx = (ServletContext) context.getMessageContext().get(MessageContext.SERVLET_CONTEXT);
    File wapProvisioningFile = (File) ctx.getAttribute(PluginConstants.CONTEXT_WAP_PROVISIONING_FILE);

    if (log.isDebugEnabled()) {
        log.debug("Received CSR from Device:" + binarySecurityToken);
    }
    String wapProvisioningFilePath = wapProvisioningFile.getPath();
    RequestSecurityTokenResponse requestSecurityTokenResponse = new RequestSecurityTokenResponse();
    requestSecurityTokenResponse.setTokenType(PluginConstants.CertificateEnrolment.TOKEN_TYPE);
    String encodedWap;
    try {
        encodedWap = prepareWapProvisioningXML(binarySecurityToken, wapProvisioningFilePath,
                headerBinarySecurityToken);
        RequestedSecurityToken requestedSecurityToken = new RequestedSecurityToken();
        BinarySecurityToken binarySecToken = new BinarySecurityToken();
        binarySecToken.setValueType(PluginConstants.CertificateEnrolment.VALUE_TYPE);
        binarySecToken.setEncodingType(PluginConstants.CertificateEnrolment.ENCODING_TYPE);
        binarySecToken.setToken(encodedWap);
        requestedSecurityToken.setBinarySecurityToken(binarySecToken);
        requestSecurityTokenResponse.setRequestedSecurityToken(requestedSecurityToken);
        requestSecurityTokenResponse.setRequestID(REQUEST_ID);
        response.value = requestSecurityTokenResponse;
    } catch (CertificateGenerationException e) {
        String msg = "Problem occurred in generating certificate.";
        log.error(msg, e);
        throw new WindowsDeviceEnrolmentException(msg, e);
    } catch (WAPProvisioningException e) {
        String msg = "Problem occurred in generating wap-provisioning file.";
        log.error(msg, e);
        throw new WAPProvisioningException(msg, e);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}

From source file:org.wso2.carbon.mdm.mobileservices.windowspc.services.syncml.impl.SyncmlServiceImpl.java

private void setChannelURI(String channelURI) {
    ServletContext ctx = (ServletContext) context.getMessageContext().get(MessageContext.SERVLET_CONTEXT);
    ctx.setAttribute("channelURI", channelURI);
}

From source file:org.wso2.carbon.mdm.mobileservices.windowspc.services.syncml.impl.SyncmlServiceImpl.java

private String getChannelURI() {
    ServletContext ctx = (ServletContext) context.getMessageContext().get(MessageContext.SERVLET_CONTEXT);
    String channelURI = (String) ctx.getAttribute("channelURI");
    return channelURI;
}

From source file:org.wso2.carbon.mdm.mobileservices.windowspc.services.wstep.impl.CertificateEnrollmentServiceImpl.java

/**
 * This method implements MS-WSTEP for Certificate Enrollment Service.
 *
 * @param tokenType           - Device Enrolment Token type is received via device
 * @param requestType         - WS-Trust request type
 * @param binarySecurityToken - CSR from device
 * @param additionalContext   - Device type and OS version is received
 * @param response            - Response will include wap-provisioning xml
 *//*w  w w  .  j a  va  2s . c  om*/
@Override
public void requestSecurityToken(String tokenType, String requestType, String binarySecurityToken,
        AdditionalContext additionalContext, Holder<RequestSecurityTokenResponse> response)
        throws WindowsDeviceEnrolmentException {
    ServletContext ctx = (ServletContext) context.getMessageContext().get(MessageContext.SERVLET_CONTEXT);

    File wapProvisioningFile = (File) ctx.getAttribute(Constants.CONTEXT_WAP_PROVISIONING_FILE);
    String storePassword = (String) ctx.getAttribute(Constants.CONTEXT_MDM_PASSWORD);
    String keyPassword = (String) ctx.getAttribute(Constants.CONTEXT_MDM_PRIVATE_KEY_PASSWORD);

    List certPropertyList = new ArrayList();
    String commonName = (String) ctx.getAttribute(Constants.CONTEXT_COMMON_NAME);
    certPropertyList.add(commonName);
    int notBeforeDate = (Integer) ctx.getAttribute(Constants.CONTEXT_NOT_BEFORE_DATE);
    certPropertyList.add(notBeforeDate);
    int notAfterDate = (Integer) ctx.getAttribute(Constants.CONTEXT_NOT_AFTER_DATE);
    certPropertyList.add(notAfterDate);
    try {
        setRootCertAndKey(storePassword, keyPassword);
    }
    //Generic exception is caught here as there is no need of taking different actions for
    // different exceptions.
    catch (Exception e) {
        throw new WindowsDeviceEnrolmentException(
                "Root certificate and private key couldn't be extracted from keystore.", e);
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Received CSR from Device:" + binarySecurityToken);
    }
    String wapProvisioningFilePath = wapProvisioningFile.getPath();
    RequestSecurityTokenResponse requestSecurityTokenResponse = new RequestSecurityTokenResponse();
    requestSecurityTokenResponse.setTokenType(Constants.CertificateEnrollment.TOKEN_TYPE);
    String encodedWap;
    try {
        encodedWap = prepareWapProvisioningXML(binarySecurityToken, certPropertyList, wapProvisioningFilePath);
    }
    //Generic exception is caught here as there is no need of taking different actions for
    // different exceptions.
    catch (Exception e) {
        throw new WindowsDeviceEnrolmentException("Wap provisioning file couldn't be " + "prepared.", e);
    }

    RequestedSecurityToken requestedSecurityToken = new RequestedSecurityToken();
    BinarySecurityToken binarySecToken = new BinarySecurityToken();
    binarySecToken.setValueType(Constants.CertificateEnrollment.VALUE_TYPE);
    binarySecToken.setEncodingType(Constants.CertificateEnrollment.ENCODING_TYPE);
    binarySecToken.setToken(encodedWap);
    requestedSecurityToken.setBinarySecurityToken(binarySecToken);
    requestSecurityTokenResponse.setRequestedSecurityToken(requestedSecurityToken);
    requestSecurityTokenResponse.setRequestID(REQUEST_ID);
    response.value = requestSecurityTokenResponse;
}

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

@Test
public void testWSSecurity() throws Exception {

    // Setup//  w  w w .ja  v a2 s  .  co  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.fedict.eid.idp.protocol.ws_federation.sts.SecurityTokenServicePortImplTest.java

@Test
public void testValidation() throws Exception {
    // setup//from w  ww.  j  a va 2s.  co m
    InputStream requestInputStream = SecurityTokenServicePortImplTest.class
            .getResourceAsStream("/sts-validation-request.xml");
    assertNotNull(requestInputStream);

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document document = documentBuilder.parse(requestInputStream);

    Element requestSecurityTokenElement = (Element) document
            .getElementsByTagNameNS("http://docs.oasis-open.org/ws-sx/ws-trust/200512", "RequestSecurityToken")
            .item(0);

    Element x509Certificate = (Element) document
            .getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "X509Certificate").item(0);
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509Certificate certificate = (X509Certificate) certificateFactory.generateCertificate(
            new ByteArrayInputStream(Base64.decodeBase64(x509Certificate.getFirstChild().getNodeValue())));
    List<X509Certificate> certificateChain = Collections.singletonList(certificate);

    JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class,
            be.fedict.eid.idp.wstrust.jaxb.wspolicy.ObjectFactory.class,
            be.fedict.eid.idp.wstrust.jaxb.wsaddr.ObjectFactory.class);
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

    JAXBElement<RequestSecurityTokenType> resultElement = (JAXBElement<RequestSecurityTokenType>) unmarshaller
            .unmarshal(requestSecurityTokenElement);
    RequestSecurityTokenType requestSecurityToken = resultElement.getValue();

    SecurityTokenServicePortImpl testedInstance = new SecurityTokenServicePortImpl();

    WebServiceContext mockWebServiceContext = EasyMock.createMock(WebServiceContext.class);
    injectResource(mockWebServiceContext, testedInstance);

    MessageContext mockMessageContext = EasyMock.createMock(MessageContext.class);

    EasyMock.expect(mockWebServiceContext.getMessageContext()).andStubReturn(mockMessageContext);

    ServletContext mockServletContext = EasyMock.createMock(ServletContext.class);

    EasyMock.expect(mockMessageContext.get(MessageContext.SERVLET_CONTEXT)).andReturn(mockServletContext);

    IdentityProviderConfiguration mockIdentityProviderConfiguration = EasyMock
            .createMock(IdentityProviderConfiguration.class);

    EasyMock.expect(mockServletContext.getAttribute(
            IdentityProviderConfigurationFactory.IDENTITY_PROVIDER_CONFIGURATION_CONTEXT_ATTRIBUTE))
            .andReturn(mockIdentityProviderConfiguration);

    EasyMock.expect(mockIdentityProviderConfiguration.getIdentityCertificateChain())
            .andReturn(certificateChain);

    EasyMock.expect(mockIdentityProviderConfiguration.getDefaultIssuer()).andReturn("e-contract-2012");

    Element samlElement = (Element) document
            .getElementsByTagNameNS(WSTrustConstants.SAML2_NAMESPACE, "Assertion").item(0);
    EasyMock.expect(mockMessageContext.get(WSSecuritySoapHandler.class.getName() + ".samlToken"))
            .andStubReturn(samlElement);

    // prepare
    EasyMock.replay(mockWebServiceContext, mockMessageContext, mockServletContext,
            mockIdentityProviderConfiguration);

    // operate
    RequestSecurityTokenResponseCollectionType result = testedInstance
            .requestSecurityToken(requestSecurityToken);

    // verify
    EasyMock.verify(mockWebServiceContext, mockMessageContext, mockServletContext,
            mockIdentityProviderConfiguration);
    assertNotNull(result);

    List<RequestSecurityTokenResponseType> resultList = result.getRequestSecurityTokenResponse();
    assertEquals(1, resultList.size());
    RequestSecurityTokenResponseType requestSecurityTokenResponse = resultList.get(0);
    List<Object> responseObjects = requestSecurityTokenResponse.getAny();
    boolean valid = false;
    String reason = null;
    for (Object responseObject : responseObjects) {
        LOG.debug("response object type: " + responseObject);
        if (responseObject instanceof JAXBElement) {
            JAXBElement jaxbElement = (JAXBElement) responseObject;
            QName qname = jaxbElement.getName();
            LOG.debug("qname: " + qname);
            if (new QName(WSTrustConstants.WS_TRUST_NAMESPACE, "Status").equals(qname)) {
                StatusType status = (StatusType) jaxbElement.getValue();
                String code = status.getCode();
                LOG.debug("status code: " + code);
                if (WSTrustConstants.VALID_STATUS_CODE.equals(code)) {
                    valid = true;
                }
                reason = status.getReason();
            }
        }
    }
    LOG.debug("status reason: " + reason);
    assertTrue(reason.indexOf("policy") != -1);
}