com.gargoylesoftware.htmlunit.Page Java Examples

The following examples show how to use com.gargoylesoftware.htmlunit.Page. 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: HiddenHtmlAlert.java    From ats-framework with Apache License 2.0 6 votes vote down vote up
@Override
@PublicAtsApi
public void clickOk(
                     final String expectedAlertText ) {

    isProcessed = false;
    webClient.setAlertHandler(new AlertHandler() {

        @Override
        public void handleAlert(
                                 Page alertPage,
                                 String alertText ) {

            isProcessed = true;
            if (!alertText.equals(expectedAlertText)) {

                throw new VerificationException("The expected alert message was: '" + expectedAlertText
                                                + "', but actually it is: '" + alertText + "'");
            }
        }
    });
}
 
Example #2
Source File: HtmlAnchor.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
@SuppressWarnings("unchecked")
public <P extends Page> P click(final Event event, final boolean ignoreVisibility) throws IOException {
    final boolean ctrl = event.isCtrlKey();
    WebWindow oldWebWindow = null;
    if (ctrl) {
        oldWebWindow = ((HTMLElement) event.getSrcElement()).getDomNodeOrDie()
                .getPage().getWebClient().getCurrentWindow();
    }

    P page = super.click(event, ignoreVisibility);

    if (ctrl) {
        page.getEnclosingWindow().getWebClient().setCurrentWindow(oldWebWindow);
        page = (P) oldWebWindow.getEnclosedPage();
    }

    return page;
}
 
Example #3
Source File: HiddenHtmlConfirm.java    From ats-framework with Apache License 2.0 6 votes vote down vote up
@Override
@PublicAtsApi
public void clickCancel() {

    isProcessed = false;
    webClient.setConfirmHandler(new ConfirmHandler() {

        @Override
        public boolean handleConfirm(
                                      Page currentPage,
                                      String confirmationText ) {

            isProcessed = true;
            return false;
        }
    });
}
 
Example #4
Source File: FrameWindow.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void setEnclosedPage(final Page page) {
    setPageDenied(PageDenied.NONE);
    super.setEnclosedPage(page);

    // we have updated a frame window by javascript write();
    // so we have to disable future updates during initialization
    // see com.gargoylesoftware.htmlunit.html.HtmlPage.loadFrames()
    final WebResponse webResponse = page.getWebResponse();
    if (webResponse instanceof StringWebResponse) {
        final StringWebResponse response = (StringWebResponse) webResponse;
        if (response.isFromJavascript()) {
            final BaseFrameElement frame = getFrameElement();
            frame.setContentLoaded();
        }
    }
}
 
Example #5
Source File: HtmlPage.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Simulate pressing an access key. This may change the focus, may click buttons and may invoke
 * JavaScript.
 *
 * @param accessKey the key that will be pressed
 * @return the element that has the focus after pressing this access key or null if no element
 * has the focus.
 * @throws IOException if an IO error occurs during the processing of this access key (this
 *         would only happen if the access key triggered a button which in turn caused a page load)
 */
public DomElement pressAccessKey(final char accessKey) throws IOException {
    final HtmlElement element = getHtmlElementByAccessKey(accessKey);
    if (element != null) {
        element.focus();
        final Page newPage;
        if (element instanceof HtmlAnchor || element instanceof HtmlArea || element instanceof HtmlButton
                || element instanceof HtmlInput || element instanceof HtmlLabel || element instanceof HtmlLegend
                || element instanceof HtmlTextArea || element instanceof HtmlArea) {
            newPage = element.click();
        }
        else {
            newPage = this;
        }

        if (newPage != this && getFocusedElement() == element) {
            // The page was reloaded therefore no element on this page will have the focus.
            getFocusedElement().blur();
        }
    }

    return getFocusedElement();
}
 
Example #6
Source File: HTMLAnchorElementTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void onClickAnchorHref() throws Exception {
    final String html
        = "<html><body>\n"
        + "<a href='#' onclick='document.form1.submit()'>link 1</a>\n"
        + "<form name='form1' action='foo.html' method='post'>\n"
        + "<input name='testText'>\n"
        + "</form>\n"
        + "</body></html>";

    getMockWebConnection().setDefaultResponse("");
    final HtmlPage page1 = loadPageWithAlerts(html);
    final Page page2 = page1.getAnchorByHref("#").click();

    assertEquals(URL_FIRST + "foo.html", page2.getUrl());
}
 
Example #7
Source File: HtmlSelect.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
 *
 * Sets the "selected" state of the specified option. If this "select" element
 * is single-select, then calling this method will deselect all other options.
 *
 * Only options that are actually in the document may be selected.
 *
 * @param isSelected true if the option is to become selected
 * @param optionValue the value of the option that is to change
 * @param invokeOnFocus whether to set focus or not.
 * @param <P> the page type
 * @return the page contained in the current window as returned
 * by {@link com.gargoylesoftware.htmlunit.WebClient#getCurrentWindow()}
 */
@SuppressWarnings("unchecked")
public <P extends Page> P setSelectedAttribute(final String optionValue,
        final boolean isSelected, final boolean invokeOnFocus) {
    try {
        final boolean attributeOnly = hasFeature(JS_SELECT_SET_VALUES_CHECKS_ONLY_VALUE_ATTRIBUTE)
                && !optionValue.isEmpty();
        final HtmlOption selected;
        if (attributeOnly) {
            selected = getOptionByValueStrict(optionValue);
        }
        else {
            selected = getOptionByValue(optionValue);
        }
        return setSelectedAttribute(selected, isSelected, invokeOnFocus, true, false, true);
    }
    catch (final ElementNotFoundException e) {
        for (final HtmlOption o : getSelectedOptions()) {
            o.setSelected(false);
        }
        return (P) getPage();
    }
}
 
Example #8
Source File: HtmlLabel.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Clicks the label and propagates to the referenced element.
 * {@inheritDoc}
 */
@Override
public <P extends Page> P click(final Event event,
        final boolean shiftKey, final boolean ctrlKey, final boolean altKey,
        final boolean ignoreVisibility) throws IOException {
    // first the click on the label
    final P page = super.click(event, shiftKey, ctrlKey, altKey, ignoreVisibility);

    // then the click on the referenced element
    final HtmlElement element = getLabeledElement();
    if (element == null || element.isDisabledElementAndDisabled()) {
        return page;
    }

    // not sure which page we should return
    return element.click(false, false, false, false, true, true);
}
 
Example #9
Source File: HiddenHtmlPrompt.java    From ats-framework with Apache License 2.0 6 votes vote down vote up
@Override
@PublicAtsApi
public void clickCancel() {

    isProcessed = false;
    webClient.setPromptHandler(new PromptHandler() {

        @Override
        public String handlePrompt(
                                    Page currentPage,
                                    String promptText,
                                    String defaultValue ) {

            isProcessed = true;
            return null;
        }
    });
}
 
Example #10
Source File: HTMLFormElement2Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * In action "this" should be the window and not the form.
 * @throws Exception if the test fails
 */
@Test
@Alerts("true")
public void thisInJavascriptAction() throws Exception {
    final String content
        = "<html>\n"
        + "<body>\n"
        + "<form action='javascript:alert(this == window)'>\n"
        + "<input type='submit' id='theButton'>\n"
        + "</form>\n"
        + "</body></html>";

    final List<String> collectedAlerts = new ArrayList<>();
    final HtmlPage page1 = loadPage(content, collectedAlerts);
    final Page page2 = page1.getHtmlElementById("theButton").click();

    assertEquals(getExpectedAlerts(), collectedAlerts);
    assertSame(page1, page2);
}
 
Example #11
Source File: JSObject.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Evaluates a JavaScript expression.
 * The expression is a string of JavaScript source code which will be evaluated in the context given by "this".
 *
 * @param expression the JavaScript expression
 * @return result Object
 * @throws JSException in case or error
 */
public Object eval(final String expression) throws JSException {
    if (LOG.isInfoEnabled()) {
        LOG.info("JSObject eval '" + expression + "'");
    }

    final Page page = Window_.getWebWindow().getEnclosedPage();
    if (page instanceof HtmlPage) {
        final HtmlPage htmlPage = (HtmlPage) page;
        final ScriptResult result = htmlPage.executeJavaScript(expression);
        final Object jsResult = result.getJavaScriptResult();
        if (jsResult instanceof ScriptableObject) {
            return new JSObject((ScriptableObject) jsResult);
        }
        if (jsResult instanceof ConsString) {
            return ((ConsString) jsResult).toString();
        }
        return jsResult;
    }
    return null;
}
 
Example #12
Source File: DelegatingWebConnectionTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void verifyExampleInClassLevelJavadoc() throws Exception {
	Assume.group(TestGroup.PERFORMANCE);

	WebClient webClient = new WebClient();

	MockMvc mockMvc = MockMvcBuilders.standaloneSetup().build();
	MockMvcWebConnection mockConnection = new MockMvcWebConnection(mockMvc, webClient);

	WebRequestMatcher cdnMatcher = new UrlRegexRequestMatcher(".*?//code.jquery.com/.*");
	WebConnection httpConnection = new HttpWebConnection(webClient);
	webClient.setWebConnection(
			new DelegatingWebConnection(mockConnection, new DelegateWebConnection(cdnMatcher, httpConnection)));

	Page page = webClient.getPage("http://code.jquery.com/jquery-1.11.0.min.js");
	assertThat(page.getWebResponse().getStatusCode(), equalTo(200));
	assertThat(page.getWebResponse().getContentAsString(), not(isEmptyString()));
}
 
Example #13
Source File: FrameWindow.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void setEnclosedPage(final Page page) {
    super.setEnclosedPage(page);

    // we have updated a frame window by javascript write();
    // so we have to disable future updates during initialization
    // see com.gargoylesoftware.htmlunit.html.HtmlPage.loadFrames()
    final WebResponse webResponse = page.getWebResponse();
    if (webResponse instanceof StringWebResponse) {
        final StringWebResponse response = (StringWebResponse) webResponse;
        if (response.isFromJavascript()) {
            final BaseFrameElement frame = getFrameElement();
            frame.setContentLoaded();
        }
    }
}
 
Example #14
Source File: HtmlAreaTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * In action "this" should be the window and not the area.
 * @throws Exception if the test fails
 */
@Test
@Alerts("true")
@BuggyWebDriver(FF = "Todo", FF68 = "Todo", FF60 = "Todo")
public void thisInJavascriptHref() throws Exception {
    try (InputStream is = getClass().getClassLoader().getResourceAsStream("testfiles/tiny-jpg.img")) {
        final byte[] directBytes = IOUtils.toByteArray(is);
        final URL urlImage = new URL(URL_FIRST, "img.jpg");
        final List<NameValuePair> emptyList = Collections.emptyList();
        getMockWebConnection().setResponse(urlImage, directBytes, 200, "ok", "image/jpg", emptyList);
    }

    final String html
        = "<html><head><title>foo</title></head><body>\n"
        + "<img src='img.jpg' width='145' height='126' usemap='#somename'>\n"
        + "<map name='somename'>\n"
        + "  <area href='javascript:alert(this == window)' id='a2' shape='rect' coords='0,0,30,30'/>\n"
        + "</map></body></html>";

    final WebDriver driver = loadPage2(html);
    final Page page;
    if (driver instanceof HtmlUnitDriver) {
        page = getWebWindowOf((HtmlUnitDriver) driver).getEnclosedPage();
    }
    else {
        page = null;
    }

    verifyAlerts(driver);

    driver.findElement(By.id("a2")).click();

    verifyAlerts(driver, getExpectedAlerts());
    if (driver instanceof HtmlUnitDriver) {
        final Page secondPage = getWebWindowOf((HtmlUnitDriver) driver).getEnclosedPage();
        assertSame(page, secondPage);
    }
}
 
Example #15
Source File: ExceptionMapperIT.java    From krazo with Apache License 2.0 5 votes vote down vote up
@Test
public void testHandledByMvcViewMapper() throws IOException {

    Page page = webClient.getPage(baseURL.toString() + "mvc/mappers/fail-mvc-view");
    WebResponse webResponse = page.getWebResponse();

    assertThat(webResponse.getStatusCode(), equalTo(492));
    assertThat(webResponse.getContentType(), startsWith("text/html"));
    assertThat(webResponse.getContentAsString(),
        containsString("<h1>Exception caught: Error thrown by controller</h1>"));

}
 
Example #16
Source File: HtmlPage.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Deregister frames that are no longer in use.
 */
public void deregisterFramesIfNeeded() {
    for (final WebWindow window : getFrames()) {
        getWebClient().deregisterWebWindow(window);
        final Page page = window.getEnclosedPage();
        if (page != null && page.isHtmlPage()) {
            // seems quite silly, but for instance if the src attribute of an iframe is not
            // set, the error only occurs when leaving the page
            ((HtmlPage) page).deregisterFramesIfNeeded();
        }
    }
}
 
Example #17
Source File: HtmlImageTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
private void useMapClick(final int x, final int y, final String urlSuffix) throws Exception {
    final URL urlImage = new URL(URL_FIRST, "img.jpg");
    try (InputStream is = getClass().getClassLoader().getResourceAsStream("testfiles/tiny-jpg.img")) {
        final byte[] directBytes = IOUtils.toByteArray(is);
        final List<NameValuePair> emptyList = Collections.emptyList();
        getMockWebConnection().setResponse(urlImage, directBytes, 200, "ok", "image/jpg", emptyList);
    }

    final String htmlContent
        = "<html>\n"
        + "<head><title>foo</title></head>\n"
        + "<body>\n"
        + "  <img id='myImg' src='" + urlImage + "' usemap='#map1'>\n"
        + "  <map name='map1'>\n"
        + "    <area href='a.html' shape='rect' coords='5,5,20,20'>\n"
        + "    <area href='b.html' shape='circle' coords='25,10,10'>\n"
        + "  </map>\n"
        + "</body></html>";
    final HtmlPage page = loadPage(htmlContent);

    final HtmlImage img = page.getHtmlElementById("myImg");

    final Page page2 = img.click(x, y);
    final URL url = page2.getUrl();
    assertTrue(url.toExternalForm(), url.toExternalForm().endsWith(urlSuffix));
}
 
Example #18
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 #19
Source File: HTMLParser.java    From HtmlUnit-Android with 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 static 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 HtmlBody body = new HtmlBody("body", page, null, false);
        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 #20
Source File: ExceptionMapperIT.java    From krazo with Apache License 2.0 5 votes vote down vote up
@Test
public void testHandledByPlainTextMapper() throws IOException {

    Page page = webClient.getPage(baseURL.toString() + "mvc/mappers/fail-plain-text");
    WebResponse webResponse = page.getWebResponse();

    assertThat(webResponse.getStatusCode(), equalTo(491));
    assertThat(webResponse.getContentType(), startsWith("text/plain"));
    assertThat(webResponse.getContentAsString(),
        equalTo("Exception caught: Error thrown by controller"));

}
 
Example #21
Source File: TestReportUiTest.java    From junit-plugin with MIT License 5 votes vote down vote up
/**
 * Validate CSS styles present to prevent duration text from wrapping
 */
@Issue("JENKINS-24352")
@Test
public void testDurationStyle() throws Exception {
    AbstractBuild b = configureTestBuild("render-test");

    JenkinsRule.WebClient wc = j.createWebClient();

    wc.setAlertHandler(new AlertHandler() {
        @Override
        public void handleAlert(Page page, String message) {
            throw new AssertionError();
        }
    });

    HtmlPage pg = wc.getPage(b, "testReport");

    // these are from the test result file:
    String duration14sec = Util.getTimeSpanString((long) (14.398 * 1000));
    String duration3_3sec = Util.getTimeSpanString((long) (3.377 * 1000));
    String duration2_5sec = Util.getTimeSpanString((long) (2.502 * 1000));

    Assert.assertNotNull(pg.getFirstByXPath("//td[contains(text(),'" + duration3_3sec + "')][contains(@class,'no-wrap')]"));

    pg = wc.getPage(b, "testReport/org.twia.vendor");

    Assert.assertNotNull(pg.getFirstByXPath("//td[contains(text(),'" + duration3_3sec + "')][contains(@class,'no-wrap')]"));
    Assert.assertNotNull(pg.getFirstByXPath("//td[contains(text(),'" + duration14sec + "')][contains(@class,'no-wrap')]"));

    pg = wc.getPage(b, "testReport/org.twia.vendor/VendorManagerTest");

    Assert.assertNotNull(pg.getFirstByXPath("//td[contains(text(),'" + duration2_5sec + "')][contains(@class,'no-wrap')]"));
}
 
Example #22
Source File: DockerTraceabilityRootActionTest.java    From docker-traceability-plugin with MIT License 5 votes vote down vote up
@Test
public void rawContainerDockerInspectSubmissions() throws Exception {
    
    // Read data from resources
    String inspectData = JSONSamples.inspectContainerData.readString();
    InspectContainerResponse inspectResponse = JSONSamples.inspectContainerData.
            readObject(InspectContainerResponse[].class)[0];
    final String containerId = inspectResponse.getId();
    final String imageId = inspectResponse.getImageId();
    
    // Init system data
    JenkinsRule.WebClient client = j.createWebClient();
    final DockerTraceabilityRootAction action = DockerTraceabilityRootAction.getInstance();
    assertNotNull(action);
         
    // Prepare a run with Fingerprints and referenced facets
    createTestBuildRefFacet(imageId, "test");
    
    // Submit JSON
    action.doSubmitContainerStatus(inspectData, null, null, null, 0, null, null);
    
    // Ensure there's a fingerprint for container, which refers the image
    final DockerDeploymentFacet containerFacet = assertExistsDeploymentFacet(containerId, imageId);
    
    // Ensure there's a fingerprint for image
    final DockerDeploymentRefFacet containerRefFacet = assertExistsDeploymentRefFacet(containerId, imageId);
    
    // Try to call the actions method to retrieve the data
    final Page res;
    try {
        res = client.goTo("docker-traceability/rawContainerInfo?id="+containerId, null);
    } catch (Exception ex) {
        ex.getMessage();
        throw new AssertionError("Cannot get a response from rawInfo page", ex);
    }
    final String responseJSON = res.getWebResponse().getContentAsString();
    ObjectMapper mapper= new ObjectMapper();
    final InspectContainerResponse[] parsedData = mapper.readValue(responseJSON, InspectContainerResponse[].class);
    assertEquals(1, parsedData.length);       
}
 
Example #23
Source File: MockMvcWebConnectionTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void contextPathEmpty() throws IOException {
	this.webClient.setWebConnection(new MockMvcWebConnection(this.mockMvc, ""));

	Page page = this.webClient.getPage("http://localhost/context/a");

	assertThat(page.getWebResponse().getStatusCode(), equalTo(200));
}
 
Example #24
Source File: JenkinsRuleTest.java    From jenkins-test-harness with MIT License 5 votes vote down vote up
private void makeRequestAndAssertLogin(JenkinsRule.WebClient wc, String expectedLogin) throws IOException, SAXException {
    WebRequest req = new WebRequest(new URL(j.getURL(),"whoAmI/api/json"));
    Page p = wc.getPage(req);
    String pageContent = p.getWebResponse().getContentAsString();
    String loginReceived = (String) JSONObject.fromObject(pageContent).get("name");
    assertEquals(expectedLogin, loginReceived.trim());
}
 
Example #25
Source File: XmlSerializer.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
private Map<String, DomAttr> getAttributesFor(final BaseFrameElement frame) throws IOException {
    final Map<String, DomAttr> map = createAttributesCopyWithClonedAttribute(frame, "src");
    final DomAttr srcAttr = map.get("src");
    if (srcAttr == null) {
        return map;
    }

    final Page enclosedPage = frame.getEnclosedPage();
    final String suffix = getFileExtension(enclosedPage);
    final File file = createFile(srcAttr.getValue(), "." + suffix);

    if (enclosedPage != null) {
        if (enclosedPage.isHtmlPage()) {
            file.delete(); // TODO: refactor as it is stupid to create empty file at one place
            // and then to complain that it already exists
            ((HtmlPage) enclosedPage).save(file);
        }
        else {
            try (InputStream is = enclosedPage.getWebResponse().getContentAsStream()) {
                try (FileOutputStream fos = new FileOutputStream(file)) {
                    IOUtils.copyLarge(is, fos);
                }
            }
        }
    }

    srcAttr.setValue(file.getParentFile().getName() + FILE_SEPARATOR + file.getName());
    return map;
}
 
Example #26
Source File: JavaScriptJobManagerMinimalTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Initializes variables required by the unit tests.
 */
@Before
public void before() {
    client_ = new WebClient();
    window_ = EasyMock.createNiceMock(WebWindow.class);
    page_ = EasyMock.createNiceMock(Page.class);
    manager_ = new JavaScriptJobManagerImpl(window_);
    EasyMock.expect(window_.getEnclosedPage()).andReturn(page_).anyTimes();
    EasyMock.expect(window_.getJobManager()).andReturn(manager_).anyTimes();
    EasyMock.replay(window_, page_);
    eventLoop_ = new DefaultJavaScriptExecutor(client_);
    eventLoop_.addWindow(window_);
}
 
Example #27
Source File: HtmlOption.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Page mouseOver(final boolean shiftKey, final boolean ctrlKey, final boolean altKey, final int button) {
    final SgmlPage page = getPage();
    if (page.getWebClient().getBrowserVersion().hasFeature(EVENT_ONMOUSEOVER_NEVER_FOR_SELECT_OPTION)) {
        return page;
    }
    return super.mouseOver(shiftKey, ctrlKey, altKey, button);
}
 
Example #28
Source File: DomNode.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
private void fireAddition(final DomNode domNode) {
    final boolean wasAlreadyAttached = domNode.isAttachedToPage();
    domNode.attachedToPage_ = isAttachedToPage();

    if (isAttachedToPage()) {
        // trigger events
        final Page page = getPage();
        if (null != page && page.isHtmlPage()) {
            ((HtmlPage) page).notifyNodeAdded(domNode);
        }

        // a node that is already "complete" (ie not being parsed) and not yet attached
        if (!domNode.isBodyParsed() && !wasAlreadyAttached) {
            for (final DomNode child : domNode.getDescendants()) {
                child.attachedToPage_ = true;
                child.onAllChildrenAddedToPage(true);
            }
            domNode.onAllChildrenAddedToPage(true);
        }
    }

    if (this instanceof DomDocumentFragment) {
        onAddedToDocumentFragment();
    }

    fireNodeAdded(new DomChangeEvent(this, domNode));
}
 
Example #29
Source File: MockMvcWebConnectionTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void contextPathExplicit() throws IOException {
	this.webClient.setWebConnection(new MockMvcWebConnection(this.mockMvc, "/context"));

	Page page = this.webClient.getPage("http://localhost/context/a");

	assertThat(page.getWebResponse().getStatusCode(), equalTo(200));
}
 
Example #30
Source File: CsrfValidateFilterIT.java    From krazo with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeleteWithCsrfFieldWorksWithStatusCode200() throws Exception {
    final HtmlPage page1 = webClient.getPage(baseURL + "resources/csrf-methods/ok-delete");
    final HtmlForm form = (HtmlForm) page1.getElementById("form");
    final HtmlSubmitInput button = form.getInputByName("submit");

    final Page result = button.click();

    assertEquals(200, result.getWebResponse()
        .getStatusCode());
}