com.gargoylesoftware.htmlunit.html.HtmlInput Java Examples

The following examples show how to use com.gargoylesoftware.htmlunit.html.HtmlInput. 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: HTMLInputElement.java    From htmlunit with 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 #2
Source File: Window.java    From HtmlUnit-Android with 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 #3
Source File: HTMLInputElement.java    From HtmlUnit-Android with 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 #4
Source File: HTMLInputElement.java    From HtmlUnit-Android with 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 #5
Source File: HTMLInputElement.java    From htmlunit with 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 #6
Source File: KubernetesCloudTest.java    From kubernetes-plugin with 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 #7
Source File: Window.java    From htmlunit with 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 #8
Source File: ConfigurationAsCodeTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@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 #9
Source File: KubernetesCloudTest.java    From kubernetes-plugin with 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 #10
Source File: HTMLCollection.java    From HtmlUnit-Android with 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 #11
Source File: WebAssert.java    From HtmlUnit-Android with 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 #12
Source File: WebAssert.java    From HtmlUnit-Android with 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 File: HTMLFormElement.java    From HtmlUnit-Android with 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 #14
Source File: HTMLInputElement.java    From HtmlUnit-Android with 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 #15
Source File: TapestrySecurityIntegrationTest.java    From tapestry-security with Apache License 2.0 5 votes vote down vote up
@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 #16
Source File: Login.java    From juddi with 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 #17
Source File: HTMLInputElement.java    From HtmlUnit-Android with 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 File: NodeChangeListenerTest.java    From audit-log-plugin with 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 #19
Source File: HTMLCollection.java    From htmlunit with 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 #20
Source File: CSSStyleSheet2Test.java    From htmlunit with 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 #21
Source File: WebAssert.java    From htmlunit with 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
Source File: WebAssert.java    From htmlunit with 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 #23
Source File: HTMLFormElement.java    From htmlunit with 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 #24
Source File: HTMLInputElement.java    From htmlunit with 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 #25
Source File: HTMLInputElement.java    From htmlunit with 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 #26
Source File: JmxWebHandlerTest.java    From simplejmx with ISC License 4 votes vote down vote up
@Test(timeout = 10000)
public void testSimple() throws Exception {
	WebClient webClient = new WebClient();
	HtmlPage page = webClient.getPage("http://" + WEB_SERVER_NAME + ":" + WEB_SERVER_PORT);
	assertTrue(page.asText().contains("JMX Domains"));

	String domain = "java.lang";
	HtmlAnchor anchor = page.getAnchorByText(domain);
	assertNotNull(anchor);
	page = anchor.click();
	assertTrue(page.asText().contains("Beans in domain " + domain));

	anchor = page.getAnchorByName("text");
	TextPage textPage = anchor.click();
	String bean = "type=Memory";
	assertTrue(textPage.getContent().contains(domain + ":" + bean));

	anchor = page.getAnchorByText(bean);
	page = anchor.click();
	assertTrue(page.asText().contains("Information about object " + domain + ":" + bean));

	anchor = page.getAnchorByName("text");
	textPage = anchor.click();
	assertTrue(textPage.getContent().contains("Verbose"));

	HtmlForm form = page.getFormByName("Verbose");
	assertNotNull(form);
	HtmlInput input = form.getInputByName("val");
	assertEquals("false", input.getValueAttribute());
	assertNotNull(input);
	input.setValueAttribute("true");
	HtmlElement button = (HtmlElement) page.createElement("button");
	button.setAttribute("type", "submit");
	// append the button to the form to simulate
	form.appendChild(button);
	// submit the form
	page = button.click();
	assertTrue(page.asText().contains("Information about object " + domain + ":" + bean));

	form = page.getFormByName("Verbose");
	assertNotNull(form);
	input = form.getInputByName("val");
	assertEquals("true", input.getValueAttribute());

	String operation = "gc";
	form = page.getFormByName(operation);
	assertNotNull(form);
	input = form.getInputByValue(operation);
	page = input.click();

	assertTrue(page.asText().contains("Invoking Operation " + operation));
	assertTrue(page.asText().contains(operation + " method successfully invoked."));

	anchor = page.getAnchorByName("text");
	assertNotNull(anchor);
	textPage = anchor.click();
	assertEquals(operation + " method successfully invoked.\n", textPage.getContent());
}
 
Example #27
Source File: Document.java    From htmlunit with 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 File: TapestrySecurityIntegrationTest.java    From tapestry-security with Apache License 2.0 4 votes vote down vote up
private void type(String id, String value)
{
	page.getForms().get(0).<HtmlInput>getInputByName(id).setValueAttribute(value);
}
 
Example #29
Source File: GSWorker.java    From slr-toolkit with 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;
}
 
Example #30
Source File: HTMLInputElement.java    From htmlunit with 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);
        }
    }
}