Example usage for org.openqa.selenium WebElement isEnabled

List of usage examples for org.openqa.selenium WebElement isEnabled

Introduction

In this page you can find the example usage for org.openqa.selenium WebElement isEnabled.

Prototype

boolean isEnabled();

Source Link

Document

Is the element currently enabled or not?

Usage

From source file:com.thoughtworks.selenium.webdriven.commands.IsEditable.java

License:Apache License

@Override
protected Boolean handleSeleneseCommand(WebDriver driver, String locator, String value) {
    WebElement element = finder.findElement(driver, locator);
    String tagName = element.getTagName().toLowerCase();
    boolean acceptableTagName = "input".equals(tagName) || "select".equals(tagName);
    String readonly = "";
    if ("input".equals(tagName)) {
        readonly = element.getAttribute("readonly");
        if (readonly == null || "false".equals(readonly)) {
            readonly = "";
        }//  w w  w  .j a  v a  2  s. c  om
    }

    return element.isEnabled() && acceptableTagName && "".equals(readonly);
}

From source file:com.vaadin.testbench.TestBenchElementTest.java

@Test
public void testIsEnabled_VaadinComponentEnabled_inputDisabled_returnsFalse() throws Exception {
    // This would probably never happen, but just make sure it works
    WebElement webElement = createMock(WebElement.class);
    expect(webElement.getAttribute("class")).andStubReturn("v-textfield");
    expect(webElement.isEnabled()).andReturn(false);
    replay(webElement);//from  ww  w. j  a va  2  s.co m

    TestBenchElement element = TestBenchElement.wrapElement(webElement, null);
    assertFalse(element.isEnabled());

    verify(webElement);
}

From source file:com.vaadin.testbench.TestBenchElementTest.java

@Test
public void testIsEnabled_VaadinComponentEnabled_inputEnabled_returnsTrue() throws Exception {
    WebElement webElement = createMock(WebElement.class);
    expect(webElement.getAttribute("class")).andStubReturn("v-textfield");
    expect(webElement.isEnabled()).andReturn(true);
    replay(webElement);//w  ww .  j  a va 2  s  .  c om

    TestBenchElement element = TestBenchElement.wrapElement(webElement, null);
    assertTrue(element.isEnabled());

    verify(webElement);
}

From source file:dagaz.controllers.ChildController.java

private void betNow() {
    if (isAboutToClose()) {
        WebElement btnBet = driver.findElement(By.id("choose-" + config.getBetSide(arena).toLowerCase()));
        config.getRoot().appendDetails("- [" + arena + "] - [" + match.getMatchNumber() + "]");
        config.getRoot().appendDetails(//from   ww w.j  a va2s.co  m
                "\tMeron Bet Rate: " + match.getHomeBetRate() + " - Trend: " + match.getHomeBetTrend());
        config.getRoot().appendDetails(
                "\tWala Bet Rate: " + match.getAwayBetRate() + " - Trend: " + match.getAwayBetTrend());
        config.getRoot().appendDetails(
                "\tDraw Bet Rate: " + match.getDrawBetRate() + " - Trend: " + match.getDrawBetTrend());
        if (btnBet.isEnabled() && isMatchCondition()) {
            btnBet.click();
            driver.findElement(By.id("input-stake")).sendKeys(config.getBetCoin(arena));
            driver.findElement(By.id("place-bet")).click();
            closeDialog();
            config.getRoot().appendDetails(
                    "\tSide: " + config.getBetSide(arena) + " - Coin: " + config.getBetCoin(arena));
            config.getRoot().appendDetails("\tPlace bet after " + match.getBetOpenElapsedTime() + "s");
            match.setIsPlaced(true);
        } else {
            config.getRoot().appendDetails("\tSkippppp...........Not match the condition.");
            match.setIsPlaced(true);
        }
    }
    if (!isConnectionReady() && match.getBetOpenElapsedTime() > 40) {
        WebElement btnBet = driver.findElement(By.id("choose-" + config.getBetSide(arena).toLowerCase()));
        config.getRoot().appendDetails("- [" + arena + "] - [" + match.getMatchNumber() + "]");
        config.getRoot().appendDetails(" ---- Connection trouble ----");
        config.getRoot().appendDetails(
                "\tMeron Bet Rate: " + match.getHomeBetRate() + " - Trend: " + match.getHomeBetTrend());
        config.getRoot().appendDetails(
                "\tWala Bet Rate: " + match.getAwayBetRate() + " - Trend: " + match.getAwayBetTrend());
        config.getRoot().appendDetails(
                "\tDraw Bet Rate: " + match.getDrawBetRate() + " - Trend: " + match.getDrawBetTrend());
        if (btnBet.isEnabled() && isMatchCondition()) {
            btnBet.click();
            driver.findElement(By.id("input-stake")).sendKeys(config.getBetCoin(arena));
            driver.findElement(By.id("place-bet")).click();
            closeDialog();
            config.getRoot().appendDetails(
                    "\tSide: " + config.getBetSide(arena) + " - Coin: " + config.getBetCoin(arena));
            config.getRoot().appendDetails("\tPlace bet after " + match.getBetOpenElapsedTime() + "s");
            match.setIsPlaced(true);
        } else {
            config.getRoot().appendDetails("\tSkippppp...........Not match the condition.");
            match.setIsPlaced(true);
        }
    }
}

From source file:de.learnlib.alex.data.entities.actions.web.ClickElementByTextAction.java

License:Apache License

@Override
protected ExecuteResult execute(WebSiteConnector connector) {
    final WebElementLocator nodeWithVariables = new WebElementLocator(insertVariableValues(node.getSelector()),
            node.getType());/*w ww. ja  va2 s  .  c  o m*/

    final WebElement root = connector.getElement(nodeWithVariables);
    final String textWithVariables = insertVariableValues(text);

    final List<WebElement> candidates;
    if (tagName == null || tagName.trim().equals("")) {
        candidates = root.findElements(By.xpath("//text()[normalize-space() = '" + textWithVariables + "']"));
    } else {
        candidates = root.findElements(By.tagName(tagName));
    }

    try {
        if (candidates.isEmpty()) {
            throw new NoSuchElementException("No candidate with text '" + textWithVariables + "' found.");
        }

        for (final WebElement candidate : candidates) {
            final boolean hasText = candidate.getText().trim().equals(textWithVariables);
            if (candidate.isDisplayed() && candidate.isEnabled() && hasText) {
                candidate.click();

                LOGGER.info(LoggerMarkers.LEARNER, "Click on element '{}' with text '{}' ", tagName, text);
                return getSuccessOutput();
            }
        }
        throw new NoSuchElementException("No clickable element found.");
    } catch (Exception e) {
        LOGGER.info(LoggerMarkers.LEARNER, "Could not click on element '{}' with text '{}' ", tagName, text, e);
        return getFailedOutput();
    }
}

From source file:de.learnlib.alex.data.entities.actions.web.ClickElementByTextActionTest.java

License:Apache License

@Test
public void itShouldClickOnTheFirstClickableElement() {
    final WebElement button1 = mock(WebElement.class);
    given(button1.getText()).willReturn(TEXT);

    final WebElement button2 = mock(WebElement.class);
    given(button1.getText()).willReturn(TEXT);

    final List<WebElement> elements = new ArrayList<>();
    elements.add(button1);/*w w w .  ja va 2s .  co  m*/
    elements.add(button2);

    given(button1.isDisplayed()).willReturn(false);
    given(button2.getText()).willReturn(TEXT);
    given(button2.isDisplayed()).willReturn(true);
    given(button2.isEnabled()).willReturn(true);
    given(container.findElements(By.tagName(TAG_NAME))).willReturn(elements);

    final ExecuteResult result = action.executeAction(connectors);
    assertTrue(result.isSuccess());

    verify(button1, never()).click();
    verify(button2).click();
}

From source file:de.learnlib.alex.data.entities.actions.web.WaitForNodeAction.java

License:Apache License

@Override
protected ExecuteResult execute(WebSiteConnector connector) {
    if (maxWaitTime < 0) {
        return getFailedOutput();
    }//  w  ww  . ja v a  2s.c om

    final WebDriverWait wait = new WebDriverWait(connector.getDriver(), maxWaitTime);
    final WebElementLocator nodeWithVariables = new WebElementLocator(insertVariableValues(node.getSelector()),
            node.getType());

    try {
        LOGGER.info(LoggerMarkers.LEARNER, "Wait for element '{}' (criterion: '{}').", nodeWithVariables,
                waitCriterion);
        switch (waitCriterion) {
        case VISIBLE:
            wait.until(wd -> connector.getElement(nodeWithVariables).isDisplayed());
            break;
        case INVISIBLE:
            wait.until(wd -> !connector.getElement(nodeWithVariables).isDisplayed());
            break;
        case ADDED:
            wait.until(wd -> {
                try {
                    connector.getElement(nodeWithVariables);
                    return true;
                } catch (Exception e) {
                    return false;
                }
            });
            break;
        case REMOVED:
            wait.until(wd -> {
                try {
                    connector.getElement(nodeWithVariables);
                    return false;
                } catch (Exception e) {
                    return true;
                }
            });
            break;
        case CLICKABLE:
            wait.until(wd -> {
                final WebElement element = connector.getElement(nodeWithVariables);
                return element.isDisplayed() && element.isEnabled();
            });
            break;
        default:
            return getFailedOutput();
        }
        return getSuccessOutput();
    } catch (TimeoutException e) {
        LOGGER.info(LoggerMarkers.LEARNER, "Waiting on the node '{}' (criterion: '{}') timed out.",
                nodeWithVariables, waitCriterion);
        return getFailedOutput();
    } catch (NoSuchElementException e) {
        LOGGER.info(LoggerMarkers.LEARNER,
                "The node with the selector {} (criterion: '{}') could not be found.", nodeWithVariables,
                waitCriterion);
        return getFailedOutput();
    }
}

From source file:DerpSelenium.test.java

public static void info(String name, WebElement element) {
    print("Element name = " + name);
    print("Element.isDisplayed = " + element.isDisplayed());
    print("Element.isEnabled = " + element.isEnabled());
    print("Element.isSeleceted = " + element.isSelected());

}

From source file:edu.uga.cs.clickminer.BrowserEngine.java

License:Open Source License

private ElementSearchResult clickJSElementFromSearchResults(String windowHandle,
        List<ElementSearchResult> searchResults, String requrl) throws ProxyErrorException {
    ElementSearchResult retval = null;/*from  www .j  a  v a  2  s.  c  om*/
    outer: for (ElementSearchResult result : searchResults) {
        FramePath fp = result.getFramePath();
        List<WebElement> elements = result.getMatchingElements();
        FrameUtils.traverseFramePath(wdriver, fp);
        String referer = wdriver.getCurrentUrl();

        //disable javascript dialog windows
        JSUtils.disableAlerts(wdriver);
        JSUtils.autoAcceptConfirm(wdriver);
        JSUtils.autoReturnPrompt(wdriver);

        for (WebElement element : elements) {
            try {
                if (element.isDisplayed() && element.isEnabled()) {
                    //we set the element id if it doesn't exist to make indexing easier
                    String elemid = element.getAttribute("id");
                    if (elemid == null) {
                        elemid = "elem" + (System.currentTimeMillis() / 1000L)
                                + (int) (Math.random() * Integer.MAX_VALUE);
                        JSUtils.setElementAttribute(wdriver, element, "id", elemid);
                    }

                    //check the jsClickIndex
                    if (jsClickIndex.entryExists(windowHandle, result.getFramePath(), elemid) && jsClickIndex
                            .getEntry(windowHandle, result.getFramePath(), elemid).equals(requrl)) {
                        if (log.isInfoEnabled()) {
                            log.info("Found matching javascript element via index.");
                        }
                        retval = result.copy();
                        List<WebElement> elems = new ArrayList<WebElement>();
                        elems.add(element);
                        retval.setMatchingElements(elems);
                        break outer;
                    }

                    Set<String> oldhandles = wdriver.getWindowHandles();
                    try {
                        element.click();
                    } catch (Exception e) {
                        if (log.isErrorEnabled()) {
                            log.error("Error clicking on element. Skipping.", e);
                        }
                        continue;
                    }
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        if (log.isWarnEnabled()) {
                            log.warn(e);
                        }
                    }

                    //close any windows the click might have opened
                    Set<String> newhandles = wdriver.getWindowHandles();
                    newhandles.removeAll(oldhandles);
                    if (newhandles.size() > 0) {
                        for (String handle : newhandles) {
                            try {
                                wdriver.switchTo().window(handle);
                                wdriver.close();
                            } catch (Exception e) {
                                if (log.isWarnEnabled()) {
                                    log.warn(e);
                                }
                            }
                        }
                        wdriver.switchTo().window(windowHandle);
                    }

                    //update the jsClickIndex
                    String url = pclient.getLastRequestByReferer(referer);
                    if (url != null) {
                        jsClickIndex.setEntry(windowHandle, result.getFramePath(), elemid, url);
                    }

                    ProxyMode pmode = pclient.getMode();
                    if (pmode == ProxyMode.CONTENT) {
                        if (log.isInfoEnabled()) {
                            log.info("Found matching javascript element by clicking.");
                        }
                        retval = result.copy();
                        List<WebElement> elems = new ArrayList<WebElement>();
                        elems.add(element);
                        retval.setMatchingElements(elems);
                        break outer;
                    }
                }
            } catch (Exception e) {
                if (log.isErrorEnabled()) {
                    log.error("Error activating javascript click element. Skipping.", e);
                }
            }
        }
    }
    return retval;
}

From source file:edu.uga.cs.clickminer.BrowserEngine.java

License:Open Source License

/**
 * Activates a clickable a html element from the list of search results and
 * generates an InteractionRecord object of the interaction. Activating the
 * element depends on the element's type. Form elements have their fields
 * filled from the content of the request and submitted. An element besides
 * an object or an embed whose target attribute is a frame within the
 * current window has a click event sent to it. In all other cases the url
 * of the request is submitted to the address bar of a new window.
 * /*from   w w  w  .  jav a  2s  .co m*/
 * @param req
 *            the request
 * @return true, if successful an element was found and activated, false
 *         otherwise
 */
private InteractionRecord activateTargetElementFromResults(List<ElementSearchResult> searchResults,
        PageEntry pageentry, MitmHttpRequest req) {

    // If the element contains the url in the request then it must be
    // clickable or submittable

    // get the names of the frames in the current frames
    wdriver.switchTo().defaultContent();
    List<String> fnames = FrameUtils.getAllFrameNames(wdriver);
    fnames.add("_self");
    fnames.add("_parent");

    ElementSearchResult selectedResult = searchResults.get(0);
    if (!selectedResult.matchesInDefaultFrame()) {
        FrameUtils.traverseFramePath(wdriver, selectedResult.getFramePath());
    }

    WebElement selelem = null;
    for (WebElement elem : selectedResult.getMatchingElements()) {
        if (elem.isDisplayed() && elem.isEnabled()) {
            selelem = elem;
            break;
        }
    }
    if (selelem == null) {
        selelem = selectedResult.getMatchingElements().get(0);
    }
    FrameEntry selectedFrame = pageentry.getMatchingFrameEntry(selectedResult.getFramePath().getUrls());
    ElementEntry selectedElement = selectedFrame.getMatchingElementEntry(selelem);
    if (log.isInfoEnabled()) {
        log.info("Activating element tag: " + selelem.getTagName() + " locator: "
                + selectedElement.getLocatorString());
    }

    Set<String> oldWinHandles = wdriver.getWindowHandles();
    String seltagname = selelem.getTagName().toLowerCase();

    // TODO must take the target of the base tag into account.
    String seltagtarget = selelem.getAttribute("target");

    String newWinHandle = null;

    if (log.isInfoEnabled()) {
        log.info("Element target: " + seltagtarget);
    }

    if (seltagname.equals("form")) {
        submitFormElement(selelem, req.getContent());
    } else if ((fnames.contains(seltagtarget)
            || (seltagtarget == null && !selectedResult.matchesInDefaultFrame()))
            && !objectHTMLElements.contains(seltagname) && selelem.isDisplayed() && selelem.isEnabled()) {
        // The frame is supposed to alter the current page in someway
        // which could alter the presence of elements within the DOM
        // and search order of the windows.

        try {
            selelem.click();
        } catch (Exception e) {
            if (log.isErrorEnabled()) {
                log.error("Error clicking on element.  " + "Opening url in new window.", e);
            }
            newWinHandle = this.openUrlInNewWindow(req.getUrl());
        }
    } else {
        // open all non-form elements in a new window
        // we do this to deal with force opening tabs
        // and caching
        newWinHandle = this.openUrlInNewWindow(req.getUrl());
    }

    // TODO might want to change this from a sleep
    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    Set<String> newWinHandles = wdriver.getWindowHandles();

    InteractionRecord irecord = null;

    if (newWinHandles.size() != oldWinHandles.size()) {
        if (newWinHandle == null) {
            newWinHandles.removeAll(oldWinHandles);
            newWinHandle = newWinHandles.iterator().next();
        }
        PageEntry destpage = PageEntry.getPageEntry(wdriver, windowIMap, newWinHandle);
        irecord = new InteractionRecord(ResultLocation.NEW_WINDOW, req, destpage);
    } else {
        PageEntry destpage = PageEntry.getPageEntry(wdriver, windowIMap, pageentry.getWindow().getWindowID());
        irecord = new InteractionRecord(ResultLocation.CURRENT_WINDOW, req, destpage);
    }

    selectedElement.setSelected(true);
    irecord.addPageEntry(pageentry);

    String windowhandle = wdriver.getWindowHandle();

    // update the ts for the window we are interacting with
    windowIMap.updateWindow(windowhandle);
    framePathIndex.updateIndex(windowhandle, windowIMap.getWindowTimestamp(windowhandle));

    // update the ts for any new windows opened
    Set<String> newWindows = windowIMap.updateNewWindows(windowhandle);
    for (String window : newWindows) {
        framePathIndex.updateIndex(window, windowIMap.getWindowTimestamp(window));
    }

    //Dismiss any alerts.
    try {
        Alert alert = wdriver.switchTo().alert();
        alert.dismiss();
    } catch (NoAlertPresentException e) {
        if (log.isDebugEnabled()) {
            log.debug("No modal dialogs, skipping");
        }
    } catch (Exception e1) {
        if (log.isErrorEnabled()) {
            log.error("Could not dismiss dialog", e1);
        }
    }
    // After the click, must always switch back to the default content.
    wdriver.switchTo().window(windowhandle);
    wdriver.switchTo().defaultContent();

    return irecord;
}