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:com.vaadin.testbench.TestBenchElement.java

@Override
public void click(int x, int y, Keys... modifiers) {
    waitForVaadin();//w  w w  .j  a  va2 s  .  co m
    Actions actions = new Actions(getCommandExecutor().getWrappedDriver());
    actions.moveToElement(actualElement, x, y);
    // Press any modifier keys
    for (Keys modifier : modifiers) {
        actions.keyDown(modifier);
    }
    actions.click();
    // Release any modifier keys
    for (Keys modifier : modifiers) {
        actions.keyUp(modifier);
    }
    actions.build().perform();
}

From source file:com.virtusa.isq.vtaf.runtime.SeleniumTestBase.java

License:Apache License

/**
 * Clicks on a link, button, checkbox or radio button. If the click action
 * causes a new page to load (like a link usually does), call
 * waitForPageToLoad. <br>/*w w  w  .  j av  a  2s.  co  m*/
 * ClickAt is capable of perform clicking on a relative location to the
 * specified element. use locator to specify the respective X,Y coordinates
 * to click
 * 
 * @param locator
 *            : Logical name of the web element assigned by the automation
 *            scripter
 * @param coordinateString
 *            the coordinate string
 */

private void doClickAt(final ObjectLocator locator, final String coordinateString) {
    String objectID = "";
    int counter = getRetryCount();
    int xOffset = 0;
    int yOffset = 0;
    WebDriver driver = getDriver();
    String objectName = locator.getLogicalName();
    try {
        // Retrieve the correct object locator from the object map
        objectID = locator.getActualLocator();

        // first verify whether the element is present in the current web
        // page
        checkForNewWindowPopups();
        WebElement element = checkElementPresence(objectID);

        try {
            xOffset = Integer.parseInt((coordinateString.split(",")[0]).trim());
            yOffset = Integer.parseInt((coordinateString.split(",")[1]).trim());
        } catch (Exception e) {

            e.printStackTrace();
            reportresult(true, "CLICKAT :" + objectName + "", "FAILED", "CLICKAT coordinate string ("
                    + coordinateString + ") for :Element (" + objectName + ") [" + objectID + "] is invalid");

            checkTrue(false, true, "CLICKAT coordinate string (" + coordinateString + ") " + "for :Element ("
                    + objectName + ") [" + objectID + "] is invalid");
        }
        /*
         * START DESCRIPTION following while loop was added to make the
         * command more consistent try the command for give amount of time
         * (can be configured through class variable RETRY) command will be
         * tried for "RETRY" amount of times until command works. any
         * exception thrown within the tries will be handled internally.
         * 
         * can be exited from the loop under 2 conditions 1. if the command
         * succeeded 2. if the RETRY count is exceeded
         */
        while (counter > 0) {
            try {
                counter--;
                // call for real selenium command
                /* selenium.clickAt(objectID, coordinateString); */

                Actions clickAt = new Actions(driver);
                clickAt.moveToElement(element, xOffset, yOffset).click();
                clickAt.build().perform();
                // if not exception is called consider and report the result
                // as passed
                reportresult(true, "CLICKAT :" + locator.getLogicalName() + "", "PASSED", "");
                // if the testcase passed move out from the loop
                break;
            } catch (StaleElementReferenceException staleElementException) {

                element = checkElementPresence(objectID);
            } catch (Exception e) {

                sleep(retryInterval);
                if (!(counter > 0)) {

                    e.printStackTrace();
                    reportresult(true, "CLICKAT :" + objectName + "", "FAILED",
                            "CLICKAT command cannot access Element (" + locator + ") [" + objectID + "] ");
                    checkTrue(false, true,
                            "CLICKAT command cannot access Element (" + objectName + ") [" + objectID + "] ");
                }
            }
        }
        /*
         * END DESCRIPTION
         */

    } catch (Exception e) {

        e.printStackTrace();
        /*
         * VTAF result reporter call
         */
        reportresult(true, "CLICKAT :" + objectName + "", "FAILED",
                "CLICKAT command  :Element (" + objectName + ") [" + objectID + "] not present");

        /*
         * VTAF specific validation framework reporting
         */
        checkTrue(false, true, "CLICKAT command  :Element (" + objectName + ") [" + objectID + "] not present");
    }

}

From source file:com.virtusa.isq.vtaf.runtime.SeleniumTestBase.java

License:Apache License

/**
 * Doubleclicks on a link, button, checkbox or radio button. If the action
 * causes a new page to load (like a link usually does), call
 * waitForPageToLoad.<br>/* ww  w . jav  a2 s. co  m*/
 * The main differentiator of <b> DoubleClickAt </b> is, user can make the
 * script click on a relative location to the element <br>
 * <br>
 * 
 * @param locator
 *            : the coordination string to be click which is relative to the
 *            element <br>
 *            this should be specified using relative X and Y coordinates,
 *            in the following format "X,Y"
 * @param coordinateString
 *            the coordinate string
 */

private void doDoubleClickAt(final ObjectLocator locator, final String coordinateString) {
    int counter = getRetryCount();
    int xOffset = 0;
    int yOffset = 0;
    WebDriver driver = getDriver();
    // Retrieve the actual object identification from the OR
    String objectID = locator.getActualLocator();
    String objectName = locator.getLogicalName();
    try {

        // Precheck done to check whether the element is available if
        // element is not
        // present, code will move to the catch block and report an error
        checkForNewWindowPopups();
        WebElement element = checkElementPresence(objectID);

        try {
            xOffset = Integer.parseInt((coordinateString.split(",")[0]).trim());
            yOffset = Integer.parseInt((coordinateString.split(",")[1]).trim());
        } catch (Exception e) {

            e.printStackTrace();

            reportresult(true, "DOUBLE CLICK AT :" + objectName + "", "FAILED",
                    "DOUBLE CLICK AT coordinate string (" + coordinateString + ") for :Element (" + objectName
                            + ") [" + objectID + "] is invalid");

            checkTrue(false, true, "DOUBLE CLICK AT coordinate string (" + coordinateString + ") "
                    + "for :Element (" + objectName + ") [" + objectID + "] is invalid");
        }

        /*
         * START DESCRIPTION following for loop was added to make the
         * command more consistent try the command for give amount of time
         * (can be configured through class variable RETRY) command will be
         * tried for "RETRY" amount of times or until command works. any
         * exception thrown within the tries will be handled internally.
         * 
         * can be exited from the loop under 2 conditions 1. if the command
         * succeeded 2. if the RETRY count is exceeded
         */
        while (counter > 0) {
            counter--;
            try {

                Actions doubleClickAt = new Actions(driver);
                doubleClickAt.moveToElement(element, xOffset, yOffset).doubleClick();
                doubleClickAt.build().perform();

                reportresult(true, "DOUBLE CLICK AT :" + objectName + "", "PASSED", "");
                break;
            } catch (StaleElementReferenceException staleElementException) {

                element = checkElementPresence(objectID);
            } catch (Exception e) {
                sleep(retryInterval);
                // The main possibility of throwing exception at this point
                // should be due to the element was not
                // fully loaded, in this catch block handle the exception
                // untill retry amount of attempts
                if (!(counter > 0)) {
                    e.printStackTrace();
                    reportresult(true, "DOUBLE CLICK AT :" + objectName + "", "FAILED",
                            "DOUBLE CLICK AT command  :Element (" + objectName + ") [" + objectID
                                    + "] not present");
                    checkTrue(false, true, "DOUBLE CLICK AT command  :Element (" + objectName + ") [" + objectID
                            + "] not present");
                }
            }
        }

        /*
         * END DESCRIPTION
         */

    } catch (Exception e) {
        // if any exception was raised report report an error and fail the
        // test case
        e.printStackTrace();
        reportresult(true, "DOUBLE CLICK AT :" + objectName + "", "FAILED",
                "DOUBLE CLICK AT command  :Element (" + objectName + ") [" + objectID + "] not present");
        checkTrue(false, true,
                "DOUBLE CLICK AT command  :Element (" + objectName + ") [" + objectID + "] not present");
    }

}

From source file:dagaz.controllers.ChildController.java

private void switchChannel() {
    try {/*  w  w w  .  j a  v a 2s .co  m*/
        StaticImageScreenRegion region = videoFooterSection();
        if (region != null) {
            List<ScreenRegion> re = region
                    .findAll(new ImageTarget(ImageIO.read(new File(imgRoot + "wifi.png"))));
            if (re.size() < 1) {
                throw new IOException("Failed to find the wifi icon.");
            } else {
                for (ScreenRegion screenRegion : re) {
                    Actions action = new Actions(driver);
                    int nextChannel = 0;
                    if (channel == 5) {
                        nextChannel = 1;
                    } else {
                        nextChannel = channel + 1;
                    }
                    WebElement element = driver.findElement(By.id("divFlashHolder"));
                    action.moveToElement(element, screenRegion.getCenter().getX() + 40,
                            300 + screenRegion.getCenter().getY()).click().build().perform();
                    action = new Actions(driver);
                    action.moveToElement(element, screenRegion.getCenter().getX() + 40,
                            300 + screenRegion.getCenter().getY() - (120 - (nextChannel * 20))).click().build()
                            .perform();
                    channel = nextChannel;
                    config.getRoot().appendDetails("\t ---- Connection trouble ----\n\t[" + arena
                            + "] - Switching to channel #" + channel + "\n\t---------------");
                }
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(ChildController.class.getName()).log(Level.SEVERE, null, ex);
        config.getRoot().appendDetails("- [" + arena + "] - Failed to switch channel.");
    }
}

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

License:Apache License

@Override
protected ExecuteResult execute(WebSiteConnector connector) {
    final WebElementLocator nodeWithVariables = node == null ? null
            : new WebElementLocator(insertVariableValues(node.getSelector()), node.getType());

    try {// w  ww  . ja va  2 s.co  m
        final Actions actions = new Actions(connector.getDriver());

        if (nodeWithVariables == null || nodeWithVariables.getSelector().trim().equals("")) {
            actions.moveByOffset(offsetX, offsetY).build().perform();
            LOGGER.info(LoggerMarkers.LEARNER, "Moved the mouse to the position ({}, {}) ", offsetX, offsetY);
        } else {
            final WebElement element = connector.getElement(nodeWithVariables);
            actions.moveToElement(element, offsetX, offsetY).build().perform();
            LOGGER.info(LoggerMarkers.LEARNER, "Moved the mouse to the element '{}'", nodeWithVariables);
        }

        return getSuccessOutput();
    } catch (Exception e) {
        LOGGER.info(LoggerMarkers.LEARNER,
                "Could not move the mouse to the element '{}' or the position ({}, {})", nodeWithVariables,
                offsetX, offsetY);
        return getFailedOutput();
    }
}

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

License:Open Source License

private void clickOnACell() throws InterruptedException {
    zoomIntoHelsinore();// w  ww.j  av a  2  s .com
    waitForCellsToBeDisplayed();

    WebElement map = getMap();

    Actions actions = new Actions(browser);
    actions.moveToElement(map, map.getSize().getWidth() / 2, map.getSize().getHeight() / 2);
    actions.click();
    actions.perform();

    // Cursor position is exactly in the center of the map
    browser.findElement(By.id("tab-map")).click();
    assertEquals("(5602'05.7\"N, 1238'59.7\"E)",
            browser.findElement(By.cssSelector("div#cursorpos.useroutput p")).getText());

    // Assert statistic data for correct cell displayed
    final String expectedCellInfo = "Cell id 6249302540 (5602'06.5\"N,1238'53.8\"E) - (5602'00\"N,1239'00.3\"E)";
    By actualCellInfoElement = By.cssSelector("div.cell-data-contents > h5");
    wait.until(ExpectedConditions.textToBePresentInElement(actualCellInfoElement, expectedCellInfo));
}

From source file:EndToEnd.BFUIJobsExcnVldtnTest.java

License:Apache License

/**
 *  testStep2BFUIImagerySubmit() to accomplish testing 
 *  of below functions of BF UI://  w w w .j a va2s . c  o m
 *  a) After user successfully logs in to BF UI Application
 *  b) Selection of Create Job link
 *  c) On the Canvas, specifying the geographic area
 *  d) Entering the input data into the Search imagery request form.
 *  e) Submit the form successfully 
 *  
 * @throws Exception
 */
@Test
public void testStep2BFUIImagerySubmit() throws Exception {
    String message = "";
    System.out.println(">>>> In BFUIJobsExcnVldtn.testStep2BFUIImagerySubmit() <<<<");

    driver.findElement(By.className("Navigation-linkCreateJob")).click();
    System.out.println(">> After requesting create job form");
    Thread.sleep(200);

    WebElement canvas = driver.findElement(By.cssSelector(".PrimaryMap-root canvas"));
    Thread.sleep(200); //To avoid any race condition

    Actions builder = new Actions(driver);
    builder.moveToElement(canvas, 900, 400).click().build().perform();
    canvas.click();
    Thread.sleep(1000); //To avoid any race condition

    builder.moveToElement(canvas, 400, 100).click().build().perform();
    canvas.click();
    Thread.sleep(200);

    System.out.println(">> After selecting bounding box as geographic search criteria area on canvas");
    Thread.sleep(5000); //To avoid any race condition

    // populating API key on the Imagery search form
    driver.findElement(By.cssSelector("input[type=\"password\"]")).clear();
    driver.findElement(By.cssSelector("input[type=\"password\"]")).sendKeys("27c9b43f20f84a75b831f91bbb8f3923");
    Thread.sleep(1000);
    // Changing From date field for Date of Capture imagery search criteria
    driver.findElement(By.cssSelector("input[type=\"text\"]")).clear();
    driver.findElement(By.cssSelector("input[type=\"text\"]")).sendKeys("2017-01-29");
    Thread.sleep(500); //To avoid any race condition
    driver.findElement(By
            .cssSelector("label.CatalogSearchCriteria-captureDateTo.forms-field-normal > input[type=\"text\"]"))
            .clear();
    driver.findElement(By
            .cssSelector("label.CatalogSearchCriteria-captureDateTo.forms-field-normal > input[type=\"text\"]"))
            .sendKeys("2017-01-31");
    Thread.sleep(500);
    new Select(driver.findElement(By.cssSelector("select"))).selectByVisibleText("RapidEye (Planet)");
    Thread.sleep(500);
    // Submitting the search criteria
    driver.findElement(By.cssSelector("button[type=\"submit\"]")).click();
    System.out.println(">> After entering data and submitting Source Imagery search form");
    Thread.sleep(16000); //Pause before exiting this test

}

From source file:EndToEnd.BFUIJobsExcnVldtnTest.java

License:Apache License

/**
 *  testStep3BFSIResponsePopup() to accomplish testing of below functions of BF UI:
 *  a) After user enter the search criteria for image search catalog and submits
 *  b) Move to the map canvas panel/*from   w w w  .j a v  a  2  s.c  om*/
 *  c) Select the response image jpg file to display the pop up
 *     with properties of the selected response image
 *  
 * @throws Exception
 */
@Test
public void testStep3BFSIResponsePopup(int cordArrayIndex) throws Exception {
    String message = "";
    System.out.println(">>>> In BFUIJobsExcnVldtn.testStep3BFSIResponsePopup() <<<<");
    Actions builder = new Actions(driver);
    WebElement canvas = driver.findElement(By.cssSelector(".PrimaryMap-root canvas"));
    WebElement search = driver.findElement(By.className("PrimaryMap-search"));
    Thread.sleep(200); //To avoid any race condition
    builder.moveToElement(search, 0, 0).click().build().perform();
    //canvas.click(); // With or without jenkins build fails
    Thread.sleep(1000); //To avoid any race condition
    System.out.println("Focusing on " + cordCity[cordArrayIndex][0] + "");
    driver.findElement(By.name("coordinate")).sendKeys(cordCity[cordArrayIndex][1]);
    Thread.sleep(200); //To avoid any race condition
    driver.findElement(By.name("coordinate")).submit();
    builder.moveToElement(canvas).click().build().perform();
    System.out.println("After moving to canvas and selecting image jpg on canvas");

    //       //By clickLinkElem = By.xpath("//*[@title='LC81950572015002LGN00']");
    //By clickLinkElem = By.xpath("//*[@title='LC82040522016276LGN00']");
    //if (this.isElementPresent(clickLinkElem)) {
    // Ensuring the properties windows is displayed for the image selected
    // LANDSAT image id for selected image should be the title.
    // driver.findElement(By.xpath("//*[@title='LC82040522016276LGN00']"));
    //driver.findElement(By.xpath("//*[@title='LC81210602015204LGN00']"));
    //System.out.println("After validating properties popup is displayed for the response image selected");
    //}

    Thread.sleep(2000); //Pause before exiting this test

}

From source file:org.evilco.bot.powersweeper.game.ScreenGameInterface.java

License:Apache License

/**
 * Builds a tile related browser action.
 *
 * @param x The X-Coordinate.// w w  w .  j a  v  a2 s. c om
 * @param y The Y-Coordinate.
 * @return The action.
 */
public Actions buildTileAction(short x, short y) {
    // create action
    Actions action = new Actions(this.powersweeper.getDriverManager().getDriver());

    // find HTML element
    WebElement html = this.powersweeper.getDriverManager().getDriver().findElement(By.tagName("html"));

    // get real coordinate
    int realX = this.getRealCoordinate(x);
    int realY = this.getRealCoordinate(y);

    realX += (CELL_SIZE / 2);
    realY += (CELL_SIZE / 2);

    // move cursor
    action.moveToElement(html, realX, realY);

    // return action
    return action;
}

From source file:org.evilco.bot.powersweeper.game.ScreenGameInterface.java

License:Apache License

/**
 * {@inheritDoc}//w w  w.ja va 2  s .  c  om
 */
@Override
public void moveToChunk(@NonNull ChunkLocation location) {
    getLogger().entry();

    // check whether sane movement is possible
    if (this.chunkLocation != null) {
        // calculate distance
        ChunkLocation distance = this.chunkLocation.getDistance(location);
        ChunkLocation distanceSanitized = new ChunkLocation(distance);
        distanceSanitized.sanitize();

        // verify whether sane movement is possible
        if (distanceSanitized.getX() <= SANE_MOVEMENT_THRESHOLD
                && distanceSanitized.getY() <= SANE_MOVEMENT_THRESHOLD) {
            // calculate distance
            long x = ((this.chunk.getWidth() * CELL_SIZE) * distance.getX());
            long y = ((this.chunk.getHeight() * CELL_SIZE) * distance.getY());

            // verify
            if (x > Integer.MAX_VALUE || y > Integer.MAX_VALUE)
                getLogger().warn("Sane movement threshold of " + SANE_MOVEMENT_THRESHOLD
                        + " seems to be too big. Aborting.");
            else {
                // find HTML
                WebElement html = this.getPowersweeper().getDriverManager().getDriver()
                        .findElement(By.tagName("html"));

                // build action
                Actions action = new Actions(this.getPowersweeper().getDriverManager().getDriver());
                action.moveToElement(html, (CELL_SIZE / 2), (CELL_SIZE / 2));
                action.clickAndHold();
                action.moveByOffset(((int) x), ((int) y));
                action.release();

                // execute
                action.build().perform();

                // wait for a few seconds
                try {
                    Thread.sleep(2000);
                } catch (Exception ex) {
                    getLogger().warn("Aliens wake us up to early.");
                }

                // update location
                this.chunkLocation = location;

                // force update
                this.update();

                // trace
                getLogger().exit();

                // skip
                return;
            }
        }
    }

    // open new URL
    this.getPowersweeper().getDriverManager().getDriver()
            .get(String.format(GAME_URL, location.getX(), location.getY()));

    // wait for a few seconds
    try {
        Thread.sleep(5000);
    } catch (Exception ex) {
        getLogger().warn("Aliens wake us up to early.");
    }

    // update location
    this.chunkLocation = location;

    // force update
    this.update();

    // trace
    getLogger().exit();
}