Example usage for org.w3c.dom Document appendChild

List of usage examples for org.w3c.dom Document appendChild

Introduction

In this page you can find the example usage for org.w3c.dom Document appendChild.

Prototype

public Node appendChild(Node newChild) throws DOMException;

Source Link

Document

Adds the node newChild to the end of the list of children of this node.

Usage

From source file:org.canova.api.conf.Configuration.java

/**
 * Write out the non-default properties in this configuration to the give
 * {@link OutputStream}./*from w w w  .j  a  va  2 s  .  c om*/
 *
 * @param out the output stream to write to.
 */
public void writeXml(OutputStream out) throws IOException {
    Properties properties = getProps();
    try {
        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        Element conf = doc.createElement("configuration");
        doc.appendChild(conf);
        conf.appendChild(doc.createTextNode("\n"));
        for (Enumeration e = properties.keys(); e.hasMoreElements();) {
            String name = (String) e.nextElement();
            Object object = properties.get(name);
            String value;
            if (object instanceof String) {
                value = (String) object;
            } else {
                continue;
            }
            Element propNode = doc.createElement("property");
            conf.appendChild(propNode);

            Element nameNode = doc.createElement("name");
            nameNode.appendChild(doc.createTextNode(name));
            propNode.appendChild(nameNode);

            Element valueNode = doc.createElement("value");
            valueNode.appendChild(doc.createTextNode(value));
            propNode.appendChild(valueNode);

            conf.appendChild(doc.createTextNode("\n"));
        }

        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(out);
        TransformerFactory transFactory = TransformerFactory.newInstance();
        Transformer transformer = transFactory.newTransformer();
        transformer.transform(source, result);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.cxf.fediz.systests.idp.IdpTest.java

@org.junit.Test
public void testSuccessfulInvokeOnIdP() throws Exception {
    OpenSAMLUtil.initSamlEngine();//  ww  w  .j  ava 2s .  c  o m

    // Create SAML AuthnRequest
    Document doc = DOMUtils.createDocument();
    doc.appendChild(doc.createElement("root"));
    // Create the AuthnRequest
    String consumerURL = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName()
            + "/secure/fedservlet";
    AuthnRequest authnRequest = new DefaultAuthnRequestBuilder().createAuthnRequest(null,
            "urn:org:apache:cxf:fediz:fedizhelloworld", consumerURL);
    authnRequest.setDestination("https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml");
    signAuthnRequest(authnRequest);

    Element authnRequestElement = OpenSAMLUtil.toDom(authnRequest, doc);
    String authnRequestEncoded = encodeAuthnRequest(authnRequestElement);

    String urlEncodedRequest = URLEncoder.encode(authnRequestEncoded, "UTF-8");

    String relayState = UUID.randomUUID().toString();
    String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml?";
    url += SSOConstants.RELAY_STATE + "=" + relayState;
    url += "&" + SSOConstants.SAML_REQUEST + "=" + urlEncodedRequest;

    String user = "alice";
    String password = "ecila";

    final WebClient webClient = new WebClient();
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getCredentialsProvider().setCredentials(
            new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
            new UsernamePasswordCredentials(user, password));

    webClient.getOptions().setJavaScriptEnabled(false);
    final HtmlPage idpPage = webClient.getPage(url);
    webClient.getOptions().setJavaScriptEnabled(true);
    Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText());

    org.opensaml.saml.saml2.core.Response samlResponse = parseSAMLResponse(idpPage, relayState, consumerURL,
            authnRequest.getID());
    String expected = "urn:oasis:names:tc:SAML:2.0:status:Success";
    Assert.assertEquals(expected, samlResponse.getStatus().getStatusCode().getValue());

    // Check claims
    String parsedResponse = DOM2Writer.nodeToString(samlResponse.getDOM().getOwnerDocument());
    String claim = ClaimTypes.FIRSTNAME.toString();
    Assert.assertTrue(parsedResponse.contains(claim));
    claim = ClaimTypes.LASTNAME.toString();
    Assert.assertTrue(parsedResponse.contains(claim));
    claim = ClaimTypes.EMAILADDRESS.toString();
    Assert.assertTrue(parsedResponse.contains(claim));

    webClient.close();
}

From source file:org.apache.cxf.fediz.systests.idp.IdpTest.java

@org.junit.Test
public void testBadIssuerFormat() throws Exception {
    OpenSAMLUtil.initSamlEngine();//from   w  ww . j  a  v a  2s .  c  o m

    // Create SAML AuthnRequest
    Document doc = DOMUtils.createDocument();
    doc.appendChild(doc.createElement("root"));
    // Create the AuthnRequest
    String consumerURL = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName()
            + "/secure/fedservlet";

    String issuerId = "urn:org:apache:cxf:fediz:fedizhelloworld";
    Issuer issuer = SamlpRequestComponentBuilder.createIssuer(issuerId);
    issuer.setFormat("urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress");

    String nameIDFormat = "urn:oasis:names:tc:SAML:2.0:nameid-format:persistent";
    NameIDPolicy nameIDPolicy = SamlpRequestComponentBuilder.createNameIDPolicy(true, nameIDFormat, issuerId);

    AuthnContextClassRef authnCtxClassRef = SamlpRequestComponentBuilder
            .createAuthnCtxClassRef("urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport");
    RequestedAuthnContext authnCtx = SamlpRequestComponentBuilder.createRequestedAuthnCtxPolicy(
            AuthnContextComparisonTypeEnumeration.EXACT, Collections.singletonList(authnCtxClassRef), null);

    String protocolBinding = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST";
    AuthnRequest authnRequest = SamlpRequestComponentBuilder.createAuthnRequest(consumerURL, false, false,
            protocolBinding, SAMLVersion.VERSION_20, issuer, nameIDPolicy, authnCtx);

    authnRequest.setDestination("https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml");
    signAuthnRequest(authnRequest);

    Element authnRequestElement = OpenSAMLUtil.toDom(authnRequest, doc);
    String authnRequestEncoded = encodeAuthnRequest(authnRequestElement);

    String urlEncodedRequest = URLEncoder.encode(authnRequestEncoded, "UTF-8");

    String relayState = UUID.randomUUID().toString();
    String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml?";
    url += SSOConstants.RELAY_STATE + "=" + relayState;
    url += "&" + SSOConstants.SAML_REQUEST + "=" + urlEncodedRequest;

    String user = "alice";
    String password = "ecila";

    final WebClient webClient = new WebClient();
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getCredentialsProvider().setCredentials(
            new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
            new UsernamePasswordCredentials(user, password));

    webClient.getOptions().setJavaScriptEnabled(false);
    final HtmlPage idpPage = webClient.getPage(url);

    org.opensaml.saml.saml2.core.Response samlResponse = parseSAMLResponse(idpPage, relayState, consumerURL,
            authnRequest.getID());
    String expected = "urn:oasis:names:tc:SAML:2.0:status:Requester";
    Assert.assertEquals(expected, samlResponse.getStatus().getStatusCode().getValue());

    webClient.close();
}

From source file:org.apache.cxf.fediz.systests.idp.IdpTest.java

@org.junit.Test
public void testSuccessfulInvokeOnIdPUsingPOST() throws Exception {
    OpenSAMLUtil.initSamlEngine();//from  www  .  j  a v  a2 s  .com

    // Create SAML AuthnRequest
    Document doc = DOMUtils.createDocument();
    doc.appendChild(doc.createElement("root"));
    // Create the AuthnRequest
    String consumerURL = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName()
            + "/secure/fedservlet";
    AuthnRequest authnRequest = new DefaultAuthnRequestBuilder().createAuthnRequest(null,
            "urn:org:apache:cxf:fediz:fedizhelloworld", consumerURL);
    authnRequest.setDestination("https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml/up");
    signAuthnRequest(authnRequest);

    Element authnRequestElement = OpenSAMLUtil.toDom(authnRequest, doc);

    // Don't inflate the token...
    String requestMessage = DOM2Writer.nodeToString(authnRequestElement);
    String authnRequestEncoded = Base64Utility.encode(requestMessage.getBytes("UTF-8"));

    String relayState = UUID.randomUUID().toString();
    String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml/up";

    String user = "alice";
    String password = "ecila";

    final WebClient webClient = new WebClient();
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getCredentialsProvider().setCredentials(
            new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
            new UsernamePasswordCredentials(user, password));

    webClient.getOptions().setJavaScriptEnabled(false);

    WebRequest request = new WebRequest(new URL(url), HttpMethod.POST);

    request.setRequestParameters(new ArrayList<NameValuePair>());
    request.getRequestParameters().add(new NameValuePair(SSOConstants.RELAY_STATE, relayState));
    request.getRequestParameters().add(new NameValuePair(SSOConstants.SAML_REQUEST, authnRequestEncoded));

    webClient.getOptions().setJavaScriptEnabled(false);
    final HtmlPage idpPage = webClient.getPage(request);

    webClient.getOptions().setJavaScriptEnabled(true);
    Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText());

    org.opensaml.saml.saml2.core.Response samlResponse = parseSAMLResponse(idpPage, relayState, consumerURL,
            authnRequest.getID());
    String expected = "urn:oasis:names:tc:SAML:2.0:status:Success";
    Assert.assertEquals(expected, samlResponse.getStatus().getStatusCode().getValue());

    // Check claims
    String parsedResponse = DOM2Writer.nodeToString(samlResponse.getDOM().getOwnerDocument());
    String claim = ClaimTypes.FIRSTNAME.toString();
    Assert.assertTrue(parsedResponse.contains(claim));
    claim = ClaimTypes.LASTNAME.toString();
    Assert.assertTrue(parsedResponse.contains(claim));
    claim = ClaimTypes.EMAILADDRESS.toString();
    Assert.assertTrue(parsedResponse.contains(claim));

    webClient.close();
}

From source file:org.apache.cxf.cwiki.SiteExporter.java

public void loadPages() throws Exception {
    Document doc = DOMUtils.newDocument();
    Element el = doc.createElementNS(SOAPNS, "ns1:getPages");
    Element el2 = doc.createElement("in0");
    el.appendChild(el2);//from   w  w  w.  j a v  a 2 s.  c  o  m
    el2.setTextContent(loginToken);
    el2 = doc.createElement("in1");
    el.appendChild(el2);
    el2.setTextContent(spaceKey);
    doc.appendChild(el);
    doc = getDispatch().invoke(doc);

    Set<String> allPages = new CopyOnWriteArraySet<String>(pages.keySet());
    Set<Page> newPages = new CopyOnWriteArraySet<Page>();
    List<Future<?>> futures = new ArrayList<Future<?>>(allPages.size());

    // XMLUtils.printDOM(doc.getDocumentElement());

    Node nd = doc.getDocumentElement().getFirstChild().getFirstChild();
    while (nd != null) {
        if (nd instanceof Element) {
            futures.add(loadPage((Element) nd, allPages, newPages));
        }
        nd = nd.getNextSibling();
    }
    for (Future<?> f : futures) {
        //wait for all the pages to be done
        f.get();
    }
    for (Page p : newPages) {
        //pages have been added, need to check
        checkForChildren(p);
    }
    for (String id : allPages) {
        //these pages have been deleted
        Page p = pages.remove(id);
        checkForChildren(p);

        File file = new File(outputDir, p.createFileName());
        if (file.exists()) {
            callSvn("rm", file.getAbsolutePath());
            svnCommitMessage.append("Deleted: " + file.getName() + "\n");
        }
        if (file.exists()) {
            file.delete();
        }
    }
    while (checkIncludes()) {
        // nothing
    }

}

From source file:com.microsoft.windowsazure.management.scheduler.CloudServiceOperationsImpl.java

/**
* Create a cloud service./* w  ww. j a  va  2s .c  o m*/
*
* @param cloudServiceName Required. The cloud service name.
* @param parameters Required. Parameters supplied to the Create cloud
* service operation.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return A standard service response including an HTTP status code and
* request ID.
*/
@Override
public OperationResponse beginCreating(String cloudServiceName, CloudServiceCreateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (cloudServiceName == null) {
        throw new NullPointerException("cloudServiceName");
    }
    if (cloudServiceName.length() > 100) {
        throw new IllegalArgumentException("cloudServiceName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getDescription() == null) {
        throw new NullPointerException("parameters.Description");
    }
    if (parameters.getDescription().length() > 1024) {
        throw new IllegalArgumentException("parameters.Description");
    }
    if (parameters.getGeoRegion() == null) {
        throw new NullPointerException("parameters.GeoRegion");
    }
    if (parameters.getLabel() == null) {
        throw new NullPointerException("parameters.Label");
    }
    if (parameters.getLabel().length() > 100) {
        throw new IllegalArgumentException("parameters.Label");
    }

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        tracingParameters.put("cloudServiceName", cloudServiceName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "beginCreatingAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/CloudServices/";
    url = url + URLEncoder.encode(cloudServiceName, "UTF-8");
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

    // Create HTTP transport objects
    HttpPut httpRequest = new HttpPut(url);

    // Set Headers
    httpRequest.setHeader("Content-Type", "application/xml");
    httpRequest.setHeader("x-ms-version", "2013-03-01");

    // Serialize Request
    String requestContent = null;
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document requestDoc = documentBuilder.newDocument();

    Element cloudServiceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "CloudService");
    requestDoc.appendChild(cloudServiceElement);

    Element labelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Label");
    labelElement.appendChild(requestDoc.createTextNode(parameters.getLabel()));
    cloudServiceElement.appendChild(labelElement);

    Element descriptionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "Description");
    descriptionElement.appendChild(requestDoc.createTextNode(parameters.getDescription()));
    cloudServiceElement.appendChild(descriptionElement);

    Element geoRegionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "GeoRegion");
    geoRegionElement.appendChild(requestDoc.createTextNode(parameters.getGeoRegion()));
    cloudServiceElement.appendChild(geoRegionElement);

    if (parameters.getEmail() != null) {
        Element emailElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Email");
        emailElement.appendChild(requestDoc.createTextNode(parameters.getEmail()));
        cloudServiceElement.appendChild(emailElement);
    }

    DOMSource domSource = new DOMSource(requestDoc);
    StringWriter stringWriter = new StringWriter();
    StreamResult streamResult = new StreamResult(stringWriter);
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.transform(domSource, streamResult);
    requestContent = stringWriter.toString();
    StringEntity entity = new StringEntity(requestContent);
    httpRequest.setEntity(entity);
    httpRequest.setHeader("Content-Type", "application/xml");

    // Send Request
    HttpResponse httpResponse = null;
    try {
        if (shouldTrace) {
            CloudTracing.sendRequest(invocationId, httpRequest);
        }
        httpResponse = this.getClient().getHttpClient().execute(httpRequest);
        if (shouldTrace) {
            CloudTracing.receiveResponse(invocationId, httpResponse);
        }
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_ACCEPTED) {
            ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        OperationResponse result = null;
        // Deserialize Response
        result = new OperationResponse();
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
            result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
        }

        if (shouldTrace) {
            CloudTracing.exit(invocationId, result);
        }
        return result;
    } finally {
        if (httpResponse != null && httpResponse.getEntity() != null) {
            httpResponse.getEntity().getContent().close();
        }
    }
}

From source file:org.apache.cxf.fediz.systests.idp.IdpTest.java

@org.junit.Test
public void testSeparateSignatureWrongSignedContent() throws Exception {
    OpenSAMLUtil.initSamlEngine();/* w w w  .  java 2 s  .  c om*/

    // Create SAML AuthnRequest
    Document doc = DOMUtils.createDocument();
    doc.appendChild(doc.createElement("root"));
    // Create the AuthnRequest
    String consumerURL = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName()
            + "/secure/fedservlet";
    AuthnRequest authnRequest = new DefaultAuthnRequestBuilder().createAuthnRequest(null,
            "urn:org:apache:cxf:fediz:fedizhelloworld", consumerURL);
    authnRequest.setDestination("https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml");

    Element authnRequestElement = OpenSAMLUtil.toDom(authnRequest, doc);
    String authnRequestEncoded = encodeAuthnRequest(authnRequestElement);

    String urlEncodedRequest = URLEncoder.encode(authnRequestEncoded, "UTF-8");

    String relayState = UUID.randomUUID().toString();

    // Sign request
    Crypto crypto = CryptoFactory.getInstance("stsKeystoreA.properties");

    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias("realma");

    // Get the private key
    PrivateKey privateKey = crypto.getPrivateKey("realma", "realma");

    java.security.Signature signature = java.security.Signature.getInstance("SHA1withRSA");
    signature.initSign(privateKey);

    String requestToSign = SSOConstants.SAML_REQUEST + "=" + urlEncodedRequest;
    requestToSign += "&" + SSOConstants.RELAY_STATE + "=" + relayState;
    requestToSign += "&" + SSOConstants.SIG_ALG + "="
            + URLEncoder.encode(SSOConstants.RSA_SHA1, StandardCharsets.UTF_8.name()) + "asf=xyz";

    signature.update(requestToSign.getBytes(StandardCharsets.UTF_8));
    byte[] signBytes = signature.sign();

    String encodedSignature = Base64.encode(signBytes);

    String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml/up?";
    url += SSOConstants.RELAY_STATE + "=" + relayState;
    url += "&" + SSOConstants.SAML_REQUEST + "=" + urlEncodedRequest;
    url += "&" + SSOConstants.SIGNATURE + "="
            + URLEncoder.encode(encodedSignature, StandardCharsets.UTF_8.name());

    String user = "alice";
    String password = "ecila";

    final WebClient webClient = new WebClient();
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getCredentialsProvider().setCredentials(
            new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
            new UsernamePasswordCredentials(user, password));

    webClient.getOptions().setJavaScriptEnabled(false);
    final HtmlPage idpPage = webClient.getPage(url);

    org.opensaml.saml.saml2.core.Response samlResponse = parseSAMLResponse(idpPage, relayState, consumerURL,
            authnRequest.getID());
    String expected = "urn:oasis:names:tc:SAML:2.0:status:Requester";
    Assert.assertEquals(expected, samlResponse.getStatus().getStatusCode().getValue());

    webClient.close();
}

From source file:org.apache.cxf.fediz.systests.idp.IdpTest.java

@org.junit.Test
public void testBase64DecodingErrorSeparateSignature() throws Exception {
    OpenSAMLUtil.initSamlEngine();/* ww w. ja va2 s  .  co m*/

    // Create SAML AuthnRequest
    Document doc = DOMUtils.createDocument();
    doc.appendChild(doc.createElement("root"));
    // Create the AuthnRequest
    String consumerURL = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName()
            + "/secure/fedservlet";
    AuthnRequest authnRequest = new DefaultAuthnRequestBuilder().createAuthnRequest(null,
            "urn:org:apache:cxf:fediz:fedizhelloworld", consumerURL);
    authnRequest.setDestination("https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml");

    Element authnRequestElement = OpenSAMLUtil.toDom(authnRequest, doc);
    String authnRequestEncoded = encodeAuthnRequest(authnRequestElement);

    String urlEncodedRequest = URLEncoder.encode(authnRequestEncoded, "UTF-8");

    String relayState = UUID.randomUUID().toString();

    // Sign request
    Crypto crypto = CryptoFactory.getInstance("stsKeystoreA.properties");

    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias("realma");

    // Get the private key
    PrivateKey privateKey = crypto.getPrivateKey("realma", "realma");

    java.security.Signature signature = java.security.Signature.getInstance("SHA1withRSA");
    signature.initSign(privateKey);

    String requestToSign = SSOConstants.SAML_REQUEST + "=" + urlEncodedRequest;
    requestToSign += "&" + SSOConstants.RELAY_STATE + "=" + relayState;
    requestToSign += "&" + SSOConstants.SIG_ALG + "="
            + URLEncoder.encode(SSOConstants.RSA_SHA1, StandardCharsets.UTF_8.name());

    signature.update(requestToSign.getBytes(StandardCharsets.UTF_8));
    byte[] signBytes = signature.sign();

    String encodedSignature = Base64.encode(signBytes);

    String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml/up?";
    url += SSOConstants.RELAY_STATE + "=" + relayState;
    url += "&" + SSOConstants.SAML_REQUEST + "=" + urlEncodedRequest;
    url += "&" + SSOConstants.SIGNATURE + "="
            + URLEncoder.encode(encodedSignature, StandardCharsets.UTF_8.name());
    url += "-xyz";

    String user = "alice";
    String password = "ecila";

    final WebClient webClient = new WebClient();
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getCredentialsProvider().setCredentials(
            new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
            new UsernamePasswordCredentials(user, password));

    webClient.getOptions().setJavaScriptEnabled(false);
    final HtmlPage idpPage = webClient.getPage(url);

    org.opensaml.saml.saml2.core.Response samlResponse = parseSAMLResponse(idpPage, relayState, consumerURL,
            authnRequest.getID());
    String expected = "urn:oasis:names:tc:SAML:2.0:status:Requester";
    Assert.assertEquals(expected, samlResponse.getStatus().getStatusCode().getValue());

    webClient.close();
}

From source file:org.apache.cxf.cwiki.SiteExporter.java

public void loadBlog() throws Exception {
    System.out.println("Loading Blog entries for " + spaceKey);
    Document doc = DOMUtils.createDocument();
    Element el = doc.createElementNS(SOAPNS, "ns1:getBlogEntries");
    Element el2 = doc.createElement("in0");
    el.appendChild(el2);// w  w w.  j  a v a2s.  c om
    el2.setTextContent(loginToken);
    el2 = doc.createElement("in1");
    el.appendChild(el2);
    el2.setTextContent(spaceKey);
    doc.appendChild(el);
    doc = getDispatch().invoke(doc);

    Map<String, BlogEntrySummary> oldBlog = new ConcurrentHashMap<String, BlogEntrySummary>(blog);

    Node nd = doc.getDocumentElement().getFirstChild().getFirstChild();
    while (nd != null) {
        if (nd instanceof Element) {
            BlogEntrySummary entry = new BlogEntrySummary((Element) nd);
            entry.setVersion(getBlogVersion(entry.id));
            BlogEntrySummary oldEntry = blog.put(entry.getId(), entry);
            System.out.println("Found Blog entry for " + entry.getTitle() + " " + entry.getPath());

            if (oldEntry == null || oldEntry.getVersion() != entry.getVersion()) {
                System.out.println("   and it's modified");
                modifiedBlog.add(entry);
            } else {
                System.out.println("   but it's not modified");
            }
            oldBlog.remove(entry.getId());
        }
        nd = nd.getNextSibling();
    }

    for (String id : oldBlog.keySet()) {
        //these pages have been deleted
        BlogEntrySummary p = blog.remove(id);
        File file = new File(outputDir, p.getPath());
        if (file.exists()) {
            callSvn("rm", file.getAbsolutePath());
            svnCommitMessage.append("Deleted: " + file.getName() + "\n");
        }
        if (file.exists()) {
            file.delete();
        }
    }
}

From source file:org.apache.cxf.fediz.systests.idp.IdpTest.java

@org.junit.Test
public void testChangedSeparateSignature() throws Exception {
    OpenSAMLUtil.initSamlEngine();//  www .  j av  a  2  s  .  com

    // Create SAML AuthnRequest
    Document doc = DOMUtils.createDocument();
    doc.appendChild(doc.createElement("root"));
    // Create the AuthnRequest
    String consumerURL = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName()
            + "/secure/fedservlet";
    AuthnRequest authnRequest = new DefaultAuthnRequestBuilder().createAuthnRequest(null,
            "urn:org:apache:cxf:fediz:fedizhelloworld", consumerURL);
    authnRequest.setDestination("https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml");

    Element authnRequestElement = OpenSAMLUtil.toDom(authnRequest, doc);
    String authnRequestEncoded = encodeAuthnRequest(authnRequestElement);

    String urlEncodedRequest = URLEncoder.encode(authnRequestEncoded, "UTF-8");

    String relayState = UUID.randomUUID().toString();

    // Sign request
    Crypto crypto = CryptoFactory.getInstance("stsKeystoreA.properties");

    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias("realma");

    // Get the private key
    PrivateKey privateKey = crypto.getPrivateKey("realma", "realma");

    java.security.Signature signature = java.security.Signature.getInstance("SHA1withRSA");
    signature.initSign(privateKey);

    String requestToSign = SSOConstants.SAML_REQUEST + "=" + urlEncodedRequest;
    requestToSign += "&" + SSOConstants.RELAY_STATE + "=" + relayState;
    requestToSign += "&" + SSOConstants.SIG_ALG + "="
            + URLEncoder.encode(SSOConstants.RSA_SHA1, StandardCharsets.UTF_8.name());

    signature.update(requestToSign.getBytes(StandardCharsets.UTF_8));
    byte[] signBytes = signature.sign();
    if (signBytes[1] != (byte) 1) {
        signBytes[1] = (byte) 1;
    } else {
        signBytes[1] = (byte) 2;
    }

    String encodedSignature = Base64.encode(signBytes);

    String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml/up?";
    url += SSOConstants.RELAY_STATE + "=" + relayState;
    url += "&" + SSOConstants.SAML_REQUEST + "=" + urlEncodedRequest;
    url += "&" + SSOConstants.SIGNATURE + "="
            + URLEncoder.encode(encodedSignature, StandardCharsets.UTF_8.name());

    String user = "alice";
    String password = "ecila";

    final WebClient webClient = new WebClient();
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getCredentialsProvider().setCredentials(
            new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
            new UsernamePasswordCredentials(user, password));

    webClient.getOptions().setJavaScriptEnabled(false);
    final HtmlPage idpPage = webClient.getPage(url);

    org.opensaml.saml.saml2.core.Response samlResponse = parseSAMLResponse(idpPage, relayState, consumerURL,
            authnRequest.getID());
    String expected = "urn:oasis:names:tc:SAML:2.0:status:Requester";
    Assert.assertEquals(expected, samlResponse.getStatus().getStatusCode().getValue());

    webClient.close();
}