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:org.zanata.util.TestEventForScreenshotListener.java

private void createScreenshot(String ofType) {
    File testIDDir = null;//  w w w.  j  a  v  a  2  s .  co  m
    try {
        testIDDir = ScreenshotDirForTest.screenshotForTest(testId);
        if (!testIDDir.exists()) {
            log.info("Creating screenshot dir {}", testIDDir.getAbsolutePath());
            boolean createdDirs = testIDDir.mkdirs();
            assert createdDirs;
        }
        String filename = generateFileName(ofType);
        File screenshotFile = new File(testIDDir, filename);

        Optional<Alert> alert = getAlert(driver);
        if (alert.isPresent()) {
            log.error(
                    "ChromeDriver screenshot({}) prevented by browser "
                            + "alert. Attempting Robot screenshot instead. " + "Alert text: {}",
                    testId, alert.get().getText());

            // warning: beta API: if it breaks, you can always use getScreenRectangle()
            WebDriver.Window window = driver.manage().window();
            Point pos = window.getPosition();
            Dimension size = window.getSize();

            Rectangle captureRectangle = new Rectangle(pos.x, pos.y, size.width, size.height);
            //                Rectangle captureRectangle = getScreenRectangle();

            BufferedImage capture = new Robot().createScreenCapture(captureRectangle);
            if (!ImageIO.write(capture, "png", screenshotFile)) {
                log.error("png writer not found for screenshot");
            }
        } else {
            File tempFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
            FileUtils.moveFile(tempFile, screenshotFile);
        }
        log.info("Screenshot saved to file: {}", filename);
    } catch (WebDriverException e) {
        throw new RuntimeException("[Screenshot]: Invalid WebDriver: ", e);
    } catch (IOException e) {
        throw new RuntimeException("[Screenshot]: Failed to write to " + testIDDir, e);
    } catch (NullPointerException e) {
        throw new RuntimeException("[Screenshot]: Null Object: ", e);
    } catch (AWTException e) {
        throw new RuntimeException("[Screenshot]: ", e);
    }
}

From source file:org.suren.autotest.web.framework.selenium.action.SeleniumClick.java

@Override
public void click(Element ele) {
    int errorTimes = 0;

    if (ele instanceof AbstractElement) {
        Object errObj = ((AbstractElement) ele).getData(ERR_TIMES);
        if (errObj instanceof Integer) {
            errorTimes = (Integer) errObj;
            if (errorTimes >= maxRetry) {
                return;
            }//  w  ww  .ja v a  2  s.  c om
        }
    }

    if (errorTimes > 0) {
        logger.warn(String.format("Click operation retry times [%s].", errorTimes));
    }

    ElementSearchStrategy<WebElement> searchStrategy = searchStrategyUtils.findStrategy(WebElement.class, ele);
    WebElement webEle = searchStrategy.search(ele);
    if (webEle == null) {
        throw new RuntimeException(
                String.format("Element [%s] can not found " + "by strategy [%s]!", ele, searchStrategy));
    }

    try {
        //??
        if (!(ele instanceof FileUpload) && !(engine.getDriver() instanceof RemoteWebDriver)) {
            Dimension size = webEle.getSize();
            Point loc = webEle.getLocation();
            int toolbarHeight = engine.getToolbarHeight();
            int x = size.getWidth() / 2 + loc.getX();
            int y = size.getHeight() / 2 + loc.getY() + toolbarHeight;

            new Robot().mouseMove(x, y);
        }

        webEle.click();

        //a??target????window?
        String tagName = webEle.getTagName();
        String targetAttr = webEle.getAttribute("target");
        if ("a".equals(tagName) && "_blank".equals(targetAttr)) {
            WebDriver driver = engine.getDriver();
            Set<String> handlers = driver.getWindowHandles();
            Iterator<String> it = handlers.iterator();
            while (it.hasNext()) {
                String name = it.next();

                driver.switchTo().window(name);
            }
        }
    } catch (WebDriverException e) {
        logger.error(String.format("[%s]??", webEle), e);
        if (ele instanceof AbstractElement) {
            ((AbstractElement) ele).putData(ERR_TIMES, ++errorTimes);
        }

        //?????
        if (e.getMessage().contains("is not clickable at point")) {
            logger.info("Will retry click operation, after element move.");

            new Actions(engine.getDriver()).moveToElement(webEle, -50, -50).perform();

            WebDriverWait wait = new WebDriverWait(engine.getDriver(), 30);
            ((JavascriptExecutor) engine.getDriver()).executeScript("arguments[0].scrollIntoView();", webEle,
                    -50, -50);
            wait.until(ExpectedConditions.visibilityOf(webEle));

            click(ele);
        }
    } catch (AWTException e) {
        e.printStackTrace();
    }
}

From source file:com.fanniemae.ezpie.actions.HighlightScan.java

protected void runHighlightAgent(Node nodeStep) {
    _hlAgentPath = _session.getAttribute(nodeStep, "HLAgentPath");
    if (_hlAgentPath == null) {
        throw new PieException("HLAgentPath not found in definition");
    }//from   w w w  . j  a va  2s.c om
    _session.addLogMessage("", "HighlightScan", "Running Highlight Agent at " + _hlAgentPath);
    try {
        this._robot = new Robot();
    } catch (AWTException e) {
        throw new PieException("Error while trying to start Highlight scan.", e);
    }
    startAgent();
    discoverFiles();
    scanFiles();
    confirmResults();
    saveResults();
    goToFolder();
    this._process.destroy();
}

From source file:org.squidy.nodes.Keyboard.java

@Override
public void onStart() throws ProcessException {
    try {//from   ww w.j a va2 s. com
        robot = new Robot();
        robot.setAutoDelay(0);
    } catch (AWTException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Couldn't initiate Robot.");
        }
        publishFailure(e);
    }

    if (openInputWindow) {
        inputWindow = InputWindow.getInstance();
        inputWindow.registerKeyListener(this);
    }
}

From source file:jdroidremote.ServerFrame.java

public static void typeCharacter(String letter) {
    System.out.println(letter);/*from www.j a v  a2s  .  c o  m*/
    Robot robot = null;
    try {
        robot = new Robot();
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    if (Character.isLetter(letter.charAt(0))) {
        try {
            boolean upperCase = Character.isUpperCase(letter.charAt(0));
            String variableName = "VK_" + letter.toUpperCase();

            KeyEvent ke = new KeyEvent(new JTextField(), 0, 0, 0, 0, ' ');
            Class clazz = ke.getClass();
            Field field = clazz.getField(variableName);
            int keyCode = field.getInt(ke);

            //System.out.println(keyCode + " = keyCode");
            robot.delay(80);

            if (upperCase) {
                robot.keyPress(KeyEvent.VK_SHIFT);
            }

            robot.keyPress(keyCode);
            robot.keyRelease(keyCode);

            if (upperCase) {
                robot.keyRelease(KeyEvent.VK_SHIFT);
            }
        } catch (Exception e) {
            System.out.println(e);
        }
    } else if (letter.equals(".")) {
        robot.keyPress(KeyEvent.VK_PERIOD); //keyCode 46
        robot.keyRelease(KeyEvent.VK_PERIOD);
    } else if (letter.equals("!")) {
        robot.keyPress(KeyEvent.VK_SHIFT); //keyCode 16
        robot.keyPress(KeyEvent.VK_1); //keycode 49
        robot.keyRelease(KeyEvent.VK_1);
        robot.keyRelease(KeyEvent.VK_SHIFT);
    } else if (letter.equals(" ")) {
        robot.keyPress(KeyEvent.VK_SPACE);
        robot.keyRelease(KeyEvent.VK_SPACE);
    } else if (letter.equals("?")) {
        robot.keyPress(KeyEvent.VK_SHIFT); //keyCode 16
        robot.keyPress(KeyEvent.VK_SLASH); //keyCode 47
        robot.keyRelease(KeyEvent.VK_SLASH);
        robot.keyRelease(KeyEvent.VK_SHIFT);
    } else if (letter.equals(",")) {
        robot.keyPress(KeyEvent.VK_COMMA);
        robot.keyRelease(KeyEvent.VK_COMMA);
    } else if (letter.equals("@enter")) {
        robot.keyPress(KeyEvent.VK_ENTER);
        robot.keyRelease(KeyEvent.VK_ENTER);
    } else if (letter.equals("@backspace")) {
        robot.keyPress(KeyEvent.VK_BACK_SPACE);
        robot.keyRelease(KeyEvent.VK_BACK_SPACE);
    }
}

From source file:com.mgmtp.jfunk.core.util.ScreenCapturer.java

/**
 * Captures the specified rectangle and saves it as png to the specified file. The file must
 * have the extension {@code png}. Any necessary but non-existent parent directories of the
 * specified file are created./* ww  w . j  a v a 2 s.c o  m*/
 * 
 * @param file
 *            the file to save the screenshot to
 * @param rectangle
 *            the rectangle to capture in screen coordinates
 */
public static void captureScreenRect(final File file, final Rectangle rectangle) {
    checkState(file.getName().endsWith("png"), "Screenshot file must have extension 'png': %s", file);
    LOGGER.trace("Creating screenshot: {}", file);

    try {
        createParentDirs(file);
        BufferedImage capture = new Robot().createScreenCapture(rectangle);
        ImageIO.write(capture, "png", file);
    } catch (AWTException ex) {
        throw new JFunkException("Error capturing screen", ex);
    } catch (IOException ex) {
        throw new JFunkException("Error saving screenshot", ex);
    }
}

From source file:visualize.Visualize.java

public static void makeScreenshot(final Rectangle rect, final int index) {
    try {/*w  w w .  ja v a  2  s.  co  m*/
        BufferedImage image = new Robot().createScreenCapture(rect);
        ImageIO.write(image, "png", new File("screenshot_" + index + ".png"));
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.cytoscape.ding.impl.cyannotator.dialogs.LoadImageDialog.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    try {/*from   www .j a  v  a  2 s  .  c o m*/
        //Read the selected Image, create an Image Annotation, repaint the whole network and then dispose off this Frame
        File imageFile = jFileChooser1.getSelectedFile(); // Get the file
        BufferedImage image = ImageIO.read(imageFile);
        URL url = imageFile.toURI().toURL();
        //The Attributes are x, y, Image, componentNumber, scaleFactor
        ImageAnnotationImpl newOne = new ImageAnnotationImpl(cyAnnotator, view, (int) startingLocation.getX(),
                (int) startingLocation.getY(), url, image, view.getZoom(), cgm);

        newOne.addComponent(null);
        cyAnnotator.addAnnotation(newOne);
        newOne.getCanvas().repaint();

        // Set this shape to be resized
        cyAnnotator.resizeShape(newOne);

        try {
            // Warp the mouse to the starting location (if supported)
            Point start = newOne.getComponent().getLocationOnScreen();
            Robot robot = new Robot();
            robot.mouseMove((int) start.getX() + 100, (int) start.getY() + 100);
        } catch (Exception e) {
        }

        this.dispose();
    } catch (Exception ex) {
        logger.warn("Unable to load the selected image", ex);
    }
}

From source file:com.truven.report.reporter.Reporter.java

/**
 * Save screen shot.//from   w ww  .  j a va2s . c om
 *
 * @param reportFolderLocation the report folder location
 * @return the string
 */
private String saveScreenShot(final String reportFolderLocation) {

    Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");
    String timestamp = sdf.format(date);
    Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
    BufferedImage capture;
    String screenShotFile = timestamp + ".png";
    String screenShotImgFolder = reportFolderLocation + File.separator + "images";
    try {
        capture = new Robot().createScreenCapture(screenRect);
        File screenShotImgFolderFile = new File(screenShotImgFolder);

        if (!screenShotImgFolderFile.exists() && !screenShotImgFolderFile.mkdirs()) {

            throw new RuntimeException(
                    "Cannot create new folder in location " + screenShotImgFolderFile.getAbsolutePath());
        }
        File screenShotImg = new File(screenShotImgFolder + File.separator + screenShotFile);
        ImageIO.write(capture, "png", screenShotImg);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (AWTException e1) {
        e1.printStackTrace();
    } catch (Exception e2) {
        e2.printStackTrace();
    }
    return screenShotFile;
}

From source file:org.jboss.arquillian.extension.screenRecorder.ScreenRecorder.java

private BufferedImage getDesktopScreenshot() {
    try {/*from  ww  w.jav a2 s.co m*/
        Robot robot = new Robot();
        Rectangle captureSize = new Rectangle(screenBounds);
        return robot.createScreenCapture(captureSize);
    } catch (AWTException e) {
        logger.error("Exception occured while taking screenshot for video record", e);
        return null;
    }
}