Example usage for org.openqa.selenium WebElement isDisplayed

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

Introduction

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

Prototype

boolean isDisplayed();

Source Link

Document

Is this element displayed or not?

Usage

From source file:dk.dma.ais.abnormal.web.EventsIT.java

License:Open Source License

@Test
public void navigateToSearchDialog() {
    try {//  w  ww .  jav  a2 s . com
        // Navigate to search dialog
        WebElement searchModal = browser.findElement(id("event-search-modal"));
        assertFalse(searchModal.isDisplayed());

        // Tab
        WebElement eventsTab = browser.findElement(id("tab-events"));
        eventsTab.click();

        // Button
        wait.until(visibilityOfElementLocated(id("events-search")));
        WebElement searchButton = browser.findElement(id("events-search"));
        searchButton.click();

        // Popup
        wait.until(visibilityOfElementLocated(id("event-search-modal")));
        wait.until(visibilityOfElementLocated(id("event-search-by-other")));
        assertTrue(searchModal.isDisplayed());

        // Ensure that "search-by-other" tab on search dialog is displayed
        WebElement searchByOtherButton = browser.findElement(id("event-search-by-other"));
        WebElement searchByIdButton = browser.findElement(id("event-search-by-id"));
        assertTrue(searchByOtherButton.isDisplayed());
        assertFalse(searchByIdButton.isDisplayed());
    } catch (AssertionError e) {
        IntegrationTestHelper.takeScreenshot(browser, "error");
        throw e;
    } catch (WebDriverException e) {
        IntegrationTestHelper.takeScreenshot(browser, "error");
        throw e;
    }
}

From source file:Domain.Story2.java

@Test
public void testSearchProduct() {
    driver.get("http://store.demoqa.com/");
    //Clear the search form
    driver.findElement(By.className("search")).clear();
    //Input "Magic" in the search form
    driver.findElement(By.className("search")).sendKeys("Magic" + Keys.RETURN);
    //Wait page forward to product detail page              
    waitUntil(d -> d.findElement(By.linkText("Magic Mouse")).isDisplayed());

    try {/*from   w  w w . j a  v a2  s . c om*/
        //Find the "Magic Mouse" Product link
        WebElement ProductGroup = driver.findElement(By.linkText("Magic Mouse"));
        assertTrue(ProductGroup.isDisplayed());
    } catch (NoSuchElementException nseex) {
        fail();
    }
    driver.manage().deleteAllCookies();
}

From source file:Domain.Story3.java

@Test
public void testRemoveItem() {
    driver.get("http://store.demoqa.com/products-page/product-category/");
    //Find the "Add to Cart" button of the first product and click it
    driver.findElements(By.className("wpsc_buy_button")).get(0).click();
    //Wait adding to cart
    waitUntil(d -> d.findElement(By.linkText("Go to Checkout")).isDisplayed());
    //Click the "Go to Checkout" button in the alert window
    driver.findElement(By.linkText("Go to Checkout")).click();
    //Wait page forward to checkout page
    waitUntil(d -> d.findElement(By.xpath("//input[@value='Remove']")).isDisplayed());
    //Click the remove button
    driver.findElement(By.xpath("//input[@value='Remove']")).click();
    //Wait the remove process finished
    waitUntil(d -> d.findElement(By.className("entry-content")).isDisplayed());

    try {//from  ww  w  . ja  va  2 s .  c  o m
        //Find the empty infos
        WebElement emptyContent = driver.findElement(By.className("entry-content"));
        assertTrue(emptyContent.isDisplayed());
    } catch (NoSuchElementException nseex) {
        fail();
    }
}

From source file:edu.samplu.common.WebDriverLegacyITBase.java

License:Educational Community License

protected List<WebElement> findVisibleElements(By by) {
    List<WebElement> webElements = driver.findElements(by);
    List<WebElement> visibleWebElements = new LinkedList<WebElement>();
    for (WebElement webElement : webElements) {
        if (webElement.isDisplayed()) {
            visibleWebElements.add(webElement);
        }/*from w  ww .  ja v  a2  s . c  om*/
    }

    return visibleWebElements;
}

From source file:edu.samplu.common.WebDriverLegacyITBase.java

License:Educational Community License

protected int howManyAreVisible(By by) throws InterruptedException {
    int count = 0;
    if (by == null) {

        return count;
    }//  w  w  w  .j av a  2 s.c om

    List<WebElement> webElementsFound = driver.findElements(by);
    for (WebElement webElement : webElementsFound) {
        if (webElement.isDisplayed()) {
            count++;
        }
    }

    return count;
}

From source file:edu.samplu.common.WebDriverLegacyITBase.java

License:Educational Community License

protected boolean isVisible(By by) {
    List<WebElement> elements = driver.findElements(by);
    for (WebElement element : elements) {
        if (element.isDisplayed()) {
            return true;
        }//from ww  w.j av  a  2  s .co m
    }
    return false;
}

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   w w w.  j  a  v a2  s.  c  o m
    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.
 * // ww  w .  ja  v 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;
}

From source file:edu.umd.cs.guitar.crawljax.ripper.plugin.GUITARWebEventMonitorPlugin.java

License:Open Source License

/**
 * Collect all events available in the current session
 * @param session//from  ww  w  .ja  v  a  2  s. c  o m
 */
private Map<WebElement, Set<Class<? extends GEvent>>> collectEventableWebElmenent(CrawlSession session) {
    Map<WebElement, Set<Class<? extends GEvent>>> eventActionMap = new HashMap<WebElement, Set<Class<? extends GEvent>>>();

    for (Class<? extends GEvent> gEvent : manager.getSupportedEvents()) {
        // Setup event specification
        EventSpecification spec = manager.getEventSpecification(gEvent);
        try {
            List<CandidateElement> candidateList = getCandidateElementList(spec, session);
            for (CandidateElement element : candidateList) {
                EmbeddedBrowser browser = session.getBrowser();
                try {
                    WebElement webElement = browser.getWebElement(element.getIdentification());

                    // We ignore the invisible and disabled element
                    if (!webElement.isDisplayed() || !webElement.isEnabled())
                        continue;

                    Set<Class<? extends GEvent>> supportedEventSet = eventActionMap.get(webElement);

                    if (supportedEventSet == null) {
                        supportedEventSet = new HashSet<Class<? extends GEvent>>();
                    }

                    supportedEventSet.add(gEvent);
                    eventActionMap.put(webElement, supportedEventSet);

                } catch (org.openqa.selenium.NoSuchElementException noElementException) {

                    LOGGER.debug("WebElement is not accessable");
                    LOGGER.debug("Identification: " + element.getIdentification());

                }
            } // end capture all GEvent

        } catch (CrawljaxException e) {
            LOGGER.debug("CrawljaxException" + e.getMessage());
        }
    }
    return eventActionMap;
}

From source file:edu.umd.cs.guitar.model.WebEventAnalyzer.java

License:Open Source License

/**
 * Analyze a web element and extract all replayable event
 *
 * <p>// w w  w .ja va 2  s. com
 *
 * @param element
 * @return a look up table for all replayable events and widgets
 */
public GUIMap extractEvents(WebElement element) {
    GUIMap map = factory.createGUIMap();

    WidgetMapTypeWrapper widgetMap = new WidgetMapTypeWrapper(factory.createWidgetMapType());
    EventMapTypeWrapper eventMap = new EventMapTypeWrapper(factory.createEventMapType());

    // List<WebElement> children = element.findElements(By.cssSelector("*"));
    List<WebElement> children = element.findElements(By.xpath(".//*"));
    List<WebElement> childrenEnabled = new ArrayList<WebElement>();

    for (WebElement aChild : children) {
        try {
            if (!aChild.isEnabled() || !(aChild.isDisplayed()))
                continue;
        } catch (StaleElementReferenceException exception) {
            LOGGER.error(exception);
        }
        childrenEnabled.add(aChild);
    }
    children = childrenEnabled;

    LOGGER.info("TOTAL visible element to explore: " + children.size());

    for (WebElement aChild : children) {
        if (!aChild.isEnabled() || !(aChild.isDisplayed()))
            continue;
        WebComponent gComponent = new WebComponent(aChild, null, null, null);

        if (hasEventSupported(gComponent)) {
            long hashcode = getHashCode(aChild);

            String widgetID = GUITARConstants.COMPONENT_ID_PREFIX + hashcode;

            if (!widgetMap.contains(widgetID)) {
                // create lookup widget
                WidgetMapElementType widgetElement = factory.createWidgetMapElementType();
                ComponentType componentData = gComponent.extractProperties();
                ComponentTypeWrapper componentDataWrapper = new ComponentTypeWrapper(componentData);
                componentDataWrapper.addProperty(GUITARConstants.ID_TAG_NAME, widgetID);
                componentData = componentDataWrapper.getDComponentType();
                widgetElement.setComponent(componentData);
                widgetElement.setWidgetId(widgetID);

                widgetMap.getWidgetMapElement().add(widgetElement);
            }

            for (GEvent event : eventManager.getEvents()) {
                if (event.isSupportedBy(gComponent)) {
                    String eventID = GUITARConstants.EVENT_ID_PREFIX + hashcode;
                    if (!eventMap.contains(eventID)) {
                        EventType eventElement = factory.createEventType();

                        // event id 
                        eventElement.setEventId(eventID);
                        // widget id
                        eventElement.setWidgetId(widgetID);
                        // action
                        String action = event.getClass().getName();
                        eventElement.setAction(action);

                        eventMap.getEventMapElement().add(eventElement);
                    }
                }
            }
        }
    }

    map.setWidgetMap(widgetMap);
    map.setEventMap(eventMap);
    return map;
}