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

The following examples show how to use com.gargoylesoftware.htmlunit.html.HtmlButton. 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: Window.java    License: Apache License 2.0 6 votes vote down vote up
private boolean matches(final Object object) {
    if (object instanceof HtmlEmbed
        || object instanceof HtmlForm
        || object instanceof HtmlImage
        || object instanceof HtmlObject) {
        return true;
    }

    return includeFormFields_
            && (object instanceof HtmlAnchor
                || object instanceof HtmlButton
                || object instanceof HtmlInput
                || object instanceof HtmlMap
                || object instanceof HtmlSelect
                || object instanceof HtmlTextArea);
}
 
Example 2
Source Project: htmlunit   Source File: HTMLButtonElement.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the {@code type} property.
 * @return the {@code type} property
 */
@JsxGetter
public String getType() {
    String type = ((HtmlButton) getDomNodeOrDie()).getTypeAttribute();
    if (null != type) {
        type = type.toLowerCase(Locale.ROOT);
    }
    if ("reset".equals(type)) {
        return "reset";
    }
    if ("submit".equals(type)) {
        return "submit";
    }
    if ("button".equals(type)) {
        return "button";
    }
    return "submit";
}
 
Example 3
Source Project: htmlunit   Source File: WebClientTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Previous window should become current window after current window is closed while loading the page.
 * @throws Exception if an error occurs
 */
@Test
public void windowTracking_SpecialCase2() throws Exception {
    final WebClient webClient = getWebClient();
    final MockWebConnection conn = new MockWebConnection();

    final String html1 = "<html><head><title>First</title></head>\n"
            + "<body><form name='form1'>\n"
            + "<button id='clickme' onClick='window.open(\"" + URL_SECOND + "\");'>Click me</button>\n"
            + "</form></body></html>";
    conn.setResponse(URL_FIRST, html1);

    final String html2 = "<html><head><title>Third</title>\n"
            + "<script type=\"text/javascript\">\n"
            + "     window.close();\n"
            + "</script></head></html>";
    conn.setDefaultResponse(html2);

    webClient.setWebConnection(conn);
    final HtmlPage firstPage = webClient.getPage(URL_FIRST);
    final HtmlButton buttonA = firstPage.getHtmlElementById("clickme");
    buttonA.click();
    assertNotNull(webClient.getCurrentWindow().getEnclosedPage());
    assertEquals("First", ((HtmlPage) webClient.getCurrentWindow().getEnclosedPage()).getTitleText());
}
 
Example 4
Source Project: htmlunit   Source File: Event3Test.java    License: Apache License 2.0 6 votes vote down vote up
private void testEventOnClick_Shift_Ctrl_Alt(final boolean shiftKey,
        final boolean ctrlKey, final boolean altKey, final String[] expectedAlerts) throws Exception {
    final String htmlContent
        = "<html><head><title>foo</title></head><body>\n"
        + "<form id='form1'>\n"
        + "  <button name='button' type='button' id='button'>Push me</button>\n"
        + "</form>\n"
        + "<script>\n"
        + "function handler(_e) {\n"
        + "  var e = _e ? _e : window.event;\n"
        + "  alert(e.shiftKey + ',' + e.ctrlKey + ',' + e.altKey);\n"
        + "}\n"
        + "document.getElementById('button').onclick = handler;\n"
        + "</script>\n"
        + "</body></html>";
    final List<String> collectedAlerts = new ArrayList<>();
    final HtmlPage page = loadPage(htmlContent, collectedAlerts);
    final HtmlButton button = page.getHtmlElementById("button");

    final HtmlPage secondPage = button.click(shiftKey, ctrlKey, altKey);

    assertEquals(expectedAlerts, collectedAlerts);

    assertSame(page, secondPage);
}
 
Example 5
Source Project: htmlunit   Source File: HTMLFormElement2Test.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void formSubmit_MultipleButtons() throws Exception {
    final String html
        = "<html><head><title>first</title></head><body>\n"
        + "<p>hello world</p>\n"
        + "<form name='form1' method='get' action='" + URL_SECOND + "'>\n"
        + "  <button type='submit' name='button1' id='button1'/>\n"
        + "  <button type='submit' name='button2' />\n"
        + "</form>\n"
        + "</body></html>";
    final String secondContent
        = "<html><head><title>second</title></head><body>\n"
        + "<p>hello world</p>\n"
        + "</body></html>";

    getMockWebConnection().setDefaultResponse(secondContent);

    final HtmlPage page = loadPageWithAlerts(html);
    assertEquals("first", page.getTitleText());

    final HtmlButton button = page.getHtmlElementById("button1");
    final HtmlPage secondPage = button.click();
    assertEquals("second", secondPage.getTitleText());
    assertEquals(URL_SECOND + "?button1=", secondPage.getUrl());
}
 
Example 6
Source Project: HtmlUnit-Android   Source File: Window.java    License: Apache License 2.0 6 votes vote down vote up
private boolean matches(final Object object) {
    if (object instanceof HtmlEmbed
        || object instanceof HtmlForm
        || object instanceof HtmlImage
        || object instanceof HtmlObject) {
        return true;
    }
    if (includeFormFields_ && (
            object instanceof HtmlAnchor
            || object instanceof HtmlButton
            || object instanceof HtmlInput
            || object instanceof HtmlMap
            || object instanceof HtmlSelect
            || object instanceof HtmlTextArea)) {
        return true;
    }
    return false;
}
 
Example 7
Source Project: HtmlUnit-Android   Source File: HTMLButtonElement.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the {@code type} property.
 * @return the {@code type} property
 */
@JsxGetter
public String getType() {
    String type = ((HtmlButton) getDomNodeOrDie()).getTypeAttribute();
    if (null != type) {
        type = type.toLowerCase(Locale.ROOT);
    }
    if ("reset".equals(type)) {
        return "reset";
    }
    if ("submit".equals(type)) {
        return "submit";
    }
    if ("button".equals(type)) {
        return "button";
    }
    return "submit";
}
 
Example 8
Source Project: kubernetes-plugin   Source File: KubernetesCloudTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void defaultWorkspaceVolume() throws Exception {
    KubernetesCloud cloud = new KubernetesCloud("kubernetes");
    j.jenkins.clouds.add(cloud);
    j.jenkins.save();
    JenkinsRule.WebClient wc = j.createWebClient();
    HtmlPage p = wc.goTo("configureClouds/");
    HtmlForm f = p.getFormByName("config");
    HtmlButton buttonExtends = HtmlFormUtil.getButtonByCaption(f, "Pod Templates...");
    buttonExtends.click();
    HtmlButton buttonAdd = HtmlFormUtil.getButtonByCaption(f, "Add Pod Template");
    buttonAdd.click();
    HtmlButton buttonDetails = HtmlFormUtil.getButtonByCaption(f, "Pod Template details...");
    buttonDetails.click();
    DomElement templates = p.getElementByName("templates");
    HtmlInput templateName = getInputByName(templates, "_.name");
    templateName.setValueAttribute("default-workspace-volume");
    j.submit(f);
    cloud = j.jenkins.clouds.get(KubernetesCloud.class);
    PodTemplate podTemplate = cloud.getTemplates().get(0);
    assertEquals("default-workspace-volume", podTemplate.getName());
    assertEquals(WorkspaceVolume.getDefault(), podTemplate.getWorkspaceVolume());
}
 
Example 9
Source Project: cxf-fediz   Source File: AbstractOIDCTest.java    License: Apache License 2.0 6 votes vote down vote up
private static HtmlPage registerClient(HtmlPage registerPage,
                                        String clientName, String redirectURI,
                                        String clientAudience,
                                        String logoutURI,
                                        boolean confidential) throws IOException {
    final HtmlForm form = registerPage.getForms().get(0);

    // Set new client values
    final HtmlTextInput clientNameInput = form.getInputByName("client_name");
    clientNameInput.setValueAttribute(clientName);
    final HtmlSelect clientTypeSelect = form.getSelectByName("client_type");
    clientTypeSelect.setSelectedAttribute(confidential ? "confidential" : "public", true);
    final HtmlTextInput redirectURIInput = form.getInputByName("client_redirectURI");
    redirectURIInput.setValueAttribute(redirectURI);
    final HtmlTextInput clientAudienceURIInput = form.getInputByName("client_audience");
    clientAudienceURIInput.setValueAttribute(clientAudience);
    final HtmlTextInput clientLogoutURI = form.getInputByName("client_logoutURI");
    clientLogoutURI.setValueAttribute(logoutURI);

    final HtmlButton button = form.getButtonByName("submit_button");
    return button.click();
}
 
Example 10
@Test
	public void testCreateTasks() throws Exception {

		HtmlPage createTaskPage = webClient.getPage("http://localhost:8080/tasks/new");

		HtmlForm form = createTaskPage.getHtmlElementById("form");
		HtmlTextInput nameInput = createTaskPage.getHtmlElementById("name");
		nameInput.setValueAttribute("My first task");
		HtmlTextArea descriptionInput = createTaskPage.getHtmlElementById("description");
		descriptionInput.setText("Description of my first task");
		HtmlButton submit = form.getOneHtmlElementByAttribute("button", "type", "submit");
		HtmlPage taskListPage = submit.click();

		Assertions.assertThat(taskListPage.getUrl().toString()).endsWith("/tasks");
//		String id = taskListPage.getHtmlElementById("todolist").getTextContent();
//		assertThat(id).isEqualTo("123");
//		String summary = newMessagePage.getHtmlElementById("summary").getTextContent();
//		assertThat(summary).isEqualTo("Spring Rocks");
//		String text = newMessagePage.getHtmlElementById("text").getTextContent();
//		assertThat(text).isEqualTo("In case you didn't know, Spring Rocks!");

	}
 
Example 11
Source Project: htmlunit   Source File: WebClientTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Previous window should become current window after current window is closed in onLoad event.
 * @throws Exception if an error occurs
 */
@Test
public void windowTracking_SpecialCase1() throws Exception {
    final WebClient webClient = getWebClient();
    final MockWebConnection conn = new MockWebConnection();

    final String html1 = "<html><head><title>First</title></head>\n"
            + "<body><form name='form1'>\n"
            + "<button id='clickme' onClick='window.open(\"" + URL_SECOND + "\");'>Click me</button>\n"
            + "</form></body></html>";
    conn.setResponse(URL_FIRST, html1);

    final String html2 = "<html><head><title>Second</title></head>\n"
            + "<body onload='doTest()'>\n"
            + "<script>\n"
            + "  function doTest() {\n"
            + "    window.close();\n"
            + "  }\n"
            + "</script></body></html>";
    conn.setDefaultResponse(html2);

    webClient.setWebConnection(conn);
    final HtmlPage firstPage = webClient.getPage(URL_FIRST);
    final HtmlButton buttonA = firstPage.getHtmlElementById("clickme");
    buttonA.click();
    assertNotNull(webClient.getCurrentWindow().getEnclosedPage());
    assertEquals("First", ((HtmlPage) webClient.getCurrentWindow().getEnclosedPage()).getTitleText());
}
 
Example 12
Source Project: htmlunit   Source File: GWT250Test.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if an error occurs
 */
@Test
public void hello() throws Exception {
    final List<String> collectedAlerts = new ArrayList<>();
    final HtmlPage page = loadGWTPage("Hello", collectedAlerts, "//button");
    final HtmlButton button = page.getFirstByXPath("//button");
    final DomText buttonLabel = (DomText) button.getChildren().iterator().next();
    assertEquals("Click me", buttonLabel.getData());
    button.click();
    final String[] expectedAlerts = {"Hello, AJAX"};
    assertEquals(expectedAlerts, collectedAlerts);
}
 
Example 13
Source Project: htmlunit   Source File: GWT250Test.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if an error occurs
 */
@Test
public void json() throws Exception {
    final HtmlPage page = loadGWTPage("JSON", null, "//button");
    final HtmlButton button = page.getFirstByXPath("//button");
    button.click();

    page.getWebClient().waitForBackgroundJavaScriptStartingBefore(2000);

    final HtmlSpan span =
        page.getFirstByXPath("//div[@class='JSON-JSONResponseObject']/div/div/table//td[2]/div/span");
    assertEquals("ResultSet", span.getFirstChild().getNodeValue());
}
 
Example 14
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 setOpenerLocationHrefRelative() throws Exception {
    final WebClient webClient = getWebClient();
    final MockWebConnection webConnection = new MockWebConnection();

    final String aContent
        = "<html><head><title>A</title></head><body>\n"
        + "<button id='clickme' onClick='window.open(\"b/b.html\");'>Click me</a>\n"
        + "</body></html>";
    final String bContent
        = "<html><head><title>B</title></head><body>\n"
        + "<button id='clickme' onClick='opener.location.href=\"../c.html\";'>Click me</a>\n"
        + "</body></html>";
    final String cContent
        = "<html><head><title>C</title></head><body></body></html>";
    final String failContent
        = "<html><head><title>FAILURE!!!</title></head><body></body></html>";

    webConnection.setResponse(new URL("http://opener/test/a.html"), aContent);
    webConnection.setResponse(new URL("http://opener/test/b/b.html"), bContent);
    webConnection.setResponse(new URL("http://opener/test/c.html"), cContent);
    webConnection.setResponse(new URL("http://opener/c.html"), failContent);

    webClient.setWebConnection(webConnection);

    final HtmlPage firstPage = webClient.getPage("http://opener/test/a.html");
    assertEquals("A", firstPage.getTitleText());

    final HtmlButton buttonA = firstPage.getHtmlElementById("clickme");
    final HtmlPage pageB = buttonA.click();
    assertNotNull("B", pageB);
    assertEquals("B", pageB.getTitleText());

    final HtmlButton buttonB = pageB.getHtmlElementById("clickme");
    final HtmlPage thirdPage = buttonB.click();
    assertSame("Page B has lost focus", pageB, thirdPage);
    assertEquals("C", ((HtmlPage) firstPage.getEnclosingWindow().getEnclosedPage()).getTitleText());
}
 
Example 15
Source Project: htmlunit   Source File: HTMLElement3Test.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
@Alerts({"onfocus text1", "onfocus text2", "onfocus text1", "onfocus text2"})
public void onFocusOnWindowFocusGain() throws Exception {
    final WebClient webClient = getWebClient();
    final MockWebConnection webConnection = new MockWebConnection();
    final List<String> collectedAlerts = new ArrayList<>();

    webClient.setAlertHandler(new CollectingAlertHandler(collectedAlerts));

    final String firstHtml = "<html><head><title>First</title></head>\n"
        + "<body><form name='form1'>\n"
        + "<input id='text1' onfocus='alert(\"onfocus text1\")'>\n"
        + "<button type='button' id='clickme' onClick='window.open(\"" + URL_SECOND + "\");'>Click me</a>\n"
        + "</form></body></html>";
    webConnection.setResponse(URL_FIRST, firstHtml);

    final String secondHtml = "<html><head><title>Second</title></head>\n"
        + "<body onLoad='doTest()'>\n"
        + "<input id='text2' onfocus='alert(\"onfocus text2\")'>\n"
        + "<script>\n"
        + "  function doTest() {\n"
        + "    opener.document.getElementById('text1').focus();\n"
        + "    document.getElementById('text2').focus();\n"
        + "  }\n"
        + "</script></body></html>";

    webConnection.setResponse(URL_SECOND, secondHtml);
    webClient.setWebConnection(webConnection);

    final HtmlPage firstPage = webClient.getPage(URL_FIRST);
    assertEquals("First", firstPage.getTitleText());

    final HtmlButton buttonA = firstPage.getHtmlElementById("clickme");
    final HtmlPage secondPage = buttonA.click();
    assertEquals("Second", secondPage.getTitleText());
    webClient.setCurrentWindow(firstPage.getEnclosingWindow());
    webClient.setCurrentWindow(secondPage.getEnclosingWindow());
    assertEquals(getExpectedAlerts(), collectedAlerts);
}
 
Example 16
Source Project: htmlunit   Source File: HTMLElement3Test.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
@Alerts({"onblur text2", "onblur text1"})
public void onBlurOnWindowFocusChange() throws Exception {
    final WebClient webClient = getWebClient();
    final MockWebConnection webConnection = new MockWebConnection();
    final List<String> collectedAlerts = new ArrayList<>();

    webClient.setAlertHandler(new CollectingAlertHandler(collectedAlerts));

    final String firstHtml = "<html><head><title>First</title></head>\n"
        + "<body><form name='form1'>\n"
        + "<input id='text1' onblur='alert(\"onblur text1\")'>\n"
        + "<button type='button' id='clickme' onClick='window.open(\"" + URL_SECOND + "\");'>Click me</a>\n"
        + "</form></body></html>";
    webConnection.setResponse(URL_FIRST, firstHtml);

    final String secondHtml = "<html><head><title>Second</title></head>\n"
        + "<body onLoad='doTest()'>\n"
        + "<input id='text2' onblur='alert(\"onblur text2\")'>\n"
        + "<script>\n"
        + "  function doTest() {\n"
        + "    opener.document.getElementById('text1').focus();\n"
        + "    document.getElementById('text2').focus();\n"
        + "  }\n"
        + "</script></body></html>";

    webConnection.setResponse(URL_SECOND, secondHtml);
    webClient.setWebConnection(webConnection);

    final HtmlPage firstPage = webClient.getPage(URL_FIRST);
    assertEquals("First", firstPage.getTitleText());

    final HtmlButton buttonA = firstPage.getHtmlElementById("clickme");
    final HtmlPage secondPage = buttonA.click();
    assertEquals("Second", secondPage.getTitleText());
    webClient.setCurrentWindow(firstPage.getEnclosingWindow());
    webClient.setCurrentWindow(secondPage.getEnclosingWindow());
    assertEquals(getExpectedAlerts(), collectedAlerts);
}
 
Example 17
Source Project: jenkins-test-harness   Source File: JenkinsRule.java    License: MIT License 5 votes vote down vote up
public HtmlButton getButtonByCaption(HtmlForm f, String s) {
    for (HtmlElement b : f.getElementsByTagName("button")) {
        if(b.getTextContent().trim().equals(s))
            return (HtmlButton)b;
    }
    return null;
}
 
Example 18
Source Project: jenkins-test-harness   Source File: HudsonTestCase.java    License: MIT License 5 votes vote down vote up
/**
 * Submits the form by clicking the submit button of the given name.
 *
 * @param name
 *      This corresponds to the @name of {@code <f:submit />}
 */
public HtmlPage submit(HtmlForm form, String name) throws Exception {
    for( HtmlElement e : form.getElementsByTagName("button")) {
        HtmlElement p = (HtmlElement)e.getParentNode().getParentNode();
        if (e instanceof HtmlButton && p.getAttribute("name").equals(name)) {
            return (HtmlPage)HtmlFormUtil.submit(form, (HtmlButton) e);
        }
    }
    throw new AssertionError("No such submit button with the name "+name);
}
 
Example 19
Source Project: jenkins-test-harness   Source File: HudsonTestCase.java    License: MIT License 5 votes vote down vote up
protected HtmlButton getButtonByCaption(HtmlForm f, String s) {
    for (HtmlElement b : f.getElementsByTagName("button")) {
        if(b.getTextContent().trim().equals(s))
            return (HtmlButton)b;
    }
    return null;
}
 
Example 20
Source Project: cxf-fediz   Source File: AbstractOIDCTest.java    License: Apache License 2.0 5 votes vote down vote up
private static HtmlPage deleteClient(final HtmlPage registeredClientPage) throws IOException {
    final HtmlForm deleteForm = registeredClientPage.getFormByName("deleteForm");
    assertNotNull(deleteForm);

    // Delete the client
    final HtmlButton button = deleteForm.getButtonByName("submit_delete_button");
    return button.click();
}
 
Example 21
Source Project: htmlunit   Source File: ComputedCSSStyleDeclaration.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Returns the element's calculated height taking relevant CSS into account, but <b>not</b> the element's child
 * elements.
 *
 * @return the element's calculated height taking relevant CSS into account, but <b>not</b> the element's child
 *         elements
 */
private int getEmptyHeight() {
    if (height2_ != null) {
        return height2_.intValue();
    }

    final DomNode node = getElement().getDomNodeOrDie();
    if (!node.mayBeDisplayed()) {
        height2_ = Integer.valueOf(0);
        return 0;
    }

    if (NONE.equals(getDisplay())) {
        height2_ = Integer.valueOf(0);
        return 0;
    }

    final Element elem = getElement();
    final int windowHeight = elem.getWindow().getWebWindow().getInnerHeight();

    if (elem instanceof HTMLBodyElement) {
        height2_ = windowHeight;
        return windowHeight;
    }

    final boolean explicitHeightSpecified = !super.getHeight().isEmpty();

    int defaultHeight;
    if (node instanceof HtmlDivision && StringUtils.isBlank(node.getTextContent())) {
        defaultHeight = 0;
    }
    else if (elem.getFirstChild() == null) {
        if (node instanceof HtmlRadioButtonInput || node instanceof HtmlCheckBoxInput) {
            defaultHeight = 13;
        }
        else if (node instanceof HtmlButton) {
            defaultHeight = 20;
        }
        else if (node instanceof HtmlInput && !(node instanceof HtmlHiddenInput)) {
            final BrowserVersion browser = getBrowserVersion();
            if (browser.hasFeature(JS_CLIENTHIGHT_INPUT_17)) {
                defaultHeight = 17;
            }
            else if (browser.hasFeature(JS_CLIENTHIGHT_INPUT_21)) {
                defaultHeight = 21;
            }
            else {
                defaultHeight = 20;
            }
        }
        else if (node instanceof HtmlSelect) {
            defaultHeight = 20;
        }
        else if (node instanceof HtmlTextArea) {
            defaultHeight = 49;
        }
        else if (node instanceof HtmlInlineFrame) {
            defaultHeight = 154;
        }
        else {
            defaultHeight = 0;
        }
    }
    else {
        defaultHeight = getBrowserVersion().getFontHeight(getFontSize());
        if (node instanceof HtmlDivision) {
            defaultHeight *= StringUtils.countMatches(node.asText(), '\n') + 1;
        }
    }

    final int defaultWindowHeight = elem instanceof HTMLCanvasElement ? 150 : windowHeight;

    int height = pixelValue(elem, new CssValue(defaultHeight, defaultWindowHeight) {
        @Override public String get(final ComputedCSSStyleDeclaration style) {
            final Element element = style.getElement();
            if (element instanceof HTMLBodyElement) {
                return String.valueOf(element.getWindow().getWebWindow().getInnerHeight());
            }
            return style.getStyleAttribute(HEIGHT, true);
        }
    });

    if (height == 0 && !explicitHeightSpecified) {
        height = defaultHeight;
    }

    height2_ = Integer.valueOf(height);
    return height;
}
 
Example 22
Source Project: htmlunit   Source File: HTMLFormElement.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Returns the value of the property {@code elements}.
 * @return the value of this property
 */
@JsxGetter
public HTMLCollection getElements() {
    final HtmlForm htmlForm = getHtmlForm();

    return new HTMLCollection(htmlForm, false) {
        private boolean filterChildrenOfNestedForms_;

        @Override
        protected List<DomNode> computeElements() {
            final List<DomNode> response = super.computeElements();
            // it would be more performant to avoid iterating through
            // nested forms but as it is a corner case of ill formed HTML
            // the needed refactoring would take too much time
            // => filter here and not in isMatching as it won't be needed in most
            // of the cases
            if (filterChildrenOfNestedForms_) {
                for (final Iterator<DomNode> iter = response.iterator(); iter.hasNext();) {
                    final HtmlElement field = (HtmlElement) iter.next();
                    if (field.getEnclosingForm() != htmlForm) {
                        iter.remove();
                    }
                }
            }
            response.addAll(htmlForm.getLostChildren());
            return response;
        }

        @Override
        protected Object getWithPreemption(final String name) {
            return HTMLFormElement.this.getWithPreemption(name);
        }

        @Override
        public EffectOnCache getEffectOnCache(final HtmlAttributeChangeEvent event) {
            return EffectOnCache.NONE;
        }

        @Override
        protected boolean isMatching(final DomNode node) {
            if (node instanceof HtmlForm) {
                filterChildrenOfNestedForms_ = true;
                return false;
            }

            return node instanceof HtmlInput || node instanceof HtmlButton
                    || node instanceof HtmlTextArea || node instanceof HtmlSelect;
        }
    };
}
 
Example 23
Source Project: htmlunit   Source File: WebClientTest.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Previous window should become current window after current window is closed.
 * @throws Exception if an error occurs
 */
@Test
@Alerts(DEFAULT = {},
        IE = "Third page loaded")
public void windowTracking_SpecialCase3() throws Exception {
    final WebClient webClient = getWebClient();
    final MockWebConnection conn = new MockWebConnection();
    final List<String> collectedAlerts = new ArrayList<>();
    webClient.setAlertHandler(new CollectingAlertHandler(collectedAlerts));

    final String html1 = "<html><head><title>First</title></head>\n"
            + "<body>\n"
            + "<button id='clickme' onClick='window.open(\"" + URL_SECOND + "\");'>Click me</button>\n"
            + "</body></html>";
    conn.setResponse(URL_FIRST, html1);

    final String html2 = "<html><head><title>Second</title></head>\n"
            + "<body onUnload='doTest()'>\n"
            + "<form name='form1' action='" + URL_THIRD + "'>\n"
            + "<button id='clickme' type='button' onclick='postBack();'>Submit</button></form>\n"
            + "<script>\n"
            + "    function doTest() {\n"
            + "      window.close();\n"
            + "    }\n"
            + "    function postBack() {\n"
            + "      var frm = document.forms[0];\n"
            + "      frm.submit();\n"
            + "    }\n"
            + "</script></body></html>";
    conn.setResponse(URL_SECOND, html2);

    final String html3 = "<html><head><title>Third</title>\n"
            + "<script type=\"text/javascript\">\n"
            + "     alert('Third page loaded');\n"
            + "     window.close();\n"
            + "</script></head></html>";
    conn.setResponse(URL_THIRD, html3);
    conn.setDefaultResponse(html3);

    webClient.setWebConnection(conn);
    final HtmlPage firstPage = webClient.getPage(URL_FIRST);

    final HtmlButton buttonA = firstPage.getHtmlElementById("clickme");
    buttonA.click();
    final HtmlPage secondPage = (HtmlPage) webClient.getCurrentWindow().getEnclosedPage();
    assertEquals("Second", secondPage.getTitleText());

    final HtmlButton buttonB = secondPage.getHtmlElementById("clickme");
    buttonB.click();
    assertEquals("First", ((HtmlPage) webClient.getCurrentWindow().getEnclosedPage()).getTitleText());
    assertEquals(getExpectedAlerts(), collectedAlerts);
}
 
Example 24
/**
 * Returns the element's calculated height taking relevant CSS into account, but <b>not</b> the element's child
 * elements.
 *
 * @return the element's calculated height taking relevant CSS into account, but <b>not</b> the element's child
 *         elements
 */
private int getEmptyHeight() {
    if (height2_ != null) {
        return height2_.intValue();
    }

    final DomNode node = getElement().getDomNodeOrDie();
    if (!node.mayBeDisplayed()) {
        height2_ = Integer.valueOf(0);
        return 0;
    }

    if ("none".equals(getDisplay())) {
        height2_ = Integer.valueOf(0);
        return 0;
    }

    final Element elem = getElement();
    final int windowHeight = elem.getWindow().getWebWindow().getInnerHeight();

    if (elem instanceof HTMLBodyElement) {
        height2_ = windowHeight;
        return windowHeight;
    }

    final boolean explicitHeightSpecified = !super.getHeight().isEmpty();

    int defaultHeight;
    if (node instanceof HtmlDivision && StringUtils.isBlank(node.getTextContent())) {
        defaultHeight = 0;
    }
    else if (elem.getFirstChild() == null) {
        if (node instanceof HtmlRadioButtonInput || node instanceof HtmlCheckBoxInput) {
            defaultHeight = 13;
        }
        else if (node instanceof HtmlButton) {
            defaultHeight = 20;
        }
        else if (node instanceof HtmlInput && !(node instanceof HtmlHiddenInput)) {
            if (getBrowserVersion().hasFeature(JS_CLIENTHIGHT_INPUT_17)) {
                defaultHeight = 17;
            }
            else {
                defaultHeight = 21;
            }
        }
        else if (node instanceof HtmlSelect) {
            defaultHeight = 20;
        }
        else if (node instanceof HtmlTextArea) {
            defaultHeight = 49;
        }
        else if (node instanceof HtmlInlineFrame) {
            defaultHeight = 154;
        }
        else {
            defaultHeight = 0;
        }
    }
    else {
        defaultHeight = getBrowserVersion().getFontHeight(getFontSize());
        if (node instanceof HtmlDivision) {
            defaultHeight *= StringUtils.countMatches(node.asText(), '\n') + 1;
        }
    }

    final int defaultWindowHeight = elem instanceof HTMLCanvasElement ? 150 : windowHeight;

    int height = pixelValue(elem, new CssValue(defaultHeight, defaultWindowHeight) {
        @Override public String get(final ComputedCSSStyleDeclaration style) {
            final Element element = style.getElement();
            if (element instanceof HTMLBodyElement) {
                return String.valueOf(element.getWindow().getWebWindow().getInnerHeight());
            }
            return style.getStyleAttribute(HEIGHT, true);
        }
    });

    if (height == 0 && !explicitHeightSpecified) {
        height = defaultHeight;
    }

    height2_ = Integer.valueOf(height);
    return height;
}
 
Example 25
Source Project: HtmlUnit-Android   Source File: HTMLFormElement.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Returns the value of the property {@code elements}.
 * @return the value of this property
 */
@JsxGetter
public HTMLCollection getElements() {
    final HtmlForm htmlForm = getHtmlForm();

    return new HTMLCollection(htmlForm, false) {
        private boolean filterChildrenOfNestedForms_;

        @Override
        protected List<DomNode> computeElements() {
            final List<DomNode> response = super.computeElements();
            // it would be more performant to avoid iterating through
            // nested forms but as it is a corner case of ill formed HTML
            // the needed refactoring would take too much time
            // => filter here and not in isMatching as it won't be needed in most
            // of the cases
            if (filterChildrenOfNestedForms_) {
                for (final Iterator<DomNode> iter = response.iterator(); iter.hasNext();) {
                    final HtmlElement field = (HtmlElement) iter.next();
                    if (field.getEnclosingForm() != htmlForm) {
                        iter.remove();
                    }
                }
            }
            response.addAll(htmlForm.getLostChildren());
            return response;
        }

        @Override
        protected Object getWithPreemption(final String name) {
            return HTMLFormElement.this.getWithPreemption(name);
        }

        @Override
        public EffectOnCache getEffectOnCache(final HtmlAttributeChangeEvent event) {
            return EffectOnCache.NONE;
        }

        @Override
        protected boolean isMatching(final DomNode node) {
            if (node instanceof HtmlForm) {
                filterChildrenOfNestedForms_ = true;
                return false;
            }

            return node instanceof HtmlInput || node instanceof HtmlButton
                    || node instanceof HtmlTextArea || node instanceof HtmlSelect;
        }
    };
}
 
Example 26
Source Project: slr-toolkit   Source File: GSWorker.java    License: Eclipse Public License 1.0 4 votes vote down vote up
protected IStatus initSession() {
	IStatus s;
	try {
		// load main page
		HtmlPage page = webClient.getPage(scholar);

		// Timeouts
		s = waitLikeUser();
		if (!s.isOK())
			return s;
		s = waitForJs(page);
		if (!s.isOK())
			return s;

		// select link to settings form, load settings form
		HtmlAnchor configLink = page.getFirstByXPath("//a[contains(@href, '/scholar_settings')]");
		HtmlPage configFormPage = webClient
				.getPage(configLink.getBaseURI() + configLink.getHrefAttribute().substring(1));

		// Timeouts
		s = waitLikeUser();
		if (!s.isOK())
			return s;
		s = waitForJs(page);
		if (!s.isOK())
			return s;

		// select settings form and enable bibtex
		HtmlForm configForm = configFormPage.getFirstByXPath("//form[@action='/scholar_setprefs']");
		for (HtmlInput r : configForm.getInputsByName("scis")) {
			if (r.getAttribute("value").equals("yes")) {
				r.setChecked(true);
				break;
			}
		}

		// click save
		HtmlButton configFormSave = configForm.getButtonByName("save");
		HtmlPage readyForSearch = configFormSave.click();

		// Timeouts
		s = waitLikeUser();
		if (!s.isOK())
			return s;
		s = waitForJs(page);
		if (!s.isOK())
			return s;
	} catch (FailingHttpStatusCodeException | IOException e) {
		return new Status(Status.ERROR, "de.tudresden.slr.googlescholar",
				"Could not initialize Google Scholar session", e);
	}

	return Status.OK_STATUS;
}