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

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

Introduction

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

Prototype

public Action build() 

Source Link

Document

Generates a composite action containing all actions so far, ready to be performed (and resets the internal builder state, so subsequent calls to #build() will contain fresh sequences).

Usage

From source file:org.richfaces.tests.metamer.ftest.richPanelMenuItem.TestPanelMenuItemDOMEventHandlers.java

License:Open Source License

@Test
@CoversAttributes("onmouseover")
@Templates(value = "plain")
public void testOnmouseover() {
    panelMenuItemAttributes.set(mode, client);
    Actions mouseover = new Actions(driver).moveToElement(page.getRequestTimeElement())
            .moveToElement(page.getItem().advanced().getRootElement(), 3, 3);
    testFireEvent(panelMenuItemAttributes, onmouseover, mouseover.build());
}

From source file:org.richfaces.tests.page.fragments.impl.input.TextInputComponentImpl.java

License:Open Source License

@Override
public TextInputComponent clear(ClearType clearType) {
    int valueLength = root.getAttribute("value").length();
    Actions builder = new Actions(getWebDriver());
    JavascriptExecutor executor = (JavascriptExecutor) getWebDriver();
    switch (clearType) {
    case BACKSPACE:
        for (int i = 0; i < valueLength; i++) {
            builder.sendKeys(root, Keys.BACK_SPACE);
        }//from ww  w .  jav  a 2s. c  o m
        builder.build().perform();
        break;
    case DELETE:
        String ctrlADel = Keys.chord(Keys.CONTROL, "a", Keys.DELETE);
        builder.sendKeys(root, ctrlADel);
        builder.build().perform();
        break;
    case ESCAPE_SQ:
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < valueLength; i++) {
            sb.append("\b");
        }
        root.sendKeys(sb.toString());
        root.click();
        break;
    case JS:
        executor.executeScript("jQuery(arguments[0]).val('')", root);
        break;
    case WD:
        root.clear();
        break;
    default:
        throw new UnsupportedOperationException("Unknown type of clear method " + clearType);
    }
    return this;
}

From source file:org.richfaces.tests.showcase.contextMenu.AbstractContextMenuTest.java

License:Open Source License

protected void checkContextMenuRenderedAtCorrectPosition(WebElement target, WebElement contextMenuPopup,
        InvocationType type, ExpectedCondition<Boolean> conditionTargetIsFocused) {
    Actions builder = new Actions(GrapheneContext.getProxy());

    if (conditionTargetIsFocused != null) {
        target.click();// ww  w. j a va 2 s .c o  m
        Graphene.waitGui(webDriver).withTimeout(2, TimeUnit.SECONDS).until(conditionTargetIsFocused);
    }
    waitGui();

    // clicks in the middle of the target
    switch (type) {
    case LEFT_CLICK:
        builder.click(target);
        break;
    case RIGHT_CLICK:
        builder.contextClick(target);
        break;
    default:
        throw new IllegalArgumentException("Wrong type of context menu invocation!");
    }
    builder.build().perform();

    Graphene.waitGui().withTimeout(2, TimeUnit.SECONDS).until(element(contextMenuPopup).isVisible());

    Point locationOfTarget = target.getLocation();
    Point locationOfCtxMenu = contextMenuPopup.getLocation();

    double witdth = getTargetWidth(target);
    double height = getTargetHeight(target);

    double halfOfDiagonal = Math.sqrt((height * height) + (witdth * witdth)) / 2.0;
    double distance = getDistance(locationOfTarget, locationOfCtxMenu);

    double result = halfOfDiagonal - distance;

    assertTrue(result >= 0 && result < TOLERANCE,
            "The context menu was not rendered on the correct position! The difference is: " + result);
}

From source file:org.richfaces.tests.showcase.focus.page.FocusPage.java

License:Open Source License

public static void typeSomethingAndDoNotCareAboutFocus(String keys) {
    Actions builder = new Actions(GrapheneContext.getProxy());

    builder.sendKeys(keys);/*from   www . j a v  a 2  s. c o m*/
    builder.build().perform();
}

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 w  w . j a  va 2s. co 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 av  a 2  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 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

/**
 * Does NOT clear any existing text in the control, but does attempt to insure the window/control has focus.
 * <br><em>Purpose:</em>
 * <a href="http://safsdev.sourceforge.net/sqabasic2000/SeleniumGenericMasterFunctionsReference.htm#detail_InputKeys" alt="inputKeys Keyword Reference" title="inputKeys Keyword Reference">inputKeys</a>
 * <p>//from www .j a  v  a2 s.  c o  m
 * Bypasses attempts to use AWT Robot for keystrokes.
 * Attempts to convert SAFS keystrokes to Selenium low-level Actions keystrokes.
 * @param we WebElement to send SAFS keystrokes (or plain text).
 * @param keystrokes SAFS keystrokes or plain text to type.
 * @throws SeleniumPlusException if we are unable to process the keystrokes successfully.
 **/
public static void inputKeysSAFS2Selenium(WebElement we, String keystrokes) throws SeleniumPlusException {
    String debugmsg = StringUtils.debugmsg(false);
    IndependantLog.debug(debugmsg + " processing '" + keystrokes + "' on webelement " + we);
    if (!focus(we))
        IndependantLog.warn(debugmsg + " Fail to set focus to webelement " + we);

    RemoteDriver wd = null;
    try {
        wd = (RemoteDriver) getWebDriver();
    } catch (Exception x) {
    }
    // convert to Selenium low-level Action keystrokes.
    if (keysparser != null) {
        Vector keys = keysparser.parseInput(keystrokes);
        Actions actions = new Actions(wd);

        if (we != null)
            actions = actions.moveToElement(we);

        Iterator events = keys.iterator();
        RobotKeyEvent event;
        Keys k = null;
        CharSequence c = null;
        while (events.hasNext()) {
            try {
                event = (RobotKeyEvent) events.next();
                c = null;
                k = convertToKeys(event);
                if (k == null) {
                    c = convertToCharacter(event);
                } else {

                }
                switch (event.get_event()) {

                case RobotKeyEvent.KEY_PRESS:
                    if (k != null) {
                        IndependantLog.debug(debugmsg + " handling keyDown '" + k.name() + "'");
                        actions = actions.keyDown(k);
                    } else {
                        IndependantLog.debug(debugmsg + " send char '" + c + "'");
                        actions = actions.sendKeys(c);
                    }
                    break;

                case RobotKeyEvent.KEY_RELEASE:
                    if (k != null) {
                        IndependantLog.debug(debugmsg + " handling keyUp '" + k.name() + "'");
                        actions = actions.keyUp(k);
                    } else {
                        IndependantLog.debug(debugmsg + " send char '" + c + "'");
                        actions = actions.sendKeys(c);
                    }
                    break;

                case RobotKeyEvent.KEY_TYPE:
                    if (k != null) {
                        IndependantLog.debug(debugmsg + " send Key '" + k.name() + "'");
                        actions = actions.sendKeys(k);
                    } else {
                        IndependantLog.debug(debugmsg + " send char '" + c + "'");
                        actions = actions.sendKeys(c);
                    }
                    break;
                default:
                }
            } catch (Exception x) {
                IndependantLog.debug(debugmsg + " IGNORING RobotKeyEvent exception:", x);
            }
        }
        try {
            actions.build().perform();
        } catch (StaleElementReferenceException x) {
            // the click probably was successful because the elements have changed!
            IndependantLog.debug(debugmsg + " StaleElementException (not found).");
        } catch (Throwable x) {
            IndependantLog.debug(debugmsg + " " + x.getClass().getName() + ", " + x.getMessage());
        } finally {
            IndependantLog.debug(debugmsg + " selenium actions.build().perform() complete.");
        }
    } else {
        // TODO what if keyparser cannot load a keys converter???
    }
}

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

License:Open Source License

/**
 * Press down a Key by Selenium's Actions API. Call {@link #keyUp(Keys)} to release the key.
 * @param keycode Keys, keycode to press (e.g. <code>Keys.CONTROL</code>)
 * @throws SeleniumPlusException if fail
 * @see #keyUp(Keys)//w  w w. j ava  2  s. c om
 */
public static void keyDown(Keys keycode) throws SeleniumPlusException {
    try {
        WebDriver wd = (WebDriver) getWebDriver();
        Actions actions = new Actions(wd);
        actions.keyDown(keycode);
        actions.build().perform();
    } catch (Exception e) {
        throw new SeleniumPlusException("Unable to successfully complete Selenium keyDown for key '" + keycode
                + "' due to " + e.getMessage(), e);
    }
}

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

License:Open Source License

/**
 * Release a Key by Selenium's Actions API. Release the key pressed by {@link #keyDown(Keys)}.
 * @param keycode Keys, keycode to release (e.g. <code>Keys.CONTROL</code>)
 * @throws SeleniumPlusException if fail
 * @see #keyDown(Keys)// w  ww . java 2  s. com
 */
public static void keyUp(Keys keycode) throws SeleniumPlusException {
    try {
        WebDriver wd = (WebDriver) getWebDriver();
        Actions actions = new Actions(wd);
        actions.keyUp(keycode);
        actions.build().perform();
    } catch (Exception e) {
        throw new SeleniumPlusException("Unable to successfully complete Selenium keyUp for key '" + keycode
                + "' due to " + e.getMessage(), e);
    }
}

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

License:Open Source License

/**
 * @param we WebElement, the component to hover mouse
 * @param point Point, the position relative to the component to hover the mouse
 * @param millisStay double, the period to hover the mouse, in milliseconds
 * @throws SeleniumPlusException if the hover fail
 *//* www .  ja va  2  s .c  o  m*/
public static void mouseHover(WebElement we, Point point, int millisStay) throws SeleniumPlusException {

    try {
        //Hover mouse on the webelement
        Actions action = new Actions(lastUsedWD);
        action.moveToElement(we);
        if (point != null) {
            int xOffset = point.x - we.getSize().width / 2;
            int yOffset = point.y - we.getSize().height / 2;
            action.moveByOffset(xOffset, yOffset);
        }
        action.build().perform();

        //Pause a while
        StringUtilities.sleep(millisStay);

        //Move out the mouse
        //action.moveByOffset(-Robot.SCREENSZIE.width, -Robot.SCREENSZIE.height);//This will throw exception
        //action.build().perform();
        Robot.getRobot().mouseMove(-Robot.SCREENSZIE.width, -Robot.SCREENSZIE.height);

    } catch (Exception e) {
        IndependantLog.warn(StringUtils.debugmsg(false) + "Failed to hover mouse by Selenium API: "
                + StringUtils.debugmsg(e));
        Point screenPoint = new Point(point.x, point.y);
        try {
            translatePoint(we, screenPoint);
            IndependantLog.warn(StringUtils.debugmsg(false) + "Try SAFS Robot to hover mouse at screen point ["
                    + screenPoint.x + "," + screenPoint.y + "]");
            Robot.mouseHover(screenPoint, millisStay);
        } catch (Exception e2) {
            throw new SeleniumPlusException(
                    "Failed to hover mouse at point [" + point.x + "," + point.y + "] relative to webelement.");
        }
    }
}