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

The following examples show how to use com.gargoylesoftware.htmlunit.html.HtmlInput. 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: HTMLInputElement.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the value of the JavaScript attribute {@code value}.
 *
 * @return the value of this attribute
 */
@JsxGetter
@Override
public String getValue() {
    final HtmlInput htmlInput = getDomNodeOrDie();
    if (htmlInput instanceof HtmlFileInput) {
        final File[] files = ((HtmlFileInput) htmlInput).getFiles();
        if (files == null || files.length == 0) {
            return ATTRIBUTE_NOT_DEFINED;
        }
        final File first = files[0];
        final String name = first.getName();
        if (name.isEmpty()) {
            return name;
        }
        return "C:\\fakepath\\" + name;
    }
    return htmlInput.getAttributeDirect("value");
}
 
Example 3
Source Project: htmlunit   Source File: HTMLInputElement.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void click() throws IOException {
    final HtmlInput domNode = getDomNodeOrDie();
    final boolean originalState = domNode.isChecked();
    final Event event;
    if (getBrowserVersion().hasFeature(EVENT_ONCLICK_USES_POINTEREVENT)) {
        event = new PointerEvent(domNode, MouseEvent.TYPE_CLICK, false, false, false, MouseEvent.BUTTON_LEFT);
    }
    else {
        event = new MouseEvent(domNode, MouseEvent.TYPE_CLICK, false, false, false, MouseEvent.BUTTON_LEFT);
    }
    domNode.click(event, event.isShiftKey(), event.isCtrlKey(), event.isAltKey(), true);

    final boolean newState = domNode.isChecked();

    if (originalState != newState
            && (domNode instanceof HtmlRadioButtonInput || domNode instanceof HtmlCheckBoxInput)) {
        domNode.fireEvent(Event.TYPE_CHANGE);
    }
}
 
Example 4
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 5
Source Project: HtmlUnit-Android   Source File: HTMLInputElement.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public String getValue() {
    final HtmlInput htmlInput = getDomNodeOrDie();
    if (htmlInput instanceof HtmlFileInput) {
        final File[] files = ((HtmlFileInput) getDomNodeOrDie()).getFiles();
        if (files == null || files.length == 0) {
            return ATTRIBUTE_NOT_DEFINED;
        }
        final File first = files[0];
        final String name = first.getName();
        if (name.isEmpty()) {
            return name;
        }
        if (getBrowserVersion().hasFeature(HTMLINPUT_FILE_VALUE_FAKEPATH)) {
            return "C:\\fakepath\\" + name;
        }
        return name;
    }
    return super.getValue();
}
 
Example 6
Source Project: HtmlUnit-Android   Source File: HTMLInputElement.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void click() throws IOException {
    final HtmlInput domNode = getDomNodeOrDie();
    final boolean originalState = domNode.isChecked();
    final Event event;
    if (getBrowserVersion().hasFeature(EVENT_ONCLICK_USES_POINTEREVENT)) {
        event = new PointerEvent(domNode, MouseEvent.TYPE_CLICK, false, false, false, MouseEvent.BUTTON_LEFT);
    }
    else {
        event = new MouseEvent(domNode, MouseEvent.TYPE_CLICK, false, false, false, MouseEvent.BUTTON_LEFT);
    }
    domNode.click(event, true);

    final boolean newState = domNode.isChecked();

    if (originalState != newState
            && (domNode instanceof HtmlRadioButtonInput || domNode instanceof HtmlCheckBoxInput)) {
        domNode.fireEvent(Event.TYPE_CHANGE);
    }
}
 
Example 7
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 8
Source Project: htmlunit   Source File: HTMLCollection.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected Object getWithPreemptionByName(final String name, final List<DomNode> elements) {
    final List<DomNode> matchingElements = new ArrayList<>();
    final boolean searchName = isGetWithPreemptionSearchName();
    for (final DomNode next : elements) {
        if (next instanceof DomElement
                && (searchName || next instanceof HtmlInput || next instanceof HtmlForm)) {
            final String nodeName = ((DomElement) next).getAttributeDirect("name");
            if (name.equals(nodeName)) {
                matchingElements.add(next);
            }
        }
    }

    if (matchingElements.isEmpty()) {
        if (getBrowserVersion().hasFeature(HTMLCOLLECTION_ITEM_SUPPORTS_DOUBLE_INDEX_ALSO)) {
            final Double doubleValue = Context.toNumber(name);
            if (!doubleValue.isNaN()) {
                final Object object = get(doubleValue.intValue(), this);
                if (object != NOT_FOUND) {
                    return object;
                }
            }
        }
        return NOT_FOUND;
    }
    else if (matchingElements.size() == 1) {
        return getScriptableForElement(matchingElements.get(0));
    }

    // many elements => build a sub collection
    final DomNode domNode = getDomNodeOrNull();
    final HTMLCollection collection = new HTMLCollection(domNode, matchingElements);
    collection.setAvoidObjectDetection(true);
    return collection;
}
 
Example 9
Source Project: htmlunit   Source File: HTMLInputElement.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Select this element.
 */
@JsxFunction
public void select() {
    final HtmlInput input = getDomNodeOrDie();
    if (input instanceof HtmlTextInput) {
        ((HtmlTextInput) input).select();
    }
    // currently nothing for other input types
}
 
Example 10
Source Project: htmlunit   Source File: HTMLInputElement.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the {@code files} property.
 * @return the {@code files} property
 */
@JsxGetter
public Object getFiles() {
    final HtmlInput htmlInput = getDomNodeOrDie();
    if (htmlInput instanceof HtmlFileInput) {
        final FileList list = new FileList(((HtmlFileInput) htmlInput).getFiles());
        list.setParentScope(getParentScope());
        list.setPrototype(getPrototype(list.getClass()));
        return list;
    }
    if (getBrowserVersion().hasFeature(HTMLINPUT_FILES_UNDEFINED)) {
        return Undefined.instance;
    }
    return null;
}
 
Example 11
Source Project: htmlunit   Source File: HTMLFormElement.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the value of the property {@code length}.
 * Does not count input {@code type=image} elements
 * (<a href="http://msdn.microsoft.com/en-us/library/ms534101.aspx">MSDN doc</a>)
 * @return the value of this property
 */
@JsxGetter
public int getLength() {
    final int all = getElements().getLength();
    final int images = getHtmlForm().getElementsByAttribute(HtmlInput.TAG_NAME, "type", "image").size();
    return all - images;
}
 
Example 12
Source Project: htmlunit   Source File: WebAssert.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Verifies that the input element with the specified name on the specified page contains the
 * specified value.
 *
 * @param page the page to check
 * @param name the name of the input element to check
 * @param value the value to check for
 */
public static void assertInputContainsValue(final HtmlPage page, final String name, final String value) {
    final String xpath = "//input[@name='" + name + "']";
    final List<?> list = page.getByXPath(xpath);
    if (list.isEmpty()) {
        throw new AssertionError("Unable to find an input element named '" + name + "'.");
    }
    final HtmlInput input = (HtmlInput) list.get(0);
    final String s = input.getValueAttribute();
    if (!s.equals(value)) {
        throw new AssertionError("The input element named '" + name + "' contains the value '" + s
                        + "', not the expected value '" + value + "'.");
    }
}
 
Example 13
Source Project: htmlunit   Source File: WebAssert.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Verifies that the input element with the specified name on the specified page does not
 * contain the specified value.
 *
 * @param page the page to check
 * @param name the name of the input element to check
 * @param value the value to check for
 */
public static void assertInputDoesNotContainValue(final HtmlPage page, final String name, final String value) {
    final String xpath = "//input[@name='" + name + "']";
    final List<?> list = page.getByXPath(xpath);
    if (list.isEmpty()) {
        throw new AssertionError("Unable to find an input element named '" + name + "'.");
    }
    final HtmlInput input = (HtmlInput) list.get(0);
    final String s = input.getValueAttribute();
    if (s.equals(value)) {
        throw new AssertionError("The input element named '" + name + "' contains the value '" + s
                        + "', not the expected value '" + value + "'.");
    }
}
 
Example 14
Source Project: htmlunit   Source File: CSSStyleSheet2Test.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void selects_miscSelectors() throws Exception {
    final String html = "<html><head><title>test</title>\n"
        + "</head><body><style></style>\n"
        + "<form name='f1' action='foo' class='yui-log'>\n"
        + "<div><div><input name='i1' id='m1'></div></div>\n"
        + "<input name='i2' class='yui-log'>\n"
        + "<button name='b1' class='yui-log'>\n"
        + "<button name='b2'>\n"
        + "</form>\n"
        + "</body></html>";

    final HtmlPage page = loadPage(html);
    final HtmlElement body = page.getBody();
    final HtmlForm form = page.getFormByName("f1");
    final HtmlInput input1 = (HtmlInput) page.getElementsByName("i1").get(0);
    final HtmlInput input2 = (HtmlInput) page.getElementsByName("i2").get(0);
    final DomElement button1 = page.getElementsByName("b1").get(0);
    final DomElement button2 = page.getElementsByName("b2").get(0);
    final BrowserVersion browserVersion = getBrowserVersion();

    final HtmlStyle node = (HtmlStyle) page.getElementsByTagName("style").item(0);
    final HTMLStyleElement host = (HTMLStyleElement) node.getScriptableObject();
    final CSSStyleSheet sheet = host.getSheet();

    Selector selector = parseSelector(sheet, "*.yui-log input");

    assertFalse(CSSStyleSheet.selects(browserVersion, selector, body, null, false));
    assertFalse(CSSStyleSheet.selects(browserVersion, selector, form, null, false));
    assertTrue(CSSStyleSheet.selects(browserVersion, selector, input1, null, false));
    assertTrue(CSSStyleSheet.selects(browserVersion, selector, input2, null, false));
    assertFalse(CSSStyleSheet.selects(browserVersion, selector, button1, null, false));
    assertFalse(CSSStyleSheet.selects(browserVersion, selector, button2, null, false));

    selector = parseSelector(sheet, "#m1");
    assertTrue(CSSStyleSheet.selects(browserVersion, selector, input1, null, false));
    assertFalse(CSSStyleSheet.selects(browserVersion, selector, input2, null, false));
}
 
Example 15
Source Project: audit-log-plugin   Source File: NodeChangeListenerTest.java    License: MIT License 5 votes vote down vote up
@Issue("JENKINS-56647")
@Test
public void testOnUpdated() throws Exception {
    Slave slave = j.createOnlineSlave();
    HtmlForm form = j.createWebClient().getPage(slave, "configure").getFormByName("config");
    HtmlInput element = form.getInputByName("_.name");
    element.setValueAttribute("newSlaveName");
    j.submit(form);

    List<LogEvent> events = app.getEvents();

    assertThat(events).hasSize(2);
    assertThat(events).extracting(event -> ((AuditMessage) event.getMessage()).getId().toString()).contains("createNode", "updateNode");
}
 
Example 16
Source Project: HtmlUnit-Android   Source File: HTMLCollection.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected Object getWithPreemptionByName(final String name, final List<DomNode> elements) {
    final List<DomNode> matchingElements = new ArrayList<>();
    final boolean searchName = isGetWithPreemptionSearchName();
    for (final DomNode next : elements) {
        if (next instanceof DomElement
                && (searchName || next instanceof HtmlInput || next instanceof HtmlForm)) {
            final String nodeName = ((DomElement) next).getAttributeDirect("name");
            if (name.equals(nodeName)) {
                matchingElements.add(next);
            }
        }
    }

    if (matchingElements.isEmpty()) {
        if (getBrowserVersion().hasFeature(HTMLCOLLECTION_ITEM_SUPPORTS_DOUBLE_INDEX_ALSO)) {
            final Double doubleValue = Context.toNumber(name);
            if (!doubleValue.isNaN()) {
                final Object object = get(doubleValue.intValue(), this);
                if (object != NOT_FOUND) {
                    return object;
                }
            }
        }
        return NOT_FOUND;
    }
    else if (matchingElements.size() == 1) {
        return getScriptableForElement(matchingElements.get(0));
    }

    // many elements => build a sub collection
    final DomNode domNode = getDomNodeOrNull();
    final HTMLCollection collection = new HTMLCollection(domNode, matchingElements);
    collection.setAvoidObjectDetection(true);
    return collection;
}
 
Example 17
Source Project: HtmlUnit-Android   Source File: HTMLInputElement.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Select this element.
 */
@JsxFunction
public void select() {
    final HtmlInput input = getDomNodeOrDie();
    if (input instanceof HtmlTextInput) {
        ((HtmlTextInput) input).select();
    }
    // currently nothing for other input types
}
 
Example 18
Source Project: HtmlUnit-Android   Source File: HTMLInputElement.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the {@code files} property.
 * @return the {@code files} property
 */
@JsxGetter
public Object getFiles() {
    final HtmlInput htmlInput = getDomNodeOrDie();
    if (htmlInput instanceof HtmlFileInput) {
        final FileList list = new FileList(((HtmlFileInput) htmlInput).getFiles());
        list.setParentScope(getParentScope());
        list.setPrototype(getPrototype(list.getClass()));
        return list;
    }
    if (getBrowserVersion().hasFeature(HTMLINPUT_FILES_UNDEFINED)) {
        return Undefined.instance;
    }
    return null;
}
 
Example 19
Source Project: HtmlUnit-Android   Source File: HTMLFormElement.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the value of the property {@code length}.
 * Does not count input {@code type=image} elements
 * (<a href="http://msdn.microsoft.com/en-us/library/ms534101.aspx">MSDN doc</a>)
 * @return the value of this property
 */
@JsxGetter
public int getLength() {
    final int all = getElements().getLength();
    final int images = getHtmlForm().getElementsByAttribute(HtmlInput.TAG_NAME, "type", "image").size();
    return all - images;
}
 
Example 20
Source Project: HtmlUnit-Android   Source File: WebAssert.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Verifies that the input element with the specified name on the specified page contains the
 * specified value.
 *
 * @param page the page to check
 * @param name the name of the input element to check
 * @param value the value to check for
 */
public static void assertInputContainsValue(final HtmlPage page, final String name, final String value) {
    final String xpath = "//input[@name='" + name + "']";
    final List<?> list = page.getByXPath(xpath);
    if (list.isEmpty()) {
        throw new AssertionError("Unable to find an input element named '" + name + "'.");
    }
    final HtmlInput input = (HtmlInput) list.get(0);
    final String s = input.getValueAttribute();
    if (!s.equals(value)) {
        throw new AssertionError("The input element named '" + name + "' contains the value '" + s
                        + "', not the expected value '" + value + "'.");
    }
}
 
Example 21
Source Project: HtmlUnit-Android   Source File: WebAssert.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Verifies that the input element with the specified name on the specified page does not
 * contain the specified value.
 *
 * @param page the page to check
 * @param name the name of the input element to check
 * @param value the value to check for
 */
public static void assertInputDoesNotContainValue(final HtmlPage page, final String name, final String value) {
    final String xpath = "//input[@name='" + name + "']";
    final List<?> list = page.getByXPath(xpath);
    if (list.isEmpty()) {
        throw new AssertionError("Unable to find an input element named '" + name + "'.");
    }
    final HtmlInput input = (HtmlInput) list.get(0);
    final String s = input.getValueAttribute();
    if (s.equals(value)) {
        throw new AssertionError("The input element named '" + name + "' contains the value '" + s
                        + "', not the expected value '" + value + "'.");
    }
}
 
Example 22
@Test
public void doReplace_should_trim_input() throws Exception {
    HtmlPage page = j.createWebClient().goTo("configuration-as-code");
    j.assertGoodStatus(page);

    HtmlForm form = page.getFormByName("replace");
    HtmlInput input = form.getInputByName("_.newSource");
    String configUri = getClass().getResource("merge3.yml").toExternalForm();
    input.setValueAttribute("  " + configUri + "  ");
    HtmlPage resultPage = j.submit(form);
    j.assertGoodStatus(resultPage);

    assertEquals("Configured by Configuration as Code plugin", j.jenkins.getSystemMessage());
}
 
Example 23
Source Project: kubernetes-plugin   Source File: KubernetesCloudTest.java    License: Apache License 2.0 5 votes vote down vote up
public HtmlInput getInputByName(DomElement root, String name) {
    DomNodeList<HtmlElement> inputs = root.getElementsByTagName("input");
    for (HtmlElement input : inputs) {
        if (name.equals(input.getAttribute("name"))) {
            return (HtmlInput) input;
        }
    }
    return null;
}
 
Example 24
@Test(groups = {"notLoggedIn"})
public void testRequiresUserRememberMe() throws Exception {
	clickOnBasePage("tynamoLoginLink");
	type("login", "psycho");
	type("password", "psycho");
	page.getForms().get(0).<HtmlInput> getInputByName("tynamoRememberMe").setChecked(true);
	click("tynamoEnter");
	webClient.getCookieManager().removeCookie(webClient.getCookieManager().getCookie("JSESSIONID"));
	assertNotNull(webClient.getCookieManager().getCookie("rememberMe"));
	clickOnBasePage("alphaServiceRequiresUser");
	assertSuccessInvoke();
	clickOnBasePage("alphaServiceRequiresAuthentication");
	assertLoginPage();
	webClient.getCookieManager().clearCookies();
}
 
Example 25
Source Project: juddi   Source File: Login.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void execute() throws Exception
{

    HtmlInput input0 = form.getInputByName("j_username");
    input0.setValueAttribute(username);

    HtmlInput input1 = form.getInputByName("j_password");
    input1.setValueAttribute(password);

    loadPageByClick(clickable, 10000);
}
 
Example 26
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 27
Source Project: htmlunit   Source File: Document.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new element with the given tag name.
 *
 * @param tagName the tag name
 * @return the new HTML element, or NOT_FOUND if the tag is not supported
 */
@JsxFunction
public Object createElement(String tagName) {
    Object result = NOT_FOUND;
    try {
        if (tagName.contains("<") || tagName.contains(">")) {
            if (LOG.isInfoEnabled()) {
                LOG.info("createElement: Provided string '"
                            + tagName + "' contains an invalid character; '<' and '>' are not allowed");
            }
            throw Context.reportRuntimeError("String contains an invalid character");
        }
        else if (tagName.length() > 0 && tagName.charAt(0) == '<' && tagName.endsWith(">")) {
            tagName = tagName.substring(1, tagName.length() - 1);

            final Matcher matcher = TAG_NAME_PATTERN.matcher(tagName);
            if (!matcher.matches()) {
                if (LOG.isInfoEnabled()) {
                    LOG.info("createElement: Provided string '" + tagName + "' contains an invalid character");
                }
                throw Context.reportRuntimeError("String contains an invalid character");
            }
        }

        final SgmlPage page = getPage();
        org.w3c.dom.Node element = page.createElement(tagName);

        if (element instanceof BaseFrameElement) {
            ((BaseFrameElement) element).markAsCreatedByJavascript();
        }
        else if (element instanceof HtmlInput) {
            ((HtmlInput) element).markAsCreatedByJavascript();
        }
        else if (element instanceof HtmlImage) {
            ((HtmlImage) element).markAsCreatedByJavascript();
        }
        else if (element instanceof HtmlRp) {
            ((HtmlRp) element).markAsCreatedByJavascript();
        }
        else if (element instanceof HtmlRt) {
            ((HtmlRt) element).markAsCreatedByJavascript();
        }
        else if (element instanceof HtmlScript) {
            ((HtmlScript) element).markAsCreatedByJavascript();
        }
        else if (element instanceof HtmlUnknownElement) {
            ((HtmlUnknownElement) element).markAsCreatedByJavascript();
        }
        else if (element instanceof HtmlSvg) {
            element = UnknownElementFactory.instance.createElementNS(page, "", "svg", null);
            ((HtmlUnknownElement) element).markAsCreatedByJavascript();
        }
        final Object jsElement = getScriptableFor(element);

        if (jsElement == NOT_FOUND) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("createElement(" + tagName
                    + ") cannot return a result as there isn't a JavaScript object for the element "
                    + element.getClass().getName());
            }
        }
        else {
            result = jsElement;
        }
    }
    catch (final ElementNotFoundException e) {
        // Just fall through - result is already set to NOT_FOUND
    }
    return result;
}
 
Example 28
Source Project: htmlunit   Source File: HTMLInputElement.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Sets the value of the attribute {@code type}.
 * Note: this replace the DOM node with a new one.
 * @param newType the new type to set
 */
@JsxSetter
public void setType(String newType) {
    HtmlInput input = getDomNodeOrDie();

    final String currentType = input.getAttributeDirect("type");

    final BrowserVersion browser = getBrowserVersion();
    if (!currentType.equalsIgnoreCase(newType)) {
        if (newType != null && browser.hasFeature(JS_INPUT_SET_TYPE_LOWERCASE)) {
            newType = newType.toLowerCase(Locale.ROOT);
        }

        if (!browser.hasFeature(HTMLINPUT_TYPE_DATETIME_SUPPORTED)
                && ("week".equals(newType)
                        || "month".equals(newType)
                        || "date".equals(newType)
                        || "datetime-local".equals(newType)
                        || "time".equals(newType))) {
            throw Context.reportRuntimeError("Invalid argument '" + newType + "' for setting property type.");
        }

        if (browser.hasFeature(HTMLINPUT_TYPE_COLOR_NOT_SUPPORTED)
                && "color".equals(newType)) {
            throw Context.reportRuntimeError("Invalid argument '" + newType + "' for setting property type.");
        }

        final AttributesImpl attributes = readAttributes(input);
        final int index = attributes.getIndex("type");
        if (index > -1) {
            attributes.setValue(index, newType);
        }
        else {
            attributes.addAttribute(null, "type", "type", null, newType);
        }

        // create a new one only if we have a new type
        if (ATTRIBUTE_NOT_DEFINED != currentType || !"text".equalsIgnoreCase(newType)) {
            final SgmlPage page = input.getPage();
            final HtmlInput newInput = (HtmlInput) page.getWebClient().getPageCreator().getHtmlParser()
                    .getFactory(HtmlInput.TAG_NAME)
                    .createElement(page, HtmlInput.TAG_NAME, attributes);

            if (input.wasCreatedByJavascript()) {
                newInput.markAsCreatedByJavascript();
            }

            if (input.getParentNode() == null) {
                // the input hasn't yet been inserted into the DOM tree (likely has been
                // created via document.createElement()), so simply replace it with the
                // new Input instance created in the code above
                input = newInput;
            }
            else {
                input.getParentNode().replaceChild(newInput, input);
            }

            input.setScriptableObject(null);
            setDomNode(newInput, true);
        }
        else {
            super.setAttribute("type", newType);
        }
    }
}
 
Example 29
Source Project: htmlunit   Source File: HTMLInputElement.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public HtmlInput getDomNodeOrDie() {
    return (HtmlInput) super.getDomNodeOrDie();
}
 
Example 30
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;
        }
    };
}