io.reactivex.MaybeOnSubscribe#com.gargoylesoftware.htmlunit.html.HtmlPage源码实例Demo

下面列出了io.reactivex.MaybeOnSubscribe#com.gargoylesoftware.htmlunit.html.HtmlPage 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: htmlunit   文件: WebAssertTest.java
/**
 * @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);
}
 
源代码2 项目: htmlunit   文件: SvgFeMergeTest.java
/**
 * @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")));
    }
}
 
源代码3 项目: htmlunit   文件: WebClientTest.java
/**
 * 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);
}
 
源代码4 项目: htmlunit   文件: SimpleWebTestCase.java
/**
 * 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;
}
 
源代码5 项目: htmlunit   文件: HTMLDocumentWriteTest.java
/**
 * 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());
}
 
源代码6 项目: htmlunit   文件: AbstractList.java
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;
        }
    }
}
 
源代码7 项目: htmlunit   文件: WebAssertTest.java
/**
 * @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);
}
 
源代码8 项目: htmlunit   文件: SvgFeGaussianBlurTest.java
/**
 * @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")));
    }
}
 
源代码9 项目: htmlunit   文件: HTMLScriptElement.java
/**
 * 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;
}
 
源代码10 项目: HtmlUnit-Android   文件: HTMLScriptElement.java
/**
 * 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;
}
 
源代码11 项目: htmlunit   文件: SvgFontFaceNameTest.java
/**
 * @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")));
    }
}
 
源代码12 项目: htmlunit   文件: WebClient.java
/**
 * <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;
}
 
源代码13 项目: HtmlUnit-Android   文件: HTMLTableRowElement.java
/**
 * 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");
}
 
源代码14 项目: htmlunit   文件: SgmlPageTest.java
/**
 * @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);
}
 
源代码15 项目: krazo   文件: ConversationIT.java
@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()));
}
 
源代码16 项目: quarkus   文件: CodeFlowDevModeTestCase.java
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();
    }
}
 
源代码17 项目: htmlunit   文件: HttpWebConnectionTest.java
/**
 * @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"));
}
 
源代码18 项目: HtmlUnit-Android   文件: HTMLDocument.java
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;
}
 
源代码19 项目: htmlunit   文件: JavaScriptEngine.java
/**
 * 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);
}
 
源代码20 项目: htmlunit   文件: WebClientTest.java
/**
 * 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);
}
 
@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");
}
 
源代码22 项目: htmlunit   文件: HtmlUnitXPathTest.java
/**
 * 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());
}
 
源代码23 项目: MyTv   文件: TvMaoCrawler.java
@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);
}
 
源代码24 项目: tomee   文件: MoviesArquillianHtmlUnitTest.java
@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();
}
 
/**
 * @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);
}
 
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");
		}
	}
}
 
源代码27 项目: HtmlUnit-Android   文件: HtmlUnitContextFactory.java
/**
 * 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;
}
 
源代码28 项目: htmlunit   文件: WindowTest.java
/**
 * @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);
}
 
源代码29 项目: htmlunit   文件: HtmlUnitNekoHtmlParser.java
/**
 * 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);
            }
        }
    }
}
 
源代码30 项目: superword   文件: SentenceExtractor.java
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 "";
}