Example usage for org.openqa.selenium.interactions Actions moveToElement

List of usage examples for org.openqa.selenium.interactions Actions moveToElement

Introduction

In this page you can find the example usage for org.openqa.selenium.interactions Actions moveToElement.

Prototype

public Actions moveToElement(WebElement target, int xOffset, int yOffset) 

Source Link

Document

Moves the mouse to an offset from the center of the element.

Usage

From source file:org.finra.jtaf.ewd.widget.element.InteractiveElement.java

License:Apache License

@Override
public void mouseMoveOut() throws WidgetException {
    try {//w w w. j  a  va2s  . com
        // TODO: Need to figure out whether 10 is sufficient
        int offsetAmount = 10;

        WebElement elem = getWebElement();
        Dimension dim = elem.getSize();
        int width = dim.getWidth();
        Actions builder = new Actions(getGUIDriver().getWrappedDriver());
        synchronized (InteractiveElement.class) {
            getGUIDriver().focus();
            builder.moveToElement(getWebElement(), width + offsetAmount, 0).build().perform();
        }
    } catch (Exception e) {
        throw new WidgetException("Error while performing mouse move out", getLocator(), e);
    }
}

From source file:org.openecomp.sdc.ci.tests.execute.resourceui.VFCanvasTest.java

License:Open Source License

@Test
public void VFCanvasTest1() throws Exception {
    // GeneralUIUtils.waitForContainsdataTestIdVisibility("left-sectioin-element-QA");

    GeneralUIUtils.moveToStep(StepsEnum.COMPOSITION);
    Thread.sleep(2000);/*w  ww .j  a  v a 2 s . c  o m*/
    List<Integer> position = null;
    WebElement canvas = GeneralUIUtils.getWebElementWaitForVisible("canvas");
    int xPos = 0;
    int yPos = 0;
    position = getposition(canvas, xPos, yPos);
    WebElement otherElement = GeneralUIUtils
            .getWebElementWaitForVisible("left-sectioin-element-QA left-section-NeutronPort");
    for (int i = 0; i < 8; i++) {
        Actions builder = new Actions(GeneralUIUtils.getDriver());
        Action dragAndDrop = builder.clickAndHold(otherElement)
                .moveToElement(canvas, position.get(0), position.get(1)).release().build();
        dragAndDrop.perform();
        Thread.sleep(2000);
    }
    Thread.sleep(2000);
    Actions builder = new Actions(GeneralUIUtils.getDriver());
    builder.moveToElement(canvas, position.get(0), position.get(1));
    builder.clickAndHold();
    position = getposition(canvas, xPos, yPos);
    builder.moveToElement(canvas, position.get(0), position.get(1));
    builder.release();
    builder.build();
    builder.perform();
    builder.moveToElement(canvas, 200, 300);
    builder.release();
    builder.perform();

}

From source file:org.opennms.smoketest.OpenNMSSeleniumTestCase.java

License:Open Source License

protected void clickMenuItem(final String menuItemText, final String submenuItemText,
        final String submenuItemHref) {
    final Actions action = new Actions(m_driver);

    final WebElement menuElement;
    if (menuItemText.startsWith("name=")) {
        final String menuItemName = menuItemText.replaceFirst("name=", "");
        menuElement = findElementByName(menuItemName);
    } else {//from   ww w.  j a v  a 2 s  .c om
        menuElement = findElementByXpath("//a[contains(text(), '" + menuItemText + "')]");
    }
    action.moveToElement(menuElement, 2, 2).perform();

    final WebElement submenuElement;
    if (submenuItemText != null) {
        if (submenuItemHref == null) {
            submenuElement = findElementByXpath("//a[contains(text(), '" + submenuItemText + "')]");
        } else {
            submenuElement = findElementByXpath(
                    "//a[@href='" + submenuItemHref + "' and contains(text(), '" + submenuItemText + "')]");
        }
    } else {
        submenuElement = null;
    }

    if (submenuElement == null) {
        // no submenu given, just click the main element
        // wait until the element is visible, not just present in the DOM
        wait.until(ExpectedConditions.visibilityOf(menuElement));
        menuElement.click();
    } else {
        // we want a submenu item, click it instead
        // wait until the element is visible, not just present in the DOM
        wait.until(ExpectedConditions.visibilityOf(submenuElement));
        submenuElement.click();
    }
}

From source file:org.qe4j.web.OpenWebDriver.java

License:Open Source License

/**
 * Uses Selenium Actions to move the mouse over the center of the element
 * specified.//from   ww  w .  ja  v a 2 s.  c o  m
 *
 * @param by
 */
public void mouseOver(By by) {
    Actions actions = new Actions(webDriver);
    WebElement element = findElement(by);
    log.info("mouse over " + OpenWebElement.extractElementInfo(element));
    Dimension dimension = element.getSize();
    actions.moveToElement(element, dimension.width / 2, dimension.height / 2);
    actions.build().perform();
}

From source file:org.qe4j.web.OpenWebElement.java

License:Open Source License

/**
 * Performs a mouseover action relative to this element.
 *
 * @param by//from www  . j a v  a  2 s  .  c o  m
 */
public void mouseOver(By by) {
    Actions actions = new Actions(webDriver);
    WebElement element = webElement.findElement(by);
    Dimension dimension = element.getSize();
    actions.moveToElement(element, dimension.width / 2, dimension.height / 2);
    actions.build().perform();
}

From source file:org.richfaces.tests.metamer.ftest.richPanelMenuGroup.TestPanelMenuGroupDOMEventHandlers.java

License:Open Source License

@Test
@CoversAttributes("onmouseover")
@Templates(value = "plain")
public void testOnmouseover() {
    //This test should be done first, because use static x and y variables
    panelMenuGroupAttributes.set(mode, client);
    Actions mouseover = new Actions(driver).moveToElement(getPage().getRequestTimeElement());
    mouseover.moveToElement(getPage().getTopGroup().advanced().getHeaderElement(), 3, 3);
    testFireEvent(panelMenuGroupAttributes, onmouseover, mouseover.build());
}

From source file:org.safs.selenium.webdriver.lib.WDLibrary.java

License:Open Source License

/**
 * Click the WebElement at a certain coordination with a special key pressed.<br>
 * Firstly it will try to get webelement's location and use Robot to click. At the same<br>
 * time, it will listen to a 'javascript mouse down' event to find out if the click really<br>
 * happened; If not, it will try to use Selenium's API to do the work.<br>
 * If the click point is outside of the boundary of the WebElement, which means we are going<br>
 * to click on the sibling component. At this situation, our click-listener will never receive<br>
 * the click event, we will turn off the click-listener.<br>
 *
 * @param clickable    WebElement, the WebElement to click on
 * @param offset      Point, the coordination relative to this WebElement to click at.<br>
 *                         if the offset is null, then click at the center.
 * @param specialKey   Keys, the special key to press during the click
 * @param mouseButtonNumber int, the mouse-button-number representing right, middle, or left button.
 *                          it can be {@link #MOUSE_BUTTON_LEFT} or {@link #MOUSE_BUTTON_RIGHT}.<br>
 *                          {@link #MOUSE_BUTTON_MIDDLE} NOT supported yet.
 * @param optional String[], the optional parameters
 * <ul>//  w ww. j ava2 s.  c o  m
 * <li> optional[0] autoscroll boolean, if the component will be scrolled into view automatically before clicking.
 *                                      if not provided, the default value is true.
 * </ul>
 * @throws SeleniumPlusException
 */
public static void click(WebElement clickable, Point offset, Keys specialKey, int mouseButtonNumber,
        String... optional) throws SeleniumPlusException {
    String debugmsg = StringUtils.debugmsg(WDLibrary.class, "click");

    checkBeforeOperation(clickable, true);
    WebDriver wd = WDLibrary.getWebDriver();
    RemoteDriver rd = (wd instanceof RemoteDriver) ? (RemoteDriver) wd : null;
    boolean autoscroll = parseAutoScroll(optional);

    if (autoscroll) {
        try {
            new Actions(wd).moveToElement(clickable).perform();
        } catch (Throwable t) {
            IndependantLog
                    .error(debugmsg + "Ignoring Selenium Robot Click 'moveToElement' action failure caused by "
                            + t.getClass().getName());
        }
    }

    MouseEvent event = null;
    DocumentClickCapture listener = new DocumentClickCapture(true, clickable);
    checkOffset(clickable, offset, listener);

    try {
        //2. Perform the click action by Robot
        Point location = getScreenLocation(clickable);
        if (offset != null)
            location.translate(offset.x, offset.y);
        else {
            Dimension d = clickable.getSize();
            location.translate(d.width / 2, d.height / 2);
        }
        listener.addListeners(false);
        RBT.click(rd, location, specialKey, mouseButtonNumber, 1);
        listener.startListening();

        //3. Wait for the 'click' event, check if the 'mousedown' event really happened.
        // CANAGL -- FIREFOX PROBLEM: A link that takes you to a new page (like the Google SignIn link) will
        // trigger the default action and apparently will NOT allow us to detect the Click occurred.
        // So this WILL generate a waitForClick InterruptedException (Timeout)
        event = listener.waitForClick(timeoutWaitRobotClick);
        if (event == null) {
            IndependantLog.resumeLogging();
            IndependantLog
                    .warn(debugmsg + " Robot may fail to perform click. Click screen location is " + location);
            throw new SeleniumPlusException("The Robot click action didn't happen.");
        } else {
            IndependantLog.resumeLogging();
            IndependantLog.debug(debugmsg + "Robot click successful.");
        }
    } catch (Throwable thr) {
        IndependantLog.resumeLogging();
        IndependantLog.warn(debugmsg + "Met Exception " + StringUtils.debugmsg(thr));

        // let the failed listeners exit.
        try {
            Thread.sleep(DocumentClickCapture.LISTENER_LOOP_DELAY + DocumentClickCapture.delayWaitReady);
        } catch (Exception x) {
            IndependantLog.debug(debugmsg + StringUtils.debugmsg(x));
        }

        try {
            //2. Perform the click action by Selenium
            IndependantLog.debug(debugmsg + " Try selenium API to click.");
            //Create a combined actions according to the parameters
            Actions actions = new Actions(getWebDriver());

            if (autoscroll) {
                if (offset != null)
                    actions.moveToElement(clickable, offset.x, offset.y);
                else
                    actions.moveToElement(clickable);
            }

            if (specialKey != null)
                actions.keyDown(specialKey);
            if (isRightMouseButton(mouseButtonNumber))
                actions.contextClick();
            else if (isLeftMouseButton(mouseButtonNumber))
                actions.click();
            else if (isMiddleMouseButton(mouseButtonNumber)) {
                throw new SeleniumPlusException("Click 'mouse middle button' has not been supported yet.");
            } else {
                throw new SeleniumPlusException(
                        "Mouse button number '" + mouseButtonNumber + "' cannot be recognized.");
            }
            if (specialKey != null)
                actions.keyUp(specialKey);

            IndependantLog.debug(
                    debugmsg + "click with key '" + specialKey + "', mousebutton='" + mouseButtonNumber + "'");

            //Perform the actions
            listener.addListeners(false);
            try {
                //if the Robot click worked, but was not detected. If we clicked a link, original page has
                //disappeared, so the link doesn't exist neither, the WebElement is stale. WebDriver will
                //not throw StaleElementReferenceException until the 'implicit timeout' is reached.
                //But we don't want to waste that time, so just set 'implicit timeout' to 0 and don't wait.
                WDTimeOut.setImplicitlyWait(0, TimeUnit.SECONDS);
                actions.build().perform();
                listener.startListening();

                // Dharmesh: Not report waitForClick failure due to listener event not capture 
                // if click coordination out of component size or background. 
                // It is hard to find sibling component.
                try {
                    event = listener.waitForClick(timeoutWaitClick);
                } catch (Throwable the) {
                    IndependantLog.debug(debugmsg + " waitForClick failed but not reported");
                }
                ;

                /*if(event != null)
                   IndependantLog.debug(debugmsg+"click has been performed.");
                else{
                   throw new SeleniumPlusException("Selenium Action.click failed to return the MouseEvent.");
                }*/

            } catch (StaleElementReferenceException x) {
                listener.stopListening(); // chrome is NOT stopping!
                // the click probably was successful because the elements have changed!
                IndependantLog.debug(debugmsg
                        + "StaleElementException (not found) suggests the click has been performed successfully.");
            } finally {
                IndependantLog.debug(
                        debugmsg + "selenium API click finally stopping listener and resetting timeouts.");
                listener.stopListening(); // chrome is NOT stopping!
                WDTimeOut.resetImplicitlyWait(Processor.getSecsWaitForComponent(), TimeUnit.SECONDS);
            }
        } catch (Throwable th) {
            listener.stopListening(); // chrome is NOT stopping!
            if (enableClickListenerFailures) {
                IndependantLog.error(debugmsg, th);
                throw new SeleniumPlusException("click action failed: " + StringUtils.debugmsg(th));
            } else {
                IndependantLog.debug(debugmsg + "ignoring selenium API click failure caused by "
                        + th.getClass().getName() + ", " + th.getMessage());
            }
        }
    } finally {
        IndependantLog.debug(debugmsg + "FINALLY stopping any ongoing listener, if any.");
        listener.stopListening(); // chrome is NOT stopping!
    }
}

From source file:org.safs.selenium.webdriver.lib.WDLibrary.java

License:Open Source License

/**
 * Double-Click the WebElement at a certain coordination with a special key pressed.<br>
 * Firstly it will try to get webelement's location and use Robot to double click. At the same<br>
 * time, it will listen to a 'javascript mouse down' event to find out if the double click really<br>
 * happened; If not, it will try to use Selenium's API to do the work.<br>
 * If the click point is outside of the boundary of the WebElement, which means we are going<br>
 * to click on the sibling component. At this situation, our click-listener will never receive<br>
 * the click event, we will turn off the click-listener.<br>
 *
 * @param clickable    WebElement, the WebElement to click on
 * @param offset      Point, the coordination relative to this WebElement to click at.<br>
 *                         if the offset is null, then click at the center.
 * @param specialKey   Keys, the special key to press during the click
 * @param mouseButtonNumber int, the mouse-button-number representing right, middle, or left button.
 *                          it can be {@link #MOUSE_BUTTON_LEFT}<br>
 *                          {@link #MOUSE_BUTTON_MIDDLE} and {@link #MOUSE_BUTTON_RIGHT} NOT supported yet.
 * @param optional String[], the optional parameters
 * <ul>/*  w  w  w  .  j  a va2s.  c o m*/
 * <li> optional[0] autoscroll boolean, if the component will be scrolled into view automatically before clicking.
 *                                      if not provided, the default value is true.
 * </ul>
 * @throws SeleniumPlusException
 */
public static void doubleClick(WebElement clickable, Point offset, Keys specialKey, int mouseButtonNumber,
        String... optional) throws SeleniumPlusException {
    String debugmsg = StringUtils.debugmsg(WDLibrary.class, "doubleClick");

    checkBeforeOperation(clickable, true);

    MouseEvent event = null;
    DocumentClickCapture listener = new DocumentClickCapture(true, clickable);
    checkOffset(clickable, offset, listener);
    boolean autoscroll = parseAutoScroll(optional);

    try {
        //2. Perform the click action by Robot
        Point location = getScreenLocation(clickable);
        if (offset != null)
            location.translate(offset.x, offset.y);
        else
            location.translate(clickable.getSize().width / 2, clickable.getSize().height / 2);
        listener.addListeners(false);
        RBT.click(location, specialKey, mouseButtonNumber, 2);
        listener.startListening();

        //3. Wait for the 'click' event, check if the 'mousedown' event really happened.
        event = listener.waitForClick(timeoutWaitClick);
        if (event == null) {
            IndependantLog.warn(
                    debugmsg + " Robot may fail to perform doubleclick. Click screen location is " + location);
            throw new SeleniumPlusException("The doubleclick action didn't happen.");
        } else {
            IndependantLog.debug(debugmsg + "doubleclick has been peformed.");
        }
    } catch (Throwable thr) {
        IndependantLog.warn(debugmsg + "Met Exception " + StringUtils.debugmsg(thr));
        try {
            //2. Perform the click action by Selenium
            IndependantLog.debug(debugmsg + " Try selenium API to doubleclick.");
            //Create a combined actions according to the parameters
            Actions actions = new Actions(WDLibrary.getWebDriver());

            if (autoscroll) {
                if (offset != null)
                    actions.moveToElement(clickable, offset.x, offset.y);
                else
                    actions.moveToElement(clickable);
            }

            if (specialKey != null)
                actions.keyDown(specialKey);
            if (isLeftMouseButton(mouseButtonNumber))
                actions.doubleClick();
            else if (isMiddleMouseButton(mouseButtonNumber) || isRightMouseButton(mouseButtonNumber)) {
                throw new SeleniumPlusException(
                        "Double click 'mouse middle/right button' has not been supported yet.");
            } else
                throw new SeleniumPlusException(
                        "Mouse button number '" + mouseButtonNumber + "' cannot be recognized.");

            if (specialKey != null)
                actions.keyUp(specialKey);

            IndependantLog.debug(debugmsg + "doubleclick with key '" + specialKey + "', mousebutton='"
                    + mouseButtonNumber + "'");

            //Perform the actions
            listener.addListeners(false);
            try {
                //unfortunately, if the Robot click worked, but was not detected, we have to wait the full
                //WebDriver implied timeout period for the perform() failure to occur.
                actions.build().perform();
                listener.startListening();
                event = listener.waitForClick(timeoutWaitClick);
                if (event != null)
                    IndependantLog.debug(debugmsg + "doubleclick has been peformed.");
                else {
                    throw new SeleniumPlusException(
                            "Selenium Action.doubleclick failed to detect the MouseEvent.");
                }
            } catch (StaleElementReferenceException x) {
                // the click probably was successful because the elements have changed!
                IndependantLog.debug(debugmsg
                        + "StaleElementException (not found) suggests the click has been performed successfully.");
            }
        } catch (Throwable th) {
            IndependantLog.error(debugmsg, th);
            throw new SeleniumPlusException("doubleclick action failed: " + StringUtils.debugmsg(th));
        }
    } finally {
        listener.stopListening();
    }
}

From source file:org.safs.selenium.webdriver.lib.WDLibrary.java

License:Open Source License

/**
 * Perform a left-drag from start point to end point relative to webelement (LeftUp corner).
 * @param we WebElement, the component relative to which to drag
 * @param start Point, the start point relative to the webelement
 * @param end Point, the end point relative to the webelement
 * @throws SeleniumPlusException//from  w  w  w  . j  a  v a  2 s.c  o m
 */
public static void leftDrag(WebElement we, Point start, Point end) throws SeleniumPlusException {
    String debugmsg = StringUtils.debugmsg(false);

    try {
        IndependantLog.debug(debugmsg + " drag from " + start + " to " + end + " relative to webelement.");
        translatePoints(we, start, end);
        Robot.leftDrag(start, end);

    } catch (Exception e) {
        IndependantLog.warn(debugmsg + "Failed to drag by SAFS Robot: " + StringUtils.debugmsg(e));
        IndependantLog.debug(debugmsg + "Try to drag by Selenium API.");

        try {
            Actions actions = new Actions(lastUsedWD);
            actions = actions.moveToElement(we, start.x, start.y);
            actions = actions.clickAndHold().moveByOffset((end.x - start.x), (end.y - start.y)).release();
            actions.build().perform();
        } catch (Exception e1) {
            IndependantLog.warn(debugmsg + "Failed to drag by Selenium API: " + StringUtils.debugmsg(e1));
            throw new SeleniumPlusException("Failed to drag.");
        }
    }
}

From source file:org.safs.selenium.webdriver.lib.WDLibrary.java

License:Open Source License

/**
 * Click a component with an offset. This API will not verify that the click does happen.<br>
 * If you want to make sure of that, please call {@link #click(WebElement, Point)} instead.<br>
 * <br>//from w  ww  .j ava 2s.c  o m
 * Sometimes we want to click without verification, for example, to show an Alert.<br> 
 * With presence of Alert, any call to Selenium API will throw out UnhandledAlertException<br>
 * and close the Alert automatically. Our API {@link #click(WebElement, Point)} will call<br>
 * Selenium API for verification, so it is unable to open the Alert successfully.<br>  
 * 
 * @param component WebElement, the component to click
 * @param offset Point, the offset (relative to component) to click at
 * @param optional String[], the optional parameters
 * <ul>
 * <li> optional[0] autoscroll boolean, if the component will be scrolled into view automatically before clicking.
 *                                      if not provided, the default value is true.
 * </ul>
 * @return boolean true if succeed.
 * @see #click(WebElement, Point)
 */
public static boolean clickUnverified(WebElement component, Point offset, String... optional) {
    String debugmsg = StringUtils.debugmsg(false);

    try {
        IndependantLog.debug(debugmsg + " click with parameter componet:" + component + ", offset:" + offset);
        //Create a combined actions according to the parameters
        Actions actions = new Actions(getWebDriver());

        boolean autoscroll = parseAutoScroll(optional);
        if (autoscroll) {
            if (offset != null)
                actions.moveToElement(component, offset.x, offset.y);
            else
                actions.moveToElement(component);
        }
        IndependantLog.debug(debugmsg + " Try Selenium API to click.");
        actions.click().perform();

        return true;
    } catch (Exception e) {
        IndependantLog.warn(
                debugmsg + " Failed with Selenium API, met " + StringUtils.debugmsg(e) + ". Try Robot click.");

        try {
            Point p = WDLibrary.getScreenLocation(component);

            if (offset != null)
                p.translate(offset.x, offset.y);
            else
                p.translate(component.getSize().width / 2, component.getSize().height / 2);

            RBT.click(p, null, WDLibrary.MOUSE_BUTTON_LEFT, 1);

            return true;
        } catch (Exception e1) {
            IndependantLog.error(debugmsg + " Failed with Robot click!");
        }
        return false;
    }
}