com.gargoylesoftware.htmlunit.xml.XmlPage Java Examples

The following examples show how to use com.gargoylesoftware.htmlunit.xml.XmlPage. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: XSLTProcessor.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Transforms the node source applying the stylesheet given by the importStylesheet() function.
 * The owner document of the output node owns the returned document fragment.
 *
 * @param source the node to be transformed
 * @return the result of the transformation
 */
@JsxFunction
public XMLDocument transformToDocument(final Node source) {
    final XMLDocument doc = new XMLDocument();
    doc.setPrototype(getPrototype(doc.getClass()));
    doc.setParentScope(getParentScope());

    final Object transformResult = transform(source);
    final org.w3c.dom.Node node;
    if (transformResult instanceof org.w3c.dom.Node) {
        final org.w3c.dom.Node transformedDoc = (org.w3c.dom.Node) transformResult;
        node = transformedDoc.getFirstChild();
    }
    else {
        node = null;
    }
    final XmlPage page = new XmlPage(node, getWindow().getWebWindow());
    doc.setDomNode(page);
    return doc;
}
 
Example #2
Source File: XMLDocument.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the element with the specified ID, as long as it is an HTML element; {@code null} otherwise.
 * @param id the ID to search for
 * @return the element with the specified ID, as long as it is an HTML element; {@code null} otherwise
 */
@JsxFunction
public Object getElementById(final String id) {
    final DomNode domNode = getDomNodeOrDie();
    final Object domElement = domNode.getFirstByXPath("//*[@id = \"" + id + "\"]");
    if (domElement != null) {
        if (!(domNode instanceof XmlPage) || domElement instanceof HtmlElement
                || getBrowserVersion().hasFeature(JS_XML_GET_ELEMENT_BY_ID__ANY_ELEMENT)) {
            return ((DomElement) domElement).getScriptableObject();
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("getElementById(" + id + "): no HTML DOM node found with this ID");
        }
    }
    return null;
}
 
Example #3
Source File: XMLDocument.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Loads an XML document from the specified location.
 *
 * @param xmlSource a string containing a URL that specifies the location of the XML file
 * @return true if the load succeeded; false if the load failed
 */
@JsxFunction(FF)
public boolean load(final String xmlSource) {
    if (async_) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("XMLDocument.load(): 'async' is true, currently treated as false.");
        }
    }
    try {
        final WebWindow ww = getWindow().getWebWindow();
        final HtmlPage htmlPage = (HtmlPage) ww.getEnclosedPage();
        final WebRequest request = new WebRequest(htmlPage.getFullyQualifiedUrl(xmlSource));
        final WebResponse webResponse = ww.getWebClient().loadWebResponse(request);
        final XmlPage page = new XmlPage(webResponse, ww, false);
        setDomNode(page);
        return true;
    }
    catch (final IOException e) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Error parsing XML from '" + xmlSource + "'", e);
        }
        return false;
    }
}
 
Example #4
Source File: HtmlObject.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize the ActiveX(Mock).
 * {@inheritDoc}
 */
@Override
protected void onAllChildrenAddedToPage(final boolean postponed) {
    if (getOwnerDocument() instanceof XmlPage) {
        return;
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Object node added: " + asXml());
    }

    final String clsId = getClassIdAttribute();
    if (ATTRIBUTE_NOT_DEFINED != clsId) {
        ((HTMLObjectElement) getScriptableObject()).setClassid(clsId);
    }
}
 
Example #5
Source File: XSLTProcessor.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Transforms the node source applying the stylesheet given by the importStylesheet() function.
 * The owner document of the output node owns the returned document fragment.
 *
 * @param source the node to be transformed
 * @return the result of the transformation
 */
@JsxFunction
public XMLDocument transformToDocument(final Node source) {
    final XMLDocument doc = new XMLDocument();
    doc.setPrototype(getPrototype(doc.getClass()));
    doc.setParentScope(getParentScope());

    final Object transformResult = transform(source);
    final org.w3c.dom.Node node;
    if (transformResult instanceof org.w3c.dom.Node) {
        final org.w3c.dom.Node transformedDoc = (org.w3c.dom.Node) transformResult;
        node = transformedDoc.getFirstChild();
    }
    else {
        node = null;
    }
    final XmlPage page = new XmlPage(node, getWindow().getWebWindow());
    doc.setDomNode(page);
    return doc;
}
 
Example #6
Source File: HtmlUnitPrefixResolver.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public String getNamespaceForPrefix(final String prefix, final Node namespaceContext) {
    String namespace = super.getNamespaceForPrefix(prefix, namespaceContext);
    if (namespace == null) {
        if (namespaceContext instanceof XmlPage) {
            final DomElement documentElement = ((XmlPage) namespaceContext).getDocumentElement();
            if (documentElement != null) {
                namespace = getNamespace(documentElement, prefix);
            }
        }
        else if (namespaceContext instanceof DomElement) {
            namespace = getNamespace((DomElement) namespaceContext, prefix);
        }
    }
    return namespace;
}
 
Example #7
Source File: DomNodeTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void getByXPath_XML() throws Exception {
    final String xml
        = "<books>\n"
        + "  <book>\n"
        + "    <title>Immortality</title>\n"
        + "    <author>John Smith</author>\n"
        + "  </book>\n"
        + "</books>";

    getMockWebConnection().setResponse(URL_FIRST, xml, MimeType.TEXT_XML);
    final WebClient client = getWebClientWithMockWebConnection();
    final XmlPage page = (XmlPage) client.getPage(URL_FIRST);

    final List<?> results = page.getByXPath("//title");
    assertEquals(1, results.size());
}
 
Example #8
Source File: HtmlSerializerVisibleText2Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Test {@link HtmlSerializerTextBuilder} special spaces.
 * @throws Exception if the test fails
 */
@Test
@Alerts(DEFAULT = "baz",
        CHROME = "",
        IE = "<foo>\n<bar>baz</bar>\n</foo>")
@NotYetImplemented({CHROME, IE})
public void xmlPage() throws Exception {
    final String xml = "<xml>\n"
            + "  <foo>\n"
            + "    <bar>baz</bar>\n"
            + "  </foo>\n"
            + "</xml>";
    final WebDriver driver = loadPage2(xml, URL_FIRST, "text/xml;charset=ISO-8859-1", ISO_8859_1);
    final String text = driver.findElement(By.xpath("//foo")).getText();
    assertEquals(getExpectedAlerts()[0], text);

    if (driver instanceof HtmlUnitDriver) {
        final XmlPage page = (XmlPage) getWebWindowOf((HtmlUnitDriver) driver).getEnclosedPage();
        final DomNode node = page.getFirstByXPath("//foo");
        assertEquals(getExpectedAlerts()[0], node.getVisibleText());
    }
}
 
Example #9
Source File: DomElement2Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Test case for Bug #1905.
 *
 * @throws Exception if the test fails
 */
@Test
public void getChildElements() throws Exception {
    final String xml = "<events>\n"
            + "  <something/>\n"
            + "</events>";
    getMockWebConnection().setDefaultResponse(xml, MimeType.TEXT_XML);
    getWebClient().setWebConnection(getMockWebConnection());
    final XmlPage page = getWebClient().getPage(URL_FIRST);
    final DomElement root = page.getDocumentElement();
    final AtomicInteger count = new AtomicInteger(0);
    root.getChildElements().forEach(e -> count.incrementAndGet());
    assertEquals(1, count.get());

    count.set(0);
    root.getChildren().forEach(e -> count.incrementAndGet());
    assertEquals(3, count.get());
}
 
Example #10
Source File: ExternalTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Tests that the deployed snapshot is not more than two weeks old.
 *
 * Currently it is configured to check every week.
 *
 * @throws Exception if an error occurs
 */
@Test
public void snapshot() throws Exception {
    final List<String> lines = FileUtils.readLines(new File("pom.xml"), ISO_8859_1);
    String version = null;
    for (int i = 0; i < lines.size(); i++) {
        if ("<artifactId>htmlunit</artifactId>".equals(lines.get(i).trim())) {
            version = getValue(lines.get(i + 1));
            break;
        }
    }
    assertNotNull(version);
    if (version.contains("SNAPSHOT")) {
        try (WebClient webClient = buildWebClient()) {
            final XmlPage page = webClient.getPage("https://oss.sonatype.org/content/repositories/snapshots/"
                    + "net/sourceforge/htmlunit/htmlunit/" + version + "/maven-metadata.xml");
            final String timestamp = page.getElementsByTagName("timestamp").get(0).getTextContent();
            final DateFormat format = new SimpleDateFormat("yyyyMMdd.HHmmss", Locale.ROOT);
            final long snapshotMillis = format.parse(timestamp).getTime();
            final long nowMillis = System.currentTimeMillis();
            final long days = TimeUnit.MILLISECONDS.toDays(nowMillis - snapshotMillis);
            assertTrue("Snapshot not deployed for " + days + " days", days < 14);
        }
    }
}
 
Example #11
Source File: CaseResultTest.java    From junit-plugin with MIT License 6 votes vote down vote up
@Email("http://jenkins.361315.n4.nabble.com/Change-remote-API-visibility-for-CaseResult-getStdout-getStderr-td395102.html")
@Test
public void testRemoteApiDefaultVisibility() throws Exception {
    FreeStyleBuild b = configureTestBuild("test-remoteapi");

    XmlPage page = (XmlPage)rule.createWebClient().goTo("job/test-remoteapi/1/testReport/org.twia.vendor/VendorManagerTest/testCreateAdjustingFirm/api/xml","application/xml");

    int found = 0;

    found = page.getByXPath(composeXPath(MAX_VISIBILITY_FIELDS)).size();
    assertTrue("Should have found an element, but found " + found, found > 0);

    found = page.getByXPath(composeXPath(REDUCED_VISIBILITY_FIELDS)).size();
    assertTrue("Should have found an element, but found " + found, found > 0);

    found = page.getByXPath(composeXPath(OTHER_FIELDS)).size();
    assertTrue("Should have found an element, but found " + found, found > 0);
}
 
Example #12
Source File: HtmlUnitPrefixResolver.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public String getNamespaceForPrefix(final String prefix, final Node namespaceContext) {
    String namespace = super.getNamespaceForPrefix(prefix, namespaceContext);
    if (namespace == null) {
        if (namespaceContext instanceof XmlPage) {
            final DomElement documentElement = ((XmlPage) namespaceContext).getDocumentElement();
            if (documentElement != null) {
                namespace = getNamespace(documentElement, prefix);
            }
        }
        else if (namespaceContext instanceof DomElement) {
            namespace = getNamespace((DomElement) namespaceContext, prefix);
        }
    }
    return namespace;
}
 
Example #13
Source File: CaseResultTest.java    From junit-plugin with MIT License 6 votes vote down vote up
@Email("http://jenkins.361315.n4.nabble.com/Change-remote-API-visibility-for-CaseResult-getStdout-getStderr-td395102.html")
 @Test
 public void testRemoteApiNoDetails() throws Exception {
     FreeStyleBuild b = configureTestBuild("test-remoteapi");

     XmlPage page = (XmlPage)rule.createWebClient().goTo("job/test-remoteapi/1/testReport/org.twia.vendor/VendorManagerTest/testCreateAdjustingFirm/api/xml?depth=-1","application/xml");

     int found = 0;

     found = page.getByXPath(composeXPath(MAX_VISIBILITY_FIELDS)).size();
     assertTrue("Should have found an element, but found " + found, found > 0);

     found = page.getByXPath(composeXPath(REDUCED_VISIBILITY_FIELDS)).size();
     assertTrue("Should have found 0 elements, but found " + found, found == 0);

     found = page.getByXPath(composeXPath(OTHER_FIELDS)).size();
     assertTrue("Should have found an element, but found " + found, found > 0);
}
 
Example #14
Source File: CaseResultTest.java    From junit-plugin with MIT License 6 votes vote down vote up
@Email("http://jenkins.361315.n4.nabble.com/Change-remote-API-visibility-for-CaseResult-getStdout-getStderr-td395102.html")
@Test
public void testRemoteApiNameOnly() throws Exception {
    FreeStyleBuild b = configureTestBuild("test-remoteapi");

    XmlPage page = (XmlPage)rule.createWebClient().goTo("job/test-remoteapi/1/testReport/org.twia.vendor/VendorManagerTest/testCreateAdjustingFirm/api/xml?depth=-10","application/xml");

    int found = 0;

    found = page.getByXPath(composeXPath(MAX_VISIBILITY_FIELDS)).size();
    assertTrue("Should have found an element, but found " + found, found > 0);

    found = page.getByXPath(composeXPath(REDUCED_VISIBILITY_FIELDS)).size();
    assertTrue("Should have found 0 elements, but found " + found, found == 0);

    found = page.getByXPath(composeXPath(OTHER_FIELDS)).size();
    assertTrue("Should have found 0 elements, but found " + found, found == 0);
}
 
Example #15
Source File: HtmlObject.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize the ActiveX(Mock).
 * {@inheritDoc}
 */
@Override
public void onAllChildrenAddedToPage(final boolean postponed) {
    if (getOwnerDocument() instanceof XmlPage) {
        return;
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Object node added: " + asXml());
    }

    final String clsId = getClassIdAttribute();
    if (ATTRIBUTE_NOT_DEFINED != clsId && getPage().getWebClient().isJavaScriptEngineEnabled()) {
        ((HTMLObjectElement) getScriptableObject()).setClassid(clsId);
    }
}
 
Example #16
Source File: XMLDocument.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Loads an XML document from the specified location.
 *
 * @param xmlSource a string containing a URL that specifies the location of the XML file
 * @return true if the load succeeded; false if the load failed
 */
@JsxFunction({FF68, FF60})
public boolean load(final String xmlSource) {
    if (async_) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("XMLDocument.load(): 'async' is true, currently treated as false.");
        }
    }
    try {
        final WebWindow ww = getWindow().getWebWindow();
        final HtmlPage htmlPage = (HtmlPage) ww.getEnclosedPage();
        final WebRequest request = new WebRequest(htmlPage.getFullyQualifiedUrl(xmlSource));
        final WebResponse webResponse = ww.getWebClient().loadWebResponse(request);
        final XmlPage page = new XmlPage(webResponse, ww, false);
        setDomNode(page);
        return true;
    }
    catch (final IOException e) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Error parsing XML from '" + xmlSource + "'", e);
        }
        return false;
    }
}
 
Example #17
Source File: Document.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the element with the specified ID, as long as it is an HTML element; {@code null} otherwise.
 * @param id the ID to search for
 * @return the element with the specified ID, as long as it is an HTML element; {@code null} otherwise
 */
@JsxFunction
public Object getElementById(final String id) {
    final DomNode domNode = getDomNodeOrDie();
    final Object domElement = domNode.getFirstByXPath("//*[@id = \"" + id + "\"]");
    if (domElement != null) {
        if (!(domNode instanceof XmlPage) || domElement instanceof HtmlElement
                || getBrowserVersion().hasFeature(JS_XML_GET_ELEMENT_BY_ID__ANY_ELEMENT)) {
            return ((DomElement) domElement).getScriptableObject();
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("getElementById(" + id + "): no HTML DOM node found with this ID");
        }
    }
    return null;
}
 
Example #18
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@Test
public void testIdPMetadata() throws Exception {
    String url = "https://localhost:" + getIdpHttpsPort()
        + "/fediz-idp/metadata?protocol=saml";

    final WebClient webClient = new WebClient();
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getOptions().setSSLClientCertificate(
        this.getClass().getClassLoader().getResource("client.jks"), "storepass", "jks");

    final XmlPage rpPage = webClient.getPage(url);
    final String xmlContent = rpPage.asXml();
    Assert.assertTrue(xmlContent.startsWith("<md:EntityDescriptor"));

    // Now validate the Signature
    Document doc = rpPage.getXmlDocument();

    doc.getDocumentElement().setIdAttributeNS(null, "ID", true);

    Node signatureNode =
        DOMUtils.getChild(doc.getDocumentElement(), "Signature");
    Assert.assertNotNull(signatureNode);

    XMLSignature signature = new XMLSignature((Element)signatureNode, "");
    org.apache.xml.security.keys.KeyInfo ki = signature.getKeyInfo();
    Assert.assertNotNull(ki);
    Assert.assertNotNull(ki.getX509Certificate());

    Assert.assertTrue(signature.checkSignatureValue(ki.getX509Certificate()));

    webClient.close();
}
 
Example #19
Source File: Text.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the value of the node.
 * @return the value of the node
 */
@JsxGetter(IE)
public Object getText() {
    final DomNode node = getDomNodeOrDie();
    if (node.getPage() instanceof XmlPage) {
        return ((DomText) node).getWholeText();
    }
    return Undefined.instance;
}
 
Example #20
Source File: SAMLSSOTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
private static String login(String url, String user, String password,
                            String idpPort, String rpIdpPort) throws IOException {
    //
    // Access the RP + get redirected to the IdP for "realm a". Then get redirected to the IdP for
    // "realm b".
    //
    final WebClient webClient = new WebClient();
    CookieManager cookieManager = new CookieManager();
    webClient.setCookieManager(cookieManager);
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getCredentialsProvider().setCredentials(
        new AuthScope("localhost", Integer.parseInt(idpPort)),
        new UsernamePasswordCredentials(user, password));

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

    Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText());

    // Now redirect back to the IdP for Realm A
    HtmlForm form = idpPage.getFormByName("signinresponseform");

    HtmlSubmitInput button = form.getInputByName("_eventId_submit");

    HtmlPage idpPageRealmA = button.click();

    Assert.assertTrue("SAML IDP Response Form".equals(idpPage.getTitleText())
                      || "IDP SignIn Response Form".equals(idpPage.getTitleText()));
    form = idpPageRealmA.getFormByName("samlsigninresponseform");

    // Now redirect back to the SAML SSO web app
    button = form.getInputByName("_eventId_submit");

    XmlPage rpPage = button.click();

    webClient.close();
    return rpPage.asXml();
}
 
Example #21
Source File: HTMLUnknownElement.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the JavaScript property {@code nodeName} for the current node.
 * @return the node name
 */
@Override
public String getNodeName() {
    final HtmlElement elem = getDomNodeOrDie();
    final Page page = elem.getPage();
    if (page instanceof XmlPage) {
        return elem.getLocalName();
    }
    return super.getNodeName();
}
 
Example #22
Source File: AbstractTests.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@Test
public void testRPMetadata() throws Exception {

    if (!isWSFederation()) {
        return;
    }

    String url = "https://localhost:" + getRpHttpsPort()
        + "/" + getServletContextName() + "/FederationMetadata/2007-06/FederationMetadata.xml";

    final WebClient webClient = new WebClient();
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getOptions().setSSLClientCertificate(
        this.getClass().getClassLoader().getResource("client.jks"), "storepass", "jks");

    final XmlPage rpPage = webClient.getPage(url);
    final String xmlContent = rpPage.asXml();
    Assert.assertTrue(xmlContent.startsWith("<md:EntityDescriptor"));

    // Now validate the Signature
    Document doc = rpPage.getXmlDocument();

    doc.getDocumentElement().setIdAttributeNS(null, "ID", true);

    Node signatureNode =
        DOMUtils.getChild(doc.getDocumentElement(), "Signature");
    Assert.assertNotNull(signatureNode);

    XMLSignature signature = new XMLSignature((Element)signatureNode, "");
    KeyInfo ki = signature.getKeyInfo();
    Assert.assertNotNull(ki);
    Assert.assertNotNull(ki.getX509Certificate());

    Assert.assertTrue(signature.checkSignatureValue(ki.getX509Certificate()));

    webClient.close();
}
 
Example #23
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@Test
public void testIdPServiceMetadata() throws Exception {
    String url = "https://localhost:" + getIdpHttpsPort()
        + "/fediz-idp/metadata/urn:org:apache:cxf:fediz:idp:realm-B";

    final WebClient webClient = new WebClient();
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getOptions().setSSLClientCertificate(
        this.getClass().getClassLoader().getResource("client.jks"), "storepass", "jks");

    final XmlPage rpPage = webClient.getPage(url);
    final String xmlContent = rpPage.asXml();
    Assert.assertTrue(xmlContent.startsWith("<md:EntityDescriptor"));

    // Now validate the Signature
    Document doc = rpPage.getXmlDocument();

    doc.getDocumentElement().setIdAttributeNS(null, "ID", true);

    Node signatureNode =
        DOMUtils.getChild(doc.getDocumentElement(), "Signature");
    Assert.assertNotNull(signatureNode);

    XMLSignature signature = new XMLSignature((Element)signatureNode, "");
    KeyInfo ki = signature.getKeyInfo();
    Assert.assertNotNull(ki);
    Assert.assertNotNull(ki.getX509Certificate());

    Assert.assertTrue(signature.checkSignatureValue(ki.getX509Certificate()));

    webClient.close();
}
 
Example #24
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@Test
public void testIdPMetadataDefault() throws Exception {
    String url = "https://localhost:" + getIdpHttpsPort()
        + "/fediz-idp/metadata";

    final WebClient webClient = new WebClient();
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getOptions().setSSLClientCertificate(
        this.getClass().getClassLoader().getResource("client.jks"), "storepass", "jks");

    final XmlPage rpPage = webClient.getPage(url);
    final String xmlContent = rpPage.asXml();
    Assert.assertTrue(xmlContent.startsWith("<md:EntityDescriptor"));

    // Now validate the Signature
    Document doc = rpPage.getXmlDocument();

    doc.getDocumentElement().setIdAttributeNS(null, "ID", true);

    Node signatureNode =
        DOMUtils.getChild(doc.getDocumentElement(), "Signature");
    Assert.assertNotNull(signatureNode);

    XMLSignature signature = new XMLSignature((Element)signatureNode, "");
    KeyInfo ki = signature.getKeyInfo();
    Assert.assertNotNull(ki);
    Assert.assertNotNull(ki.getX509Certificate());

    Assert.assertTrue(signature.checkSignatureValue(ki.getX509Certificate()));

    webClient.close();
}
 
Example #25
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@Test
public void testIdPMetadata() throws Exception {
    String url = "https://localhost:" + getIdpHttpsPort()
        + "/fediz-idp/FederationMetadata/2007-06/FederationMetadata.xml";

    final WebClient webClient = new WebClient();
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getOptions().setSSLClientCertificate(
        this.getClass().getClassLoader().getResource("client.jks"), "storepass", "jks");

    final XmlPage rpPage = webClient.getPage(url);
    final String xmlContent = rpPage.asXml();
    Assert.assertTrue(xmlContent.startsWith("<md:EntityDescriptor"));

    // Now validate the Signature
    Document doc = rpPage.getXmlDocument();

    doc.getDocumentElement().setIdAttributeNS(null, "ID", true);

    Node signatureNode =
        DOMUtils.getChild(doc.getDocumentElement(), "Signature");
    Assert.assertNotNull(signatureNode);

    XMLSignature signature = new XMLSignature((Element)signatureNode, "");
    KeyInfo ki = signature.getKeyInfo();
    Assert.assertNotNull(ki);
    Assert.assertNotNull(ki.getX509Certificate());

    Assert.assertTrue(signature.checkSignatureValue(ki.getX509Certificate()));

    webClient.close();
}
 
Example #26
Source File: TestResultPublishingTest.java    From junit-plugin with MIT License 5 votes vote down vote up
void assertTestResultsAsExpected(WebClient wc, Run run, String restOfUrl,
                                 String packageName,
                                 String expectedResult, String expectedDurationStr,
                                 int expectedTotalTests, int expectedTotalDiff,
                                 int expectedFailCount, int expectedFailDiff,
                                 int expectedSkipCount, int expectedSkipDiff) throws IOException, SAXException {

    // TODO: verify expectedResult
    // TODO: verify expectedDuration

    XmlPage xmlPage = wc.goToXml(run.getUrl() + restOfUrl + "/" + packageName + "/api/xml");
    int expectedPassCount = expectedTotalTests - expectedFailCount - expectedSkipCount;
    // Verify xml results
    rule.assertXPathValue(xmlPage, "/packageResult/failCount", Integer.toString(expectedFailCount));
    rule.assertXPathValue(xmlPage, "/packageResult/skipCount", Integer.toString(expectedSkipCount));
    rule.assertXPathValue(xmlPage, "/packageResult/passCount", Integer.toString(expectedPassCount));
    rule.assertXPathValue(xmlPage, "/packageResult/name", packageName);

    // TODO: verify html results
    HtmlPage testResultPage =   wc.getPage(run, restOfUrl);

    // Verify inter-build diffs in html table
    String xpathToFailDiff =  "//table[@id='testresult']//tr[td//span[text()=\"" + packageName + "\"]]/td[4]";
    String xpathToSkipDiff =  "//table[@id='testresult']//tr[td//span[text()=\"" + packageName + "\"]]/td[6]";
    String xpathToTotalDiff = "//table[@id='testresult']//tr[td//span[text()=\"" + packageName + "\"]]/td[last()]";

    Object totalDiffObj = testResultPage.getFirstByXPath(xpathToTotalDiff);
    assertPaneDiffText("total diff", expectedTotalDiff, totalDiffObj);

    Object failDiffObj = testResultPage.getFirstByXPath(xpathToFailDiff);
    assertPaneDiffText("failure diff", expectedFailDiff, failDiffObj);

    Object skipDiffObj = testResultPage.getFirstByXPath(xpathToSkipDiff);
    assertPaneDiffText("skip diff", expectedSkipDiff, skipDiffObj);

    // TODO: The link in the table for each of the three packages in the testReport table should link to a by-package page,
    // TODO: for example, http://localhost:8080/job/breakable/lastBuild/testReport/com.yahoo.breakable.misc/

}
 
Example #27
Source File: XMLDOMDocument.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new instance, with associated {@link XmlPage}.
 * @param enclosingWindow the window
 */
public XMLDOMDocument(final WebWindow enclosingWindow) {
    if (enclosingWindow != null) {
        try {
            final XmlPage page = new XmlPage((WebResponse) null, enclosingWindow, true, false);
            setDomNode(page);
        }
        catch (final IOException e) {
            throw Context.reportRuntimeError("IOException: " + e);
        }
    }
}
 
Example #28
Source File: XMLDOMDocument.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a processing instruction node that contains the supplied target and data.
 * @param target the target part of the processing instruction
 * @param data the rest of the processing instruction preceding the closing ?&gt; characters
 * @return the new processing instruction object
 */
@JsxFunction
public Object createProcessingInstruction(final String target, final String data) {
    final DomProcessingInstruction domProcessingInstruction =
            ((XmlPage) getPage()).createProcessingInstruction(target, data);
    return getScriptableFor(domProcessingInstruction);
}
 
Example #29
Source File: XMLDOMDocument.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Loads an XML document from the specified location.
 * @param xmlSource a URL that specifies the location of the XML file
 * @return {@code true} if the load succeeded; {@code false} if the load failed
 */
@JsxFunction
public boolean load(final String xmlSource) {
    if (async_ && LOG.isDebugEnabled()) {
        LOG.debug("XMLDOMDocument.load(): 'async' is true, currently treated as false.");
    }
    try {
        final WebWindow ww = getWindow().getWebWindow();
        final HtmlPage htmlPage = (HtmlPage) ww.getEnclosedPage();
        final URL fullyQualifiedURL = htmlPage.getFullyQualifiedUrl(xmlSource);
        final WebRequest request = new WebRequest(fullyQualifiedURL);
        final WebResponse webResponse = ww.getWebClient().loadWebResponse(request);
        final XmlPage page = new XmlPage(webResponse, ww, false, false);
        setDomNode(page);

        preserveWhiteSpaceDuringLoad_ = preserveWhiteSpace_;
        url_ = fullyQualifiedURL.toExternalForm();
        return true;
    }
    catch (final IOException e) {
        final XMLDOMParseError parseError = getParseError();
        parseError.setErrorCode(-1);
        parseError.setFilepos(1);
        parseError.setLine(1);
        parseError.setLinepos(1);
        parseError.setReason(e.getMessage());
        parseError.setSrcText("xml");
        parseError.setUrl(xmlSource);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Error parsing XML from '" + xmlSource + "'", e);
        }
        return false;
    }
}
 
Example #30
Source File: XMLDOMDocument.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Loads an XML document using the supplied string.
 * @param strXML the XML string to load into this XML document object;
 *     this string can contain an entire XML document or a well-formed fragment
 * @return {@code true} if the load succeeded; {@code false} if the load failed
 */
@JsxFunction
public boolean loadXML(final String strXML) {
    try {
        final WebWindow webWindow = getWindow().getWebWindow();

        final WebResponse webResponse = new StringWebResponse(strXML, webWindow.getEnclosedPage().getUrl());
        final XmlPage page = new XmlPage(webResponse, webWindow, false, false);
        setDomNode(page);

        preserveWhiteSpaceDuringLoad_ = preserveWhiteSpace_;
        url_ = "";
        return true;
    }
    catch (final IOException e) {
        final XMLDOMParseError parseError = getParseError();
        parseError.setErrorCode(-1);
        parseError.setFilepos(1);
        parseError.setLine(1);
        parseError.setLinepos(1);
        parseError.setReason(e.getMessage());
        parseError.setSrcText("xml");
        parseError.setUrl("");
        if (LOG.isDebugEnabled()) {
            LOG.debug("Error parsing XML\n" + strXML, e);
        }
        return false;
    }
}