Example usage for java.awt Robot Robot

List of usage examples for java.awt Robot Robot

Introduction

In this page you can find the example usage for java.awt Robot Robot.

Prototype

public Robot() throws AWTException 

Source Link

Document

Constructs a Robot object in the coordinate system of the primary screen.

Usage

From source file:swift.selenium.WebHelper.java

public static void saveScreenShot() {
    if (!(Automation.driver instanceof TakesScreenshot)) {

        System.out.println(/*from   w  w w . j  a  v  a  2s  . c  om*/
                "Not able to take screenshot: Current WebDriver does not support TakesScreenshot interface.");
        return;
    }

    File scrFile = null;
    String date = null;
    String location = null;
    String fileName = null;
    BufferedImage image = null;

    if (StringUtils.isBlank(TransactionMapping.report.frmDate))
        TransactionMapping.report.setFromDate(Automation.dtFormat.format(new Date()));

    date = TransactionMapping.report.frmDate.replaceAll("[-/: ]", "");

    try {
        if (StringUtils.isNotBlank(ErrorMsg))
            //KV:Save File Name as with Current Test Step 
            fileName = TransactionMapping.report.strTestcaseId + "_"
                    + TransactionMapping.report.strTrasactionType + "_" + ErrorMsg + "_" + date + ".jpeg";
        else
            fileName = TransactionMapping.report.strTestcaseId + "_"
                    + TransactionMapping.report.strTrasactionType + "_" + date + ".jpeg";

        /*   scrFile = ((TakesScreenshot)Automation.driver).getScreenshotAs(OutputType.FILE);
           FileUtils.copyFile(scrFile, new File(location));*/
        Thread.sleep(2000);
        image = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
        ImageIO.write(image, "png",
                new File(Automation.configHashMap.get("INPUT_DATA_FILEPATH").toString() + File.separator + ".."
                        + File.separator + "Results" + File.separator + "ScreenShots" + File.separator
                        + fileName));

        location = Automation.configHashMap.get("INPUT_DATA_FILEPATH").toString() + File.separator + ".."
                + File.separator + "Results" + File.separator + "ScreenShots" + File.separator + fileName
                + ".jpeg";
        TransactionMapping.report.strScreenshot = "file:\\\\" + location;
    } catch (Exception e) {

        System.out.println("Taking screenshot failed for: " + TransactionMapping.report.strTestcaseId);
        // e.printStackTrace();
        return;
    }
}

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

/**
 * Performs a Java robot click on the specific coordinates. <br>
 * //  w  w  w. ja va 2s.c  o  m
 * @param resolution
 *            the resolution
 * @param coordinates
 *            the coordinates
 * @param waitTime
 *            the wait time
 * @throws Exception
 *             the exception
 */

public final void mouseMoveAndClick(final String resolution, final String coordinates, final String waitTime)
        throws Exception {

    String res = resolution;
    final int f11KeyCode = KeyEvent.VK_F11;
    final int optimumPauseBetweenkeyCombs = 10;
    if (res.startsWith("prop=")) {

        String resolutionFromProp = getExecProps().getProperty((res.split("prop=")[1]));
        if (resolutionFromProp != null) {
            res = resolutionFromProp;
        } else {
            reportresult(true, "MOUSE MOVE AND CLICK:", "FAILED",
                    "MOUSE MOVE AND CLICK command: Invalid property key value passed : " + res);
            checkTrue(false, true, "MOUSE MOVE AND CLICK command: Invalid property key value passed : " + res);
        }
    }

    float screenWidht = 0;
    float screeHigt = 0;
    try {
        String[] resArr = res.split(",");
        screenWidht = Float.parseFloat(resArr[0]);
        screeHigt = Float.parseFloat(resArr[1]);
    } catch (Exception e) {

        getLog().error(e);
        reportresult(true, "MOUSE MOVE AND CLICK:", "FAILED",
                "MOUSE MOVE AND CLICK command: Invalid input value passed for resolution : " + res);
        checkTrue(false, true,
                "MOUSE MOVE AND CLICK command: Invalid input value passed for resolution : " + res);
    }

    String[] coordinatesArr = coordinates.split(",");
    float xCordinate = 0;
    float yCordinate = 0;
    try {
        xCordinate = Float.parseFloat(coordinatesArr[0]);
        yCordinate = Float.parseFloat(coordinatesArr[1]);
    } catch (Exception e) {

        getLog().error(e);
        reportresult(true, "MOUSE MOVE AND CLICK:", "FAILED",
                "MOUSE MOVE AND CLICK command: Invalid input value passed for coordinates : " + coordinates);
        checkTrue(false, true,
                "MOUSE MOVE AND CLICK command: Invalid input value passed for coordinates : " + coordinates);
    }
    String command = "";

    if (coordinatesArr.length > 2) {

        command = coordinatesArr[2];
    }

    Robot robot = new Robot();

    super.sleep(Integer.parseInt(waitTime));

    int xCordinateAutual = (int) calWidth(screenWidht, xCordinate);
    int yCordinateAutual = (int) calHight(screeHigt, yCordinate);

    robot.keyPress(f11KeyCode);
    robot.delay(optimumPauseBetweenkeyCombs);
    robot.keyRelease(f11KeyCode);
    sleep(retryInterval);

    // Mouse Move
    robot.mouseMove(xCordinateAutual, yCordinateAutual);

    // Click
    if ("".equals(command)) {

        robot.mousePress(InputEvent.BUTTON1_MASK);
        sleep(retryInterval);
        robot.mouseRelease(InputEvent.BUTTON1_MASK);
        reportresult(true, "MOUSE MOVE AND CLICK : ", "PASSED",
                "MOUSE MOVE AND CLICK command: Resolution : " + res);

    } else if ("dclick".equals(command.toLowerCase(Locale.getDefault()))) {

        robot.mousePress(InputEvent.BUTTON1_MASK);
        robot.mouseRelease(InputEvent.BUTTON1_MASK);
        final int optimumPauseBetweenDclick = 500;
        robot.delay(optimumPauseBetweenDclick);
        robot.mousePress(InputEvent.BUTTON1_MASK);
        robot.mouseRelease(InputEvent.BUTTON1_MASK);

        reportresult(true, "MOUSE MOVE AND DOUBLE CLICK : ", "PASSED",
                "MOUSE MOVE AND DOUBLE CLICK command: Resolution: " + res);
        checkTrue(false, true, "MOUSE MOVE AND CLICK command: Resolution: " + res);

    }

    robot.keyPress(f11KeyCode);
    robot.delay(optimumPauseBetweenkeyCombs);
    robot.keyRelease(f11KeyCode);
}

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

/**
 * Fires a native robot event into the webpage. <br>
 * /* w  ww .  j ava 2  s.  c  om*/
 * @param event
 *            : Specicy the event which should be performed<br>
 *            1. If a keyboard event event should be started with KEY%<br>
 * <br>
 *            Ex: KEY%\n|\t<br>
 * <br>
 *            2. If it is a mouse event event should be started with MOUSE%<br>
 * <br>
 *            Ex: MOUSE%CLICK|RCLICK <br>
 * <br>
 * @param waittime
 *            : Wait time before the events.
 * */
public final void fireEvent(final String event, final String waittime) {

    super.sleep(Integer.parseInt(waittime));
    /*
     * 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
     */
    try {
        setRobot(new Robot());
        clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        if (event.startsWith("KEY%")) {

            fireKeyEvent(event.split("%")[1]);
        } else if (event.startsWith("MOUSE%")) {

            fireMouseEvent(event.split("%")[1]);
        } else if (event.startsWith("VERIFY%")) {

            fireEventVerifyValue(event.split("%")[1]);
        } else {
            reportresult(true, "FIRE EVENT :", "FAILED", "Invalid event type passed :" + event);
            checkTrue(false, true, "Invalid event type passed :" + event);
        }

        reportresult(true, "FIRE EVENT Command : ", "PASSED", "Input Events = " + event);
    } catch (Exception e) {

        if (e.getMessage().startsWith("Command")) {
            e.printStackTrace();
            reportresult(true, "FIRE EVENT :", "FAILED",
                    "FIRE EVENT passed command is invalid (" + event + ")");
            checkTrue(false, true, "FIRE EVENT passed command is invalid (" + event + ") ");
        } else {
            e.printStackTrace();
            reportresult(true, "FIRE EVENT Command:", "FAILED",
                    "FIRE EVENT command cannot perform the event (" + event + ")");
            checkTrue(false, true, "FIRE EVENT command cannot cannot perform the event (" + event + ") ");

        }
    }
}

From source file:app.RunApp.java

/**
 * Save heatmap graph as image/*from www.  ja  v  a2s. co  m*/
 * 
 * @throws AWTException
 * @throws IOException 
 */
private void saveHeatmapGraph() throws AWTException, IOException {
    BufferedImage image = new Robot().createScreenCapture(
            new Rectangle(panelHeatmap.getLocationOnScreen().x + 31, panelHeatmap.getLocationOnScreen().y + 31,
                    panelHeatmap.getWidth() - 61, panelHeatmap.getHeight() - 61));
    JFileChooser fc = new JFileChooser();

    FileNameExtensionFilter fname1 = new FileNameExtensionFilter(".png", "png");

    fc.removeChoosableFileFilter(fc.getChoosableFileFilters()[0]);

    fc.setFileFilter(fname1);
    fc.addChoosableFileFilter(fname1);

    int returnVal = fc.showSaveDialog(this);

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = new File(fc.getSelectedFile().getAbsolutePath() + ".png");
        ImageIO.write(image, "png", file);

        JOptionPane.showMessageDialog(null, "File saved.", "Successful", JOptionPane.INFORMATION_MESSAGE);
        Toolkit.getDefaultToolkit().beep();
    }
}

From source file:app.RunApp.java

/**
 * Save co-ocurrence graph as image//from ww  w.ja v  a 2  s .c  o m
 * 
 * @throws AWTException
 * @throws IOException 
 */
private void saveCoocurrenceGraph() throws AWTException, IOException {
    BufferedImage image = new Robot().createScreenCapture(new Rectangle(
            panelCoOcurrenceRight.getLocationOnScreen().x, panelCoOcurrenceRight.getLocationOnScreen().y,
            panelCoOcurrenceRight.getWidth(), panelCoOcurrenceRight.getHeight()));

    JFileChooser fc = new JFileChooser();

    FileNameExtensionFilter fname1 = new FileNameExtensionFilter(".png", "png");

    fc.removeChoosableFileFilter(fc.getChoosableFileFilters()[0]);

    fc.setFileFilter(fname1);
    fc.addChoosableFileFilter(fname1);

    int returnVal = fc.showSaveDialog(this);

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = new File(fc.getSelectedFile().getAbsolutePath() + ".png");

        ImageIO.write(image, "png", file);

        JOptionPane.showMessageDialog(null, "File saved.", "Successful", JOptionPane.INFORMATION_MESSAGE);
        Toolkit.getDefaultToolkit().beep();
    }
}