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.apache.cxf.fediz.systests.idp.IdpTest.java

@org.junit.Test
public void testForceAuthnWrongCredentials() throws Exception {
    OpenSAMLUtil.initSamlEngine();/*from w w  w.j  a va  2s  .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.setForceAuthn(Boolean.TRUE);
    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.addRequestHeader("Authorization", "Basic " + Base64.encode((user + ":" + password).getBytes()));

    //
    // First invocation
    //

    webClient.getOptions().setJavaScriptEnabled(false);
    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));

    //
    // Second invocation - change the credentials, this should fail
    //

    webClient.removeRequestHeader("Authorization");
    webClient.addRequestHeader("Authorization",
            "Basic " + Base64.encode(("mallory" + ":" + password).getBytes()));

    webClient.getOptions().setJavaScriptEnabled(false);
    try {
        webClient.getPage(url);
        Assert.fail("Authentication failure expected");
    } catch (FailingHttpStatusCodeException ex) {
        Assert.assertEquals(ex.getStatusCode(), 401);
    }

    webClient.close();
}

From source file:hoot.services.controllers.osm.ElementResource.java

private Document getElementXml(final String mapId, final long elementId, final ElementType elementType,
        final boolean multiLayerUniqueElementIds, final boolean addChildren, Connection dbConn)
        throws Exception {
    long mapIdNum = -1;
    try {/*from   ww  w.j  a  v a  2  s  .co  m*/
        QMaps maps = QMaps.maps;
        //input mapId may be a map ID or a map name
        mapIdNum = ModelDaoUtils.getRecordIdForInputString(mapId, dbConn, maps, maps.id, maps.displayName);
    } catch (Exception e) {
        if (e.getMessage().startsWith("Multiple records exist")) {
            ResourceErrorHandler.handleError(
                    e.getMessage().replaceAll("records", "maps").replaceAll("record", "map"), Status.NOT_FOUND,
                    log);
        } else if (e.getMessage().startsWith("No record exists")) {
            ResourceErrorHandler.handleError(
                    e.getMessage().replaceAll("records", "maps").replaceAll("record", "map"), Status.NOT_FOUND,
                    log);
        }
        ResourceErrorHandler.handleError("Error requesting map with ID: " + mapId + " (" + e.getMessage() + ")",
                Status.BAD_REQUEST, log);
    }

    Document elementDoc = null;
    Set<Long> elementIds = new HashSet<Long>();
    elementIds.add(elementId);
    @SuppressWarnings("unchecked")
    final List<Tuple> elementRecords = (List<Tuple>) Element.getElementRecordsWithUserInfo(mapIdNum,
            elementType, elementIds, dbConn);
    if (elementRecords == null || elementRecords.size() == 0) {
        ResourceErrorHandler.handleError(
                "Element with ID: " + elementId + " and type: " + elementType + " does not exist.",
                Status.NOT_FOUND, log);
    }
    assert (elementRecords.size() == 1);

    final Element element = ElementFactory.getInstance().create(elementType, elementRecords.get(0), dbConn,
            Long.parseLong(mapId));

    Users usersTable = elementRecords.get(0).get(QUsers.users);
    elementDoc = XmlDocumentBuilder.create();
    org.w3c.dom.Element elementRootXml = OsmResponseHeaderGenerator.getOsmDataHeader(elementDoc);
    elementDoc.appendChild(elementRootXml);
    org.w3c.dom.Element elementXml = element.toXml(elementRootXml, usersTable.getId(),
            usersTable.getDisplayName(), multiLayerUniqueElementIds, addChildren);
    elementRootXml.appendChild(elementXml);

    return elementDoc;
}

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

@org.junit.Test
public void testSeparateSignature() throws Exception {
    OpenSAMLUtil.initSamlEngine();/*from  w  w w .  j  a  va2s.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());

    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 testSuccessfulSSOInvokeOnIdPWithForceAuthn() throws Exception {
    OpenSAMLUtil.initSamlEngine();/* www. j a va 2s. 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.setForceAuthn(Boolean.TRUE);
    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));

    //
    // First invocation
    //

    webClient.getOptions().setJavaScriptEnabled(false);
    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));

    //
    // Second invocation
    //

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

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

    // Check claims
    parsedResponse = DOM2Writer.nodeToString(samlResponse.getDOM().getOwnerDocument());
    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 testSuccessfulSSOInvokeOnIdP() throws Exception {
    OpenSAMLUtil.initSamlEngine();/*w  w w  . j a v  a2 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");
    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.addRequestHeader("Authorization", "Basic " + Base64.encode((user + ":" + password).getBytes()));

    //
    // First invocation
    //

    webClient.getOptions().setJavaScriptEnabled(false);
    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));

    //
    // Second invocation - change the credentials to make sure the session is set up correctly
    //

    webClient.removeRequestHeader("Authorization");
    webClient.addRequestHeader("Authorization",
            "Basic " + Base64.encode(("mallory" + ":" + password).getBytes()));

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

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

    // Check claims
    parsedResponse = DOM2Writer.nodeToString(samlResponse.getDOM().getOwnerDocument());
    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 Future<?> loadPage(Element pageSumEl, final Set<String> allPages, final Set<Page> newPages)
        throws Exception {
    Document doc = DOMUtils.newDocument();
    Element el = doc.createElementNS(SOAPNS, "ns1:getPage");
    Element el2 = doc.createElement("in0");
    el.appendChild(el2);//from www.  ja va 2s. c  om
    el2.setTextContent(loginToken);
    el2 = doc.createElement("in1");
    el.appendChild(el2);
    el2.setTextContent(DOMUtils.getChildContent(pageSumEl, "id"));
    doc.appendChild(el);

    //make sure we only fire off about 15-20 or confluence may get a bit overloaded
    while (asyncCount.get() > 15) {
        Thread.sleep(10);
    }
    asyncCount.incrementAndGet();
    Future<?> f = getDispatch().invokeAsync(doc, new AsyncHandler<Document>() {
        public void handleResponse(Response<Document> doc) {
            try {
                Page page = new Page(doc.get(), SiteExporter.this);
                page.setExporter(SiteExporter.this);
                Page oldPage = pages.put(page.getId(), page);
                if (oldPage == null || page.getModifiedTime().compare(oldPage.getModifiedTime()) > 0) {
                    if (!modifiedPages.contains(page)) {
                        modifiedPages.add(page);
                    }
                    if (oldPage == null) {
                        //need to check parents to see if it has a {children} tag so we can re-render
                        newPages.add(page);
                    }
                }
                if (allPages.contains(page.getId())) {
                    allPages.remove(page.getId());
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                asyncCount.decrementAndGet();
            }
        }
    });
    return f;
}

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

private void loadAttachments(AbstractPage p) throws Exception {
    Document doc = DOMUtils.createDocument();
    Element el = doc.createElementNS(SOAPNS, "ns1:getAttachments");
    Element el2 = doc.createElement("in0");
    el.appendChild(el2);//from   w  ww  .j av a2  s.  c o  m
    el2.setTextContent(loginToken);
    el2 = doc.createElement("in1");
    el.appendChild(el2);
    el2.setTextContent(p.getId());
    el.appendChild(el2);
    doc.appendChild(el);

    doc = getDispatch().invoke(doc);
    el = DOMUtils.getFirstElement(DOMUtils.getFirstElement(doc.getDocumentElement()));
    while (el != null) {
        try {
            String filename = DOMUtils.getChildContent(el, "fileName");
            String durl = DOMUtils.getChildContent(el, "url");
            String aid = DOMUtils.getChildContent(el, "id");

            p.addAttachment(aid, filename);

            String dirName = p.getPath();
            dirName = dirName.substring(0, dirName.lastIndexOf(".")) + ".data";
            File file = new File(outputDir, dirName);
            if (!file.exists()) {
                callSvn("mkdir", file.getAbsolutePath());
                file.mkdirs();
            }
            filename = filename.replace(' ', '-');
            file = new File(file, filename);
            boolean exists = file.exists();
            FileOutputStream out = new FileOutputStream(file);
            URL url = new URL(durl);
            InputStream ins = url.openStream();
            IOUtils.copy(ins, out);
            out.close();
            ins.close();
            if (!exists) {
                callSvn("add", file.getAbsolutePath());
                svnCommitMessage.append("Added: " + dirName + "/" + file.getName() + "\n");
            } else {
                svnCommitMessage.append("Modified: " + dirName + "/" + file.getName() + "\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        el = DOMUtils.getNextElement(el);
    }
}

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

@org.junit.Test
public void testSuccessfulSSOInvokeOnIdPWithForceAuthnSeparateSignature() throws Exception {
    OpenSAMLUtil.initSamlEngine();//from   w ww  .java2 s.  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.setForceAuthn(Boolean.TRUE);
    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());

    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));

    //
    // First invocation
    //

    webClient.getOptions().setJavaScriptEnabled(false);
    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));

    //
    // Second invocation
    //

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

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

    // Check claims
    parsedResponse = DOM2Writer.nodeToString(samlResponse.getDOM().getOwnerDocument());
    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:edu.stanford.epad.epadws.aim.AIMUtil.java

public static void returnImageAnnotationsXMLV4(PrintWriter responseStream, List<ImageAnnotationCollection> aims)
        throws ParserConfigurationException, edu.stanford.hakan.aim4api.base.AimException {
    long starttime = System.currentTimeMillis();
    DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
    Document doc = docBuilder.newDocument();
    Element root = doc.createElement("imageAnnotations");
    doc.appendChild(root);

    for (ImageAnnotationCollection aim : aims) {
        Node node = aim.getXMLNode(docBuilder.newDocument());
        Node copyNode = doc.importNode(node, true);
        Element res = (Element) copyNode; // Copy the node
        res.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:rdf",
                "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
        res.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xsi",
                "http://www.w3.org/2001/XMLSchema-instance");
        res.setAttribute("xsi:schemaLocation",
                "gme://caCORE.caCORE/4.4/edu.northwestern.radiology.AIM AIM_v4_rv44_XML.xsd");
        res.setAttribute("xmlns", "gme://caCORE.caCORE/4.4/edu.northwestern.radiology.AIM");
        Node n = renameNodeNS(res, "ImageAnnotationCollection",
                "gme://caCORE.caCORE/4.4/edu.northwestern.radiology.AIM");
        root.appendChild(n); // Adding to the root
    }/*from   ww w.  ja  v a 2 s.co  m*/
    String queryResults = XmlDocumentToString(doc, "gme://caCORE.caCORE/4.4/edu.northwestern.radiology.AIM");
    long xmltime = System.currentTimeMillis();
    log.info("Time taken create xml:" + (xmltime - starttime) + " msecs for " + aims.size() + " annotations");
    responseStream.print(queryResults);
    long resptime = System.currentTimeMillis();
    log.info("" + aims.size() + " annotations returned to client, time to write resp:" + (resptime - xmltime)
            + " msecs");
}

From source file:de.pixida.logtest.reporting.XUnitReportGenerator.java

@Override
public void finish() {
    try {//w  w  w . j  av  a 2  s .com
        // Create document
        final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        docFactory.setNamespaceAware(true);
        final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        // Create root element
        final Document doc = docBuilder.newDocument();
        final Element rootElement = doc.createElement("testsuite");
        rootElement.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
        rootElement.setAttribute("xsi:schemaLocation",
                "https://maven.apache.org/surefire/maven-surefire-plugin/xsd/surefire-test-report.xsd");
        rootElement.setAttribute("name", "LogFileAnalysisTestsuite");
        final double msToSec = 1000.0;
        rootElement.setAttribute("time", String.valueOf(this.totalTimeMs / msToSec));
        final long numTests = this.results.size();
        final long numSuccesses = this.results.values().stream()
                .mapToLong(result -> result.stream().filter(r -> r.getMiddle().isSuccess()).count()).sum();
        final long numFailures = this.results.values().stream()
                .mapToLong(result -> result.stream().filter(r -> r.getMiddle().isFailure()).count()).sum();
        final long numSkipped = 0L;
        final long numErrors = numTests - numSuccesses - numFailures;
        rootElement.setAttribute("tests", String.valueOf(numTests));
        rootElement.setAttribute("errors", String.valueOf(numErrors));
        rootElement.setAttribute("skipped", String.valueOf(numSkipped));
        rootElement.setAttribute("failures", String.valueOf(numFailures));
        doc.appendChild(rootElement);

        // Create payload
        this.addProperties(doc, rootElement);
        this.addTestCases(doc, rootElement);

        // Dump results into file
        final TransformerFactory transformerFactory = TransformerFactory.newInstance();
        final Transformer transformer = transformerFactory.newTransformer();
        final DOMSource source = new DOMSource(doc);
        final File parentFile = this.destFile.getParentFile();
        if (parentFile != null) {
            parentFile.mkdirs(); // If fails, will be caught by the following operations
        }
        final StreamResult result = new StreamResult(this.destFile);
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        transformer.transform(source, result);
    } catch (final DOMException | TransformerException | ParserConfigurationException e) {
        LOG.error("Failed to write results", e);
    }
}