Java Code Examples for com.gargoylesoftware.htmlunit.html.HtmlPage

The following examples show how to use com.gargoylesoftware.htmlunit.html.HtmlPage. These examples are extracted from open source projects. 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 Project: htmlunit   Source File: WebAssertTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if an error occurs
 */
@Test
public void assertTextPresent() throws Exception {
    final String html = "<html><body><div id='a'>bar</div></body></html>";
    final HtmlPage page = loadPage(html);

    WebAssert.assertTextPresent(page, "bar");

    boolean caught = false;
    try {
        WebAssert.assertTextPresent(page, "baz");
    }
    catch (final AssertionError e) {
        caught = true;
    }
    assertTrue(caught);
}
 
Example 2
Source Project: htmlunit   Source File: SvgFeMergeTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
@Alerts("[object SVGFEMergeElement]")
public void simpleScriptable() throws Exception {
    final String html = HtmlPageTest.STANDARDS_MODE_PREFIX_
        + "<html><head>\n"
        + "<script>\n"
        + "  function test() {\n"
        + "    alert(document.getElementById('myId'));\n"
        + "  }\n"
        + "</script>\n"
        + "</head><body onload='test()'>\n"
        + "  <svg xmlns='http://www.w3.org/2000/svg' version='1.1'>\n"
        + "    <feMerge id='myId'/>\n"
        + "  </svg>\n"
        + "</body></html>";

    final WebDriver driver = loadPageWithAlerts2(html);
    if (driver instanceof HtmlUnitDriver) {
        final HtmlPage page = (HtmlPage) getWebWindowOf((HtmlUnitDriver) driver).getEnclosedPage();
        assertTrue(SvgFeMerge.class.isInstance(page.getElementById("myId")));
    }
}
 
Example 3
Source Project: htmlunit   Source File: WebClientTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test tabbing to the next element.
 * @throws Exception if something goes wrong
 */
@Test
public void tabNext() throws Exception {
    final WebClient webClient = getWebClient();
    final List<String> collectedAlerts = new ArrayList<>();
    webClient.setAlertHandler(new CollectingAlertHandler(collectedAlerts));

    final HtmlPage page = getPageForKeyboardTest(webClient, new String[]{"1", "2", "3"});

    assertEquals("submit0", page.tabToNextElement().getAttribute("name"));
    assertEquals("submit1", page.tabToNextElement().getAttribute("name"));
    assertEquals("submit2", page.tabToNextElement().getAttribute("name"));

    final String[] expectedAlerts = {"focus-0", "blur-0", "focus-1", "blur-1", "focus-2"};
    assertEquals(expectedAlerts, collectedAlerts);
}
 
Example 4
Source Project: htmlunit   Source File: SimpleWebTestCase.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Defines the provided HTML as the response of the MockWebConnection for {@link WebTestCase#URL_FIRST}
 * and loads the page with this URL using the current browser version; finally, asserts the alerts
 * equal the expected alerts.
 * @param html the HTML to use
 * @param url the URL from which the provided HTML code should be delivered
 * @param waitForJS the milliseconds to wait for background JS tasks to complete. Ignored if -1.
 * @return the new page
 * @throws Exception if something goes wrong
 */
protected final HtmlPage loadPageWithAlerts(final String html, final URL url, final int waitForJS)
    throws Exception {
    if (getExpectedAlerts() == null) {
        throw new IllegalStateException("You must annotate the test class with '@RunWith(BrowserRunner.class)'");
    }

    // expand variables in expected alerts
    expandExpectedAlertsVariables(url);

    createTestPageForRealBrowserIfNeeded(html, getExpectedAlerts());

    final WebClient client = getWebClientWithMockWebConnection();
    final List<String> collectedAlerts = new ArrayList<>();
    client.setAlertHandler(new CollectingAlertHandler(collectedAlerts));

    final MockWebConnection webConnection = getMockWebConnection();
    webConnection.setResponse(url, html);

    final HtmlPage page = client.getPage(url);
    if (waitForJS > 0) {
        assertEquals(0, client.waitForBackgroundJavaScriptStartingBefore(waitForJS));
    }
    assertEquals(getExpectedAlerts(), collectedAlerts);
    return page;
}
 
Example 5
Source Project: htmlunit   Source File: HTMLDocumentWriteTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Verifies that calling document.write() after document parsing has finished results in a whole
 * new page being loaded.
 * @throws Exception if an error occurs
 */
@Test
public void write_WhenParsingFinished() throws Exception {
    final String html =
          "<html><head><script>\n"
        + "  function test() { document.write(1); document.write(2); document.close(); }\n"
        + "</script></head>\n"
        + "<body><span id='s' onclick='test()'>click</span></body></html>";

    HtmlPage page = loadPage(html);
    assertEquals("click", page.getBody().asText());

    final HtmlSpan span = page.getHtmlElementById("s");
    page = span.click();
    assertEquals("12", page.getBody().asText());
}
 
Example 6
Source Project: htmlunit   Source File: AbstractList.java    License: Apache License 2.0 6 votes vote down vote up
private void registerListener() {
    if (!listenerRegistered_) {
        final DomNode domNode = getDomNodeOrNull();
        if (domNode != null) {
            final DomHtmlAttributeChangeListenerImpl listener = new DomHtmlAttributeChangeListenerImpl(this);
            domNode.addDomChangeListener(listener);
            if (attributeChangeSensitive_) {
                if (domNode instanceof HtmlElement) {
                    ((HtmlElement) domNode).addHtmlAttributeChangeListener(listener);
                }
                else if (domNode instanceof HtmlPage) {
                    ((HtmlPage) domNode).addHtmlAttributeChangeListener(listener);
                }
            }
            listenerRegistered_ = true;
        }
    }
}
 
Example 7
Source Project: htmlunit   Source File: WebAssertTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if an error occurs
 */
@Test
public void assertElementNotPresent() throws Exception {
    final String html = "<html><body><div id='a'>bar</div></body></html>";
    final HtmlPage page = loadPage(html);

    WebAssert.assertElementNotPresent(page, "b");

    boolean caught = false;
    try {
        WebAssert.assertElementNotPresent(page, "a");
    }
    catch (final AssertionError e) {
        caught = true;
    }
    assertTrue(caught);
}
 
Example 8
Source Project: htmlunit   Source File: SvgFeGaussianBlurTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
@Alerts("[object SVGFEGaussianBlurElement]")
public void simpleScriptable() throws Exception {
    final String html = HtmlPageTest.STANDARDS_MODE_PREFIX_
        + "<html><head>\n"
        + "<script>\n"
        + "  function test() {\n"
        + "    alert(document.getElementById('myId'));\n"
        + "  }\n"
        + "</script>\n"
        + "</head><body onload='test()'>\n"
        + "  <svg xmlns='http://www.w3.org/2000/svg' version='1.1'>\n"
        + "    <feGaussianBlur id='myId'/>\n"
        + "  </svg>\n"
        + "</body></html>";

    final WebDriver driver = loadPageWithAlerts2(html);
    if (driver instanceof HtmlUnitDriver) {
        final HtmlPage page = (HtmlPage) getWebWindowOf((HtmlUnitDriver) driver).getEnclosedPage();
        assertTrue(SvgFeGaussianBlur.class.isInstance(page.getElementById("myId")));
    }
}
 
Example 9
Source Project: htmlunit   Source File: HTMLScriptElement.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the {@code src} property.
 * @return the {@code src} property
 */
@JsxGetter
public String getSrc() {
    final HtmlScript tmpScript = (HtmlScript) getDomNodeOrDie();
    String src = tmpScript.getSrcAttribute();
    if (ATTRIBUTE_NOT_DEFINED == src) {
        return src;
    }
    try {
        final URL expandedSrc = ((HtmlPage) tmpScript.getPage()).getFullyQualifiedUrl(src);
        src = expandedSrc.toString();
    }
    catch (final MalformedURLException e) {
        // ignore
    }
    return src;
}
 
Example 10
Source Project: HtmlUnit-Android   Source File: HTMLScriptElement.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the {@code src} property.
 * @return the {@code src} property
 */
@JsxGetter
public String getSrc() {
    final HtmlScript tmpScript = (HtmlScript) getDomNodeOrDie();
    String src = tmpScript.getSrcAttribute();
    if (ATTRIBUTE_NOT_DEFINED == src) {
        return src;
    }
    try {
        final URL expandedSrc = ((HtmlPage) tmpScript.getPage()).getFullyQualifiedUrl(src);
        src = expandedSrc.toString();
    }
    catch (final MalformedURLException e) {
        // ignore
    }
    return src;
}
 
Example 11
Source Project: htmlunit   Source File: SvgFontFaceNameTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
@Alerts("[object SVGElement]")
public void simpleScriptable() throws Exception {
    final String html = HtmlPageTest.STANDARDS_MODE_PREFIX_
        + "<html><head>\n"
        + "<script>\n"
        + "  function test() {\n"
        + "    alert(document.getElementById('myId'));\n"
        + "  }\n"
        + "</script>\n"
        + "</head><body onload='test()'>\n"
        + "  <svg xmlns='http://www.w3.org/2000/svg' version='1.1'>\n"
        + "    <font-face-name id='myId'/>\n"
        + "  </svg>\n"
        + "</body></html>";

    final WebDriver driver = loadPageWithAlerts2(html);
    if (driver instanceof HtmlUnitDriver) {
        final HtmlPage page = (HtmlPage) getWebWindowOf((HtmlUnitDriver) driver).getEnclosedPage();
        assertTrue(SvgElement.class.isInstance(page.getElementById("myId")));
    }
}
 
Example 12
Source Project: htmlunit   Source File: WebClient.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * <p><span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span></p>
 *
 * Opens a new dialog window.
 * @param url the URL of the document to load and display
 * @param opener the web window that is opening the dialog
 * @param dialogArguments the object to make available inside the dialog via <tt>window.dialogArguments</tt>
 * @return the new dialog window
 * @throws IOException if there is an IO error
 */
public DialogWindow openDialogWindow(final URL url, final WebWindow opener, final Object dialogArguments)
    throws IOException {

    WebAssert.notNull("url", url);
    WebAssert.notNull("opener", opener);

    final DialogWindow window = new DialogWindow(this, dialogArguments);
    fireWindowOpened(new WebWindowEvent(window, WebWindowEvent.OPEN, null, null));

    final HtmlPage openerPage = (HtmlPage) opener.getEnclosedPage();
    final WebRequest request = new WebRequest(url, getBrowserVersion().getHtmlAcceptHeader(),
                                                    getBrowserVersion().getAcceptEncodingHeader());
    request.setCharset(UTF_8);

    if (getBrowserVersion().hasFeature(DIALOGWINDOW_REFERER) && openerPage != null) {
        final String referer = openerPage.getUrl().toExternalForm();
        request.setAdditionalHeader(HttpHeader.REFERER, referer);
    }

    getPage(window, request);

    return window;
}
 
Example 13
Source Project: HtmlUnit-Android   Source File: HTMLTableRowElement.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Inserts a new cell at the specified index in the element's cells collection. If the index
 * is -1 or there is no index specified, then the cell is appended at the end of the
 * element's cells collection.
 * @see <a href="http://msdn.microsoft.com/en-us/library/ms536455.aspx">MSDN Documentation</a>
 * @param index specifies where to insert the cell in the tr.
 *        The default value is -1, which appends the new cell to the end of the cells collection
 * @return the newly-created cell
 */
@JsxFunction
public Object insertCell(final Object index) {
    int position = -1;
    if (index != Undefined.instance) {
        position = (int) Context.toNumber(index);
    }
    final HtmlTableRow htmlRow = (HtmlTableRow) getDomNodeOrDie();

    final boolean indexValid = position >= -1 && position <= htmlRow.getCells().size();
    if (indexValid) {
        final DomElement newCell = ((HtmlPage) htmlRow.getPage()).createElement("td");
        if (position == -1 || position == htmlRow.getCells().size()) {
            htmlRow.appendChild(newCell);
        }
        else {
            htmlRow.getCell(position).insertBefore(newCell);
        }
        return getScriptableFor(newCell);
    }
    throw Context.reportRuntimeError("Index or size is negative or greater than the allowed amount");
}
 
Example 14
Source Project: htmlunit   Source File: SgmlPageTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void getElementsByTagNameAsterisk() throws Exception {
    final String html
        = "<html><head><title>First</title></head>\n"
        + "<body>\n"
        + "<form><input type='button' name='button1' value='pushme'></form>\n"
        + "<div>a</div> <div>b</div> <div>c</div>\n"
        + "</body></html>";

    final HtmlPage page = loadPage(html);

    final DomNodeList<DomElement> elements = page.getElementsByTagName("*");

    assertEquals(9, elements.getLength());
    validateDomNodeList(elements);

    final HtmlDivision newDiv = new HtmlDivision(HtmlDivision.TAG_NAME, page, null);
    page.getBody().appendChild(newDiv);
    assertEquals(10, elements.getLength());
    validateDomNodeList(elements);
}
 
Example 15
Source Project: krazo   Source File: ConversationIT.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testConversation() throws Exception {
    HtmlPage page;
    Iterator<HtmlElement> it;

    page = webClient.getPage(webUrl + "resources/converse/start");
    it = page.getDocumentElement().getElementsByTagName("p").iterator();
    final String secret = it.next().asText();
    System.out.println(secret);

    page = webClient.getPage(webUrl + "resources/converse/" +
        page.getDocumentElement().getElementsByTagName("a")
            .iterator().next().getAttribute("href"));
    it = page.getDocumentElement().getElementsByTagName("p").iterator();
    assertTrue(secret.equals(it.next().asText()));

    page = webClient.getPage(webUrl + "resources/converse/stop");
    it = page.getDocumentElement().getElementsByTagName("p").iterator();
    assertFalse(secret.equals(it.next().asText()));
}
 
Example 16
Source Project: quarkus   Source File: CodeFlowDevModeTestCase.java    License: Apache License 2.0 6 votes vote down vote up
private void useTenantConfigResolver() throws IOException, InterruptedException {
    try (final WebClient webClient = createWebClient()) {
        HtmlPage page = webClient.getPage("http://localhost:8080/web-app/tenant/tenant-config-resolver");

        assertEquals("Log in to devmode", page.getTitleText());

        HtmlForm loginForm = page.getForms().get(0);

        loginForm.getInputByName("username").setValueAttribute("alice-dev-mode");
        loginForm.getInputByName("password").setValueAttribute("alice-dev-mode");

        page = loginForm.getInputByName("login").click();

        assertEquals("tenant-config-resolver:alice-dev-mode", page.getBody().asText());
        webClient.getCookieManager().clearCookies();
    }
}
 
Example 17
Source Project: htmlunit   Source File: HttpWebConnectionTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void cookiesEnabledAfterDisable() throws Exception {
    final Map<String, Class<? extends Servlet>> servlets = new HashMap<>();
    servlets.put("/test1", Cookie1Servlet.class);
    servlets.put("/test2", Cookie2Servlet.class);
    startWebServer("./", null, servlets);

    final WebClient client = getWebClient();

    client.getCookieManager().setCookiesEnabled(false);
    HtmlPage page = client.getPage(URL_FIRST + "test1");
    assertTrue(page.asText().contains("No Cookies"));

    client.getCookieManager().setCookiesEnabled(true);
    page = client.getPage(URL_FIRST + "test1");
    assertTrue(page.asText().contains("key1=value1"));
}
 
Example 18
Source Project: HtmlUnit-Android   Source File: HTMLDocument.java    License: Apache License 2.0 6 votes vote down vote up
private List<DomNode> getItComputeElements(final HtmlPage page, final String name,
        final boolean forIDAndOrName, final boolean alsoFrames) {
    final List<DomElement> elements;
    if (forIDAndOrName) {
        elements = page.getElementsByIdAndOrName(name);
    }
    else {
        elements = page.getElementsByName(name);
    }
    final List<DomNode> matchingElements = new ArrayList<>();
    for (final DomElement elt : elements) {
        if (elt instanceof HtmlForm || elt instanceof HtmlImage
                || (alsoFrames && elt instanceof BaseFrameElement)) {
            matchingElements.add(elt);
        }
    }
    return matchingElements;
}
 
Example 19
Source Project: htmlunit   Source File: JavaScriptEngine.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Handles an exception that occurred during execution of JavaScript code.
 * @param page the page in which the script causing this exception was executed
 * @param e the timeout error that was thrown from the script engine
 */
protected void handleJavaScriptTimeoutError(final HtmlPage page, final TimeoutError e) {
    final WebClient webClient = getWebClient();
    // shutdown was already called
    if (webClient == null) {
        if (LOG.isInfoEnabled()) {
            LOG.info("Caught script timeout error after the shutdown of the Javascript engine - ignored.");
        }
        return;
    }

    webClient.getJavaScriptErrorListener().timeoutError(page, e.getAllowedTime(), e.getExecutionTime());
    if (webClient.getOptions().isThrowExceptionOnScriptError()) {
        throw new RuntimeException(e);
    }
    LOG.info("Caught script timeout error", e);
}
 
Example 20
Source Project: htmlunit   Source File: WebClientTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test pressing an accesskey.
 * @throws Exception if something goes wrong
 */
@Test
public void accessKeys() throws Exception {
    final WebClient webClient = getWebClient();
    final List<String> collectedAlerts = new ArrayList<>();
    webClient.setAlertHandler(new CollectingAlertHandler(collectedAlerts));

    final HtmlPage page = getPageForKeyboardTest(webClient, new String[]{"1", "2", "3"});

    assertEquals("submit0", page.pressAccessKey('a').getAttribute("name"));
    assertEquals("submit2", page.pressAccessKey('c').getAttribute("name"));
    assertEquals("submit1", page.pressAccessKey('b').getAttribute("name"));

    final String[] expectedAlerts = {"focus-0", "blur-0", "focus-2", "blur-2", "focus-1"};
    assertEquals(expectedAlerts, collectedAlerts);
}
 
Example 21
@Test
public void requestAuthorizationCodeGrantWhenInvalidRedirectUriThenDisplayLoginPageWithError() throws Exception {
	HtmlPage page = this.webClient.getPage("/");
	URL loginPageUrl = page.getBaseURL();
	URL loginErrorPageUrl = new URL(loginPageUrl.toString() + "?error");

	ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId("google");

	HtmlAnchor clientAnchorElement = this.getClientAnchorElement(page, clientRegistration);
	assertThat(clientAnchorElement).isNotNull();

	WebResponse response = this.followLinkDisableRedirects(clientAnchorElement);

	UriComponents authorizeRequestUriComponents = UriComponentsBuilder.fromUri(
		URI.create(response.getResponseHeaderValue("Location"))).build();

	Map<String, String> params = authorizeRequestUriComponents.getQueryParams().toSingleValueMap();
	String code = "auth-code";
	String state = URLDecoder.decode(params.get(OAuth2ParameterNames.STATE), "UTF-8");
	String redirectUri = URLDecoder.decode(params.get(OAuth2ParameterNames.REDIRECT_URI), "UTF-8");
	redirectUri += "-invalid";

	String authorizationResponseUri =
		UriComponentsBuilder.fromHttpUrl(redirectUri)
			.queryParam(OAuth2ParameterNames.CODE, code)
			.queryParam(OAuth2ParameterNames.STATE, state)
			.build().encode().toUriString();

	page = this.webClient.getPage(new URL(authorizationResponseUri));
	assertThat(page.getBaseURL()).isEqualTo(loginErrorPageUrl);

	HtmlElement errorElement = page.getBody().getFirstByXPath("p");
	assertThat(errorElement).isNotNull();
	assertThat(errorElement.asText()).contains("invalid_redirect_uri_parameter");
}
 
Example 22
Source Project: htmlunit   Source File: HtmlUnitXPathTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Test evaluation of some simple paths.
 * @throws Exception if test fails
 */
@Test
public void simplePath() throws Exception {
    final String content = "<html><head><title>Test page</title></head>\n"
        + "<body><a href='foo.html' id='myLink'>foo</a></body>\n"
        + "</html>";

    final HtmlPage page = loadPage(content);
    assertEquals(page.getDocumentElement(), page.getFirstByXPath("/html"));
    assertEquals(page.getDocumentElement().getFirstChild(), page.getFirstByXPath("/html/head"));
    assertEquals(page.getHtmlElementById("myLink"), page.getFirstByXPath("/html/body/a"));
    assertEquals("Test page", ((DomText) page.getFirstByXPath("/html/head/title/text()")).getNodeValue());
}
 
Example 23
Source Project: MyTv   Source File: TvMaoCrawler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public HtmlPage makeObject(TvMaoObjectKey key) throws Exception {
	Page page = WebCrawler.crawl(key.url);
	if (page.isHtmlPage()) {
		return (HtmlPage) page;
	}
	throw new MyTvException("invalid web page which url: " + key.url);
}
 
Example 24
Source Project: tomee   Source File: MoviesArquillianHtmlUnitTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testShouldMakeSureWebappIsWorking() throws Exception {
    final String url = "http://" + deploymentUrl.getHost() + ":" + deploymentUrl.getPort() + "/moviefun";

    WebClient webClient = new WebClient();
    HtmlPage page = webClient.getPage(url + "/setup.jsp");

    assertMoviesPresent(page);

    page = webClient.getPage(url + "/moviefun");

    assertMoviesPresent(page);
    webClient.closeAllWindows();
}
 
Example 25
/**
 * @throws Exception if the test fails
 */
@Test
public void dontWaitWhenUnnecessary() throws Exception {
    final String content = "<html>\n"
        + "<head>\n"
        + "  <title>test</title>\n"
        + "  <script>\n"
        + "    var threadID;\n"
        + "    function test() {\n"
        + "      threadID = setTimeout(doAlert, 10000);\n"
        + "    }\n"
        + "    function doAlert() {\n"
        + "      alert('blah');\n"
        + "    }\n"
        + "  </script>\n"
        + "</head>\n"
        + "<body onload='test()'>\n"
        + "</body>\n"
        + "</html>";

    final List<String> collectedAlerts = Collections.synchronizedList(new ArrayList<String>());
    final HtmlPage page = loadPage(content, collectedAlerts);
    final JavaScriptJobManager jobManager = page.getEnclosingWindow().getJobManager();
    assertNotNull(jobManager);
    assertEquals(1, jobManager.getJobCount());

    startTimedTest();
    assertEquals(1, page.getWebClient().waitForBackgroundJavaScriptStartingBefore(7000));
    assertMaxTestRunTime(100);
    assertEquals(1, jobManager.getJobCount());
    assertEquals(Collections.EMPTY_LIST, collectedAlerts);
}
 
Example 26
public void assertNoMoreEquivalenceDuels(int gameId)
		throws FailingHttpStatusCodeException, MalformedURLException, IOException {
	HtmlPage playPage = browser.getPage("http://localhost:8080" + Paths.BATTLEGROUND_GAME + "?gameId=" + gameId);
	for (HtmlAnchor a : playPage.getAnchors()) {
		if (a.getHrefAttribute().contains(Paths.BATTLEGROUND_GAME + "?acceptEquivalent=")) {
			Assert.fail("On game " + gameId + " there is still an equivalence duel open");
		}
	}
}
 
Example 27
Source Project: HtmlUnit-Android   Source File: HtmlUnitContextFactory.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Pre process the specified source code in the context of the given page using the processor specified
 * in the webclient. This method delegates to the pre processor handler specified in the
 * <code>WebClient</code>. If no pre processor handler is defined, the original source code is returned
 * unchanged.
 * @param htmlPage the page
 * @param sourceCode the code to process
 * @param sourceName a name for the chunk of code (used in error messages)
 * @param lineNumber the line number of the source code
 * @param htmlElement the HTML element that will act as the context
 * @return the source code after being pre processed
 * @see com.gargoylesoftware.htmlunit.ScriptPreProcessor
 */
protected String preProcess(
    final HtmlPage htmlPage, final String sourceCode, final String sourceName, final int lineNumber,
    final HtmlElement htmlElement) {

    String newSourceCode = sourceCode;
    final ScriptPreProcessor preProcessor = webClient_.getScriptPreProcessor();
    if (preProcessor != null) {
        newSourceCode = preProcessor.preProcess(htmlPage, sourceCode, sourceName, lineNumber, htmlElement);
        if (newSourceCode == null) {
            newSourceCode = "";
        }
    }
    return newSourceCode;
}
 
Example 28
Source Project: htmlunit   Source File: WindowTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void status() throws Exception {
    final WebClient webClient = getWebClient();
    final MockWebConnection webConnection = new MockWebConnection();

    final String firstContent
        = "<html><head><title>First</title><script>\n"
        + "function doTest() {\n"
        + "  alert(window.status);\n"
        + "  window.status = 'newStatus';\n"
        + "  alert(window.status);\n"
        + "}\n"
        + "</script></head><body onload='doTest()'>\n"
        + "</body></html>";

    final URL url = URL_FIRST;
    webConnection.setResponse(url, firstContent);
    webClient.setWebConnection(webConnection);

    final List<String> collectedAlerts = new ArrayList<>();
    webClient.setAlertHandler(new CollectingAlertHandler(collectedAlerts));

    final List<String> collectedStatus = new ArrayList<>();
    webClient.setStatusHandler(new StatusHandler() {
        @Override
        public void statusMessageChanged(final Page page, final String message) {
            collectedStatus.add(message);
        }
    });
    final HtmlPage firstPage = webClient.getPage(URL_FIRST);
    assertEquals("First", firstPage.getTitleText());

    final String[] expectedAlerts = {"", "newStatus"};
    assertEquals("alerts", expectedAlerts, collectedAlerts);

    final String[] expectedStatus = {"newStatus"};
    assertEquals("status", expectedStatus, collectedStatus);
}
 
Example 29
Source Project: htmlunit   Source File: HtmlUnitNekoHtmlParser.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Adds a body element to the current page, if necessary. Strictly speaking, this should
 * probably be done by NekoHTML. See the bug linked below. If and when that bug is fixed,
 * we may be able to get rid of this code.
 *
 * http://sourceforge.net/p/nekohtml/bugs/15/
 * @param page
 * @param originalCall
 * @param checkInsideFrameOnly true if the original page had body that was removed by JavaScript
 */
private void addBodyToPageIfNecessary(
        final HtmlPage page, final boolean originalCall, final boolean checkInsideFrameOnly) {
    // IE waits for the whole page to load before initializing bodies for frames.
    final boolean waitToLoad = page.hasFeature(PAGE_WAIT_LOAD_BEFORE_BODY);
    if (page.getEnclosingWindow() instanceof FrameWindow && originalCall && waitToLoad) {
        return;
    }

    // Find out if the document already has a body element (or frameset).
    final Element doc = page.getDocumentElement();
    boolean hasBody = false;
    for (Node child = doc.getFirstChild(); child != null; child = child.getNextSibling()) {
        if (child instanceof HtmlBody || child instanceof HtmlFrameSet) {
            hasBody = true;
            break;
        }
    }

    // If the document does not have a body, add it.
    if (!hasBody && !checkInsideFrameOnly) {
        final DomElement body = getFactory("body").createElement(page, "body", null);
        doc.appendChild(body);
    }

    // If this is IE, we need to initialize the bodies of any frames, as well.
    // This will already have been done when emulating FF (see above).
    if (waitToLoad) {
        for (final FrameWindow frame : page.getFrames()) {
            final Page containedPage = frame.getEnclosedPage();
            if (containedPage != null && containedPage.isHtmlPage()) {
                addBodyToPageIfNecessary((HtmlPage) containedPage, false, false);
            }
        }
    }
}
 
Example 30
Source Project: superword   Source File: SentenceExtractor.java    License: Apache License 2.0 5 votes vote down vote up
public static String getContent2(String url) {
    try{
        LOGGER.debug("url:"+url);
        HtmlPage htmlPage = WEB_CLIENT.getPage(url);
        String html = htmlPage.asXml();
        //LOGGER.debug("html:"+html);
        return html;
    }catch (Exception e) {
        e.printStackTrace();
        LOGGER.error("获取URL:"+url+"页面出错", e);
    }
    return "";
}