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:com.netease.dagger.BrowserEmulator.java

/**
 * Open new tab in browser/*from w w  w.j  a v  a 2 s  . c  om*/
 */
public void openNewTAB() {
    pause(stepInterval);
    try {
        Robot robot = new Robot();
        robot.keyPress(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_T);
        robot.keyRelease(KeyEvent.VK_CONTROL);
        robot.keyRelease(KeyEvent.VK_T);
    } catch (Exception e) {
        e.printStackTrace();
        handleFailure("Failed to open new TAB");
    }
    logger.info("Success to open new TAB");
}

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

/**
 * Moves already taken screenshot and uses it as a 'before' one. Then
 * takes another screenshot./* w ww  .  j  a  v a2 s. c  om*/
 */
private void takeScreenshot(File before, TestClass testClass, Method testMethod, String appender)
        throws AWTException, IOException {
    File testClassDirectory = getDirectory(configuration.getScreenshotFolder(), testClass);
    testClassDirectory.mkdirs();

    File beforeDestination = FileUtils.getFile(testClassDirectory,
            testMethod.getName() + "_before." + configuration.getImageFileType());
    if (beforeDestination.exists()) {
        beforeDestination.delete();
    }
    FileUtils.moveFile(before, beforeDestination);

    Rectangle screenSize = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
    BufferedImage image = new Robot().createScreenCapture(screenSize);
    String imageName = testMethod.getName() + "_" + appender + "." + configuration.getImageFileType();

    File outputFile = FileUtils.getFile(testClassDirectory, imageName);
    if (outputFile.exists()) {
        outputFile.delete();
    }
    ImageIO.write(image, configuration.getImageFileType().toString(), outputFile);
}

From source file:org.eclipse.jubula.rc.swing.driver.RobotAwtImpl.java

/**
 * Creates a new instance. /*from  w w w  .j  a va2s .c om*/
 * @param factory The Robot factory instance.
 * @throws RobotException If the AWT-Robot cannot be created.
 */
public RobotAwtImpl(IRobotFactory factory) throws RobotException {
    // HERE init robot in the AWT Event Dispatch Thread on Linux ??? (see
    // http://www.netbeans.org/issues/show_bug.cgi?id=37476)
    try {
        m_robot = new Robot();
        m_robot.setAutoWaitForIdle(false);
        m_robot.setAutoDelay(0);
    } catch (AWTException awte) {
        log.error(awte);
        m_robot = null;
        throw new RobotException(awte);
    } catch (SecurityException se) {
        log.error(se);
        m_robot = null;
        throw new RobotException(se);
    }
    m_interceptor = factory.getRobotEventInterceptor();
    m_mouseMotionTracker = factory.getMouseMotionTracker();
    m_queuer = factory.getEventThreadQueuer();
    m_eventFlusher = new EventFlusher(m_robot, FLUSH_TIMEOUT);
}

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

/**
 * Takes screenshot and saves it into a temporary file.
 *///from w  w w. j  a v  a2s  .co  m
private File takeScreenshot() throws AWTException, IOException {
    Rectangle screenSize = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
    BufferedImage image = new Robot().createScreenCapture(screenSize);
    File temp = File.createTempFile("arquillian-screen-recorder", "." + configuration.getImageFileType());
    temp.deleteOnExit();
    ImageIO.write(image, configuration.getImageFileType().toString(), temp);
    return temp;
}

From source file:com.pentaho.ctools.issues.cde.CDE417.java

/**
 * ############################### Test Case 1 ###############################
 *
 * Test Case Name: /*from  www  .j av a  2 s .c  o m*/
 *   Popup Export issues
 *
 * Description: 
 *   CDE-417 issue, so when user clicks to export chart, popup shown has chart preview. 
 *   CDE-424 issue we'll delete the .js file prior to opening the dashboard and saving the dashboard should create 
 *   the .js file again and enable exporting.
 *   CDF-448 exporting chart with skip ticks (chart is too small to show all labels) is successful
 *   CDF-502 export chart with array parameters is successful
 *   CDE-514 all charts are available on charts to export property and all elements are available on the data to export property
 *   
 * Steps:
 * 424
 *    1. Open PUC and click Browse Files
 *    2. Go to dashboard folder, click countryChart.js file and click Move To Trash
 *    3. Open created sample and save Dashboard
 * 514
 *    4. Go to Export Component and assert all charts appear on the Chart to Export property
 *    5. Assert all charts and the table appear on data to export property
 *    
 * 417/448/502
 *    6. Click to export chart, click export, assert chart is shown and assert export works as expected (448 and 502)
 *    7. Click to export chart2, click export, assert chart is shown and assert export works as expected
 * 
 * @throws InterruptedException
 *
 */
@Test
public void tc01_PopupExportComponent_PreviewerRendersChart() throws InterruptedException {
    this.log.info("tc01_PopupExportComponent_PreviewerRendersChart");

    /*
     * ## Step 1
     */
    //Show Hidden Files
    BrowseFiles browser = new BrowseFiles(driver);
    if (!PUCSettings.SHOWHIDDENFILES) {
        browser.CheckShowHiddenFiles();
    }

    /*
     * ## Step 2
     */
    //String pathChart = "/public/Issues/CDF/CDF-548/chart.js";
    //String pathCdfChart = "/public/Issues/CDF/CDF-548/CDF-548_chart.js";
    String pathCountryChart = "/public/Issues/CDF/CDF-548/countryChart.js";
    String pathCdfCountryChart = "/public/Issues/CDF/CDF-548/CDF-548_countryChart.js";
    //boolean fileDeleteChart = browser.DeleteFile( pathChart );
    //boolean fileDeleteCdfChart = browser.DeleteFile( pathCdfChart );
    boolean fileDeleteCountryChart = browser.DeleteFile(pathCountryChart);
    boolean fileDeleteCdfCountryChart = browser.DeleteFile(pathCdfCountryChart);
    //assertTrue( fileDeleteChart );
    //assertTrue( fileDeleteCdfChart );
    assertTrue(fileDeleteCountryChart);
    assertTrue(fileDeleteCdfCountryChart);

    driver.switchTo().defaultContent();
    WebDriver frame = driver.switchTo().frame("browser.perspective");
    this.elemHelper.WaitForAttributeValue(frame, By.xpath("//div[@id='fileBrowserFiles']/div[2]/div[1]"),
            "title", "CDF-548.cda");
    String nameOfCdf548Wcdf = this.elemHelper.GetAttribute(frame,
            By.xpath("//div[@id='fileBrowserFiles']/div[2]/div[1]"), "title");
    assertEquals("CDF-548.cda", nameOfCdf548Wcdf);

    /*
     * ## Step 3
     */
    // Go to Export Popup Component sample in Edit mode
    driver.get(baseUrl + "api/repos/%3Apublic%3AIssues%3ACDF%3ACDF-548%3ACDF-548.wcdf/edit");

    //Save Dashboard
    WebElement saveButton = this.elemHelper.WaitForElementPresenceAndVisible(driver, By.id("Save"));
    assertNotNull(saveButton);
    this.elemHelper.Click(driver, By.id("Save"));
    WebElement saveNotify = this.elemHelper.WaitForElementPresenceAndVisible(driver,
            By.cssSelector("div.notify-bar-message"));
    assertNotNull(saveNotify);
    String saveMessage = this.elemHelper.WaitForElementPresentGetText(driver,
            By.cssSelector("div.notify-bar-message"));
    assertEquals("Dashboard saved successfully", saveMessage);

    /* 
     * ## Step 4 
      */
    //Go to components panel and expand "Others"
    WebElement componentsPanelButton = this.elemHelper.FindElement(driver,
            By.cssSelector("div.componentsPanelButton"));
    assertNotNull(componentsPanelButton);
    componentsPanelButton.click();
    WebElement componentsTable = this.elemHelper.FindElement(driver, By.id("cdfdd-components-components"));
    assertNotNull(componentsTable);
    WebElement othersExpander = this.elemHelper.FindElement(driver,
            By.xpath("//table[@id='table-cdfdd-components-components']//tr[@id='OTHERCOMPONENTS']/td/span"));
    assertNotNull(othersExpander);
    othersExpander.click();

    //Select Export Popup Component
    WebElement exportPopupElement = this.elemHelper.FindElement(driver,
            By.xpath("//table[@id='table-cdfdd-components-components']//td[contains(text(),'exportPopup')]"));
    assertNotNull(exportPopupElement);
    exportPopupElement.click();

    //Open options for Chart Component to Export and assert "chart" and "countryChart"
    WebElement chartExportProperty = this.elemHelper.FindElement(driver, By.xpath(
            "//table[@id='table-cdfdd-components-properties']//td[@title='Id for Chart Component to Export']/../td[2]"));
    assertNotNull(chartExportProperty);
    chartExportProperty.click();
    WebElement chartExportInput = this.elemHelper.FindElement(driver, By.xpath(
            "//table[@id='table-cdfdd-components-properties']//td[@title='Id for Chart Component to Export']/../td[2]/form/input"));
    assertNotNull(chartExportInput);
    chartExportInput.clear();
    Robot robot;
    try {
        robot = new Robot();
        robot.keyPress(KeyEvent.VK_DOWN);
        robot.keyRelease(KeyEvent.VK_DOWN);
    } catch (AWTException e) {
        e.printStackTrace();
    }
    WebElement chartExportOptions = this.elemHelper.FindElement(driver, By.xpath("//body/ul"));
    assertNotNull(chartExportOptions);
    String chartOption1 = this.elemHelper.WaitForElementPresentGetText(driver, By.xpath("//body/ul/li/a"));
    String chartOption2 = this.elemHelper.WaitForElementPresentGetText(driver, By.xpath("//body/ul/li[2]/a"));
    assertEquals("chart", chartOption1);
    assertEquals("countryChart", chartOption2);
    this.elemHelper.Click(driver, By.xpath("//body/ul/li/a"));

    /* 
     * ## Step 5 
      */
    //Open options for Data Component to Export and assert "table", "chart" and "countryChart"
    WebElement dataExportProperty = this.elemHelper.FindElement(driver, By.xpath(
            "//table[@id='table-cdfdd-components-properties']//td[@title='Id for Data Component to Export']/../td[2]"));
    assertNotNull(dataExportProperty);
    dataExportProperty.click();
    WebElement dataExportInput = this.elemHelper.FindElement(driver, By.xpath(
            "//table[@id='table-cdfdd-components-properties']//td[@title='Id for Data Component to Export']/../td[2]/form/input"));
    assertNotNull(dataExportInput);
    dataExportInput.clear();
    Robot robot1;
    try {
        robot1 = new Robot();
        robot1.keyPress(KeyEvent.VK_DOWN);
        robot1.keyRelease(KeyEvent.VK_DOWN);
    } catch (AWTException e) {
        e.printStackTrace();
    }
    WebElement dataExportOptions = this.elemHelper.FindElement(driver, By.xpath("//body/ul"));
    assertNotNull(dataExportOptions);
    String dataOption1 = this.elemHelper.WaitForElementPresentGetText(driver, By.xpath("//body/ul/li/a"));
    String dataOption2 = this.elemHelper.WaitForElementPresentGetText(driver, By.xpath("//body/ul/li[2]/a"));
    String dataOption3 = this.elemHelper.WaitForElementPresentGetText(driver, By.xpath("//body/ul/li[3]/a"));
    assertEquals("table", dataOption1);
    assertEquals("chart", dataOption2);
    assertEquals("countryChart", dataOption3);

    /* 
     * ## Step 6 
     */
    driver.get(baseUrl + "api/repos/%3Apublic%3AIssues%3ACDF%3ACDF-548%3ACDF-548.wcdf/generatedContent");
    this.elemHelper.WaitForElementInvisibility(driver, By.cssSelector("div.blockUI.blockOverlay"));

    //Click export Button
    WebElement exportChartButton = this.elemHelper.FindElement(driver, By.xpath("//div[@id='export']/div"));
    assertNotNull(exportChartButton);
    exportChartButton.click();

    //Assert popup and click Export Chart link
    WebElement exportChartLink = this.elemHelper.FindElement(driver, By.cssSelector("div.exportElement"));
    assertNotNull(exportChartLink);
    exportChartLink.click();

    //Assert chart popup
    WebElement exportChartPopup = this.elemHelper.FindElement(driver, By.id("fancybox-content"));
    assertNotNull(exportChartPopup);

    // Check URL of displayed image
    String chartSRCUrl = this.elemHelper.GetAttribute(driver,
            By.xpath("//div[@id='fancybox-content']/div/div/div/div[2]/img"), "src");
    assertEquals(baseUrl
            + "plugin/cgg/api/services/draw?outputType=png&script=%2Fpublic%2FIssues%2FCDF%2FCDF-548%2Fchart.js&paramcountries=France&paramcountries=USA&paramwidth=400&paramheight=400",
            chartSRCUrl);
    assertEquals(200, HttpUtils.GetResponseCode(chartSRCUrl, "admin", "password"));

    // Export chart and assert export was successful
    WebElement chartExportButton = this.elemHelper.FindElement(driver,
            By.cssSelector("div.exportChartPopupButton.exportChartOkButton"));
    assertNotNull(chartExportButton);

    //Click export and assert file is correctly downloaded
    try {
        //Delete the existence if exist
        new File(this.exportFilePath).delete();

        //Click to export
        chartExportButton.click();

        //Wait for file to be created in the destination dir
        DirectoryWatcher dw = new DirectoryWatcher();
        dw.WatchForCreate(downloadDir);

        //Check if the file really exist
        File exportFile = new File(this.exportFilePath);
        // assertTrue(exportFile.exists());

        //Wait for the file to be downloaded totally
        for (int i = 0; i < 50; i++) { //we only try 50 times == 5000 ms
            long nSize = FileUtils.sizeOf(exportFile);
            //Since the file always contents the same data, we wait for the expected bytes
            if (nSize >= 10000) {
                break;
            }
            this.log.info("BeforeSleep " + nSize);
            Thread.sleep(100);
        }

        this.log.info("File size :" + FileUtils.sizeOf(exportFile));

        //Check if the file downloaded is the expected
        String md5 = DigestUtils.md5Hex(Files.readAllBytes(exportFile.toPath()));
        assertEquals(md5, "c8c3ad02461f7b5c8a36ee2aec0eca95");

        //The delete file
        DeleteFile();

    } catch (Exception e) {
        this.log.error(e.getMessage());
    }

    // Close dialog box
    this.elemHelper.Click(driver, By.id("fancybox-close"));
    assertTrue(this.elemHelper.WaitForElementNotPresent(driver,
            By.xpath("//div[@id='fancybox-content']/div/div/div/div/div[1]")));

    /* 
     * ## Step 7
     */
    this.elemHelper.WaitForElementInvisibility(driver, By.cssSelector("div.exportElement"));
    //Click export Button
    WebElement exportCountryChartButton = this.elemHelper.FindElement(driver,
            By.xpath("//div[@id='export2']/div"));
    assertNotNull(exportCountryChartButton);
    exportCountryChartButton.click();

    //Assert popup and click Export Chart link
    WebElement exportCountryChartLink = this.elemHelper.FindElement(driver,
            By.xpath("//div[contains(text(),'Export Chart2')]"));
    assertNotNull(exportCountryChartLink);
    exportCountryChartLink.click();

    //Assert chart popup
    WebElement exportCountryChartPopup = this.elemHelper.FindElement(driver, By.id("fancybox-content"));
    assertNotNull(exportCountryChartPopup);

    // Check URL of displayed image
    String countryChartSRCUrl = this.elemHelper.GetAttribute(driver,
            By.xpath("//div[@id='fancybox-content']/div/div/div/div[2]/img"), "src");
    assertEquals(baseUrl
            + "plugin/cgg/api/services/draw?outputType=svg&script=%2Fpublic%2FIssues%2FCDF%2FCDF-548%2FcountryChart.js&paramwidth=400&paramheight=300",
            countryChartSRCUrl);
    assertEquals(200, HttpUtils.GetResponseCode(countryChartSRCUrl, "admin", "password"));

    // Export chart and assert export was successful
    WebElement countryChartExportButton = this.elemHelper.FindElement(driver,
            By.cssSelector("div.exportChartPopupButton.exportChartOkButton"));
    assertNotNull(countryChartExportButton);

    //Click export and assert file is correctly downloaded
    try {
        //Delete the existence if exist
        new File(this.exportFilePath2).delete();

        //Click to export
        countryChartExportButton.click();

        //Wait for file to be created in the destination dir
        DirectoryWatcher dw = new DirectoryWatcher();
        dw.WatchForCreate(downloadDir);

        //Check if the file really exist
        File exportFile = new File(this.exportFilePath2);
        // assertTrue(exportFile.exists());

        //Wait for the file to be downloaded totally
        for (int i = 0; i < 50; i++) { //we only try 50 times == 5000 ms
            long nSize = FileUtils.sizeOf(exportFile);
            //Since the file always contents the same data, we wait for the expected bytes
            if (nSize >= 30000) {
                break;
            }
            this.log.info("BeforeSleep " + nSize);
            Thread.sleep(100);
        }

        this.log.info("File size :" + FileUtils.sizeOf(exportFile));

        //Check if the file downloaded is the expected
        String md5 = DigestUtils.md5Hex(Files.readAllBytes(exportFile.toPath()));
        assertEquals(md5, "c0d04625306dd1f32afed115c0bf94be");

        //The delete file
        DeleteFile();

    } catch (Exception e) {
        this.log.error(e.getMessage());
    }

    // Close dialog box
    this.elemHelper.Click(driver, By.id("fancybox-close"));
    assertTrue(this.elemHelper.WaitForElementNotPresent(driver,
            By.xpath("//div[@id='fancybox-content']/div/div/div/div/div[1]")));
}

From source file:com.netease.dagger.BrowserEmulator.java

/**
 * Close previous tab in browser// ww  w. ja  v a2 s .  co m
 */
public void closePreviousTAB() {
    pause(stepInterval);
    try {
        Robot robot = new Robot();
        robot.keyPress(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_PAGE_UP);
        robot.keyRelease(KeyEvent.VK_CONTROL);
        robot.keyRelease(KeyEvent.VK_PAGE_UP);
        robot.keyPress(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_W);
        robot.keyRelease(KeyEvent.VK_CONTROL);
        robot.keyRelease(KeyEvent.VK_W);
    } catch (Exception e) {
        e.printStackTrace();
        handleFailure("Failed to close previous TAB");
    }
    logger.info("Success to close previous TAB");
}

From source file:com.photon.phresco.Screens.InvalidJarBase.java

public void instantiateBrowser(String selectedBrowser, String selectedPlatform, String applicationURL,
        String applicationContext) throws ScreenException, MalformedURLException {

    if (selectedBrowser.equalsIgnoreCase(Constants.BROWSER_CHROME)) {
        try {/*  www . java2  s .c  o m*/
            // "D:/Selenium-jar/chromedriver_win_19.0.1068.0/chromedriver.exe"
            chromeService = new ChromeDriverService.Builder()
                    .usingDriverExecutable(new File(getChromeLocation())).usingAnyFreePort().build();

            log.info("-------------***LAUNCHING GOOGLECHROME***--------------");

            driver = new ChromeDriver(chromeService);
            //driver.manage().window().maximize();
            //   driver = new ChromeDriver(chromeService, chromeOption);
            // driver.manage().timeouts().implicitlyWait(30,
            // TimeUnit.SECONDS);            
            //driver.navigate().to(applicationURL + applicationContext);
            driver.manage().window().maximize();
            driver.navigate().to(applicationURL + applicationContext);

        } catch (Exception e) {
            e.printStackTrace();
        }

    } else if (selectedBrowser.equalsIgnoreCase(Constants.BROWSER_IE)) {
        log.info("---------------***LAUNCHING INTERNET EXPLORE***-----------");
        driver = new InternetExplorerDriver();
        driver.manage().window().maximize();
        driver.navigate().to(applicationURL + applicationContext);

    } else if (selectedBrowser.equalsIgnoreCase(Constants.BROWSER_FIREFOX)) {
        log.info("-------------***LAUNCHING FIREFOX***--------------");
        driver = new FirefoxDriver();
        driver.manage().window().maximize();
        driver.navigate().to(applicationURL + applicationContext);

    } else if (selectedBrowser.equalsIgnoreCase(Constants.BROWSER_OPERA)) {
        log.info("-------------***LAUNCHING OPERA***--------------");
        System.out.println("******entering window maximize********");
        try {
            System.out.println("******entering window maximize********");
            Robot robot;
            try {
                robot = new Robot();
                robot.keyPress(KeyEvent.VK_ALT);
                robot.keyPress(KeyEvent.VK_SPACE);
                robot.keyRelease(KeyEvent.VK_ALT);
                robot.keyRelease(KeyEvent.VK_SPACE);
                robot.keyPress(KeyEvent.VK_X);
                robot.keyRelease(KeyEvent.VK_X);
            } catch (AWTException e) {

                e.printStackTrace();
            }

        } catch (Exception e) {

            e.printStackTrace();
        }

    } else {
        throw new ScreenException("------Only FireFox,InternetExplore and Chrome works-----------");
    }

}

From source file:net.sourceforge.docfetcher.util.AppUtil.java

public static void sendHotkeyToFront() {
    try {//from w ww. ja  v  a  2 s.com
        int one = SettingsConf.IntArray.HotkeyToFront.get()[0];
        one = KeyCodeTranslator.translateSWTKey(one);
        int two = SettingsConf.IntArray.HotkeyToFront.get()[1];
        two = KeyCodeTranslator.translateSWTKey(two);
        Robot robot = new Robot();
        robot.keyPress(one);
        robot.keyPress(two);
        robot.delay(500);
        robot.keyRelease(two);
        robot.keyRelease(one);
    } catch (AWTException e) {
        AppUtil.showStackTrace(e);
    }
}

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

@Override
public void onStart() {

    // Search minimum/maximum of x/y.
    GraphicsDevice[] devices = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices();
    screenBounds = new Rectangle[devices.length];
    for (int i = 0; i < devices.length; i++) {
        GraphicsDevice device = devices[i];
        GraphicsConfiguration gc = device.getDefaultConfiguration();
        Rectangle bounds = gc.getBounds();
        screenBounds[i] = bounds;/*w w w  .  j av a2 s.  co  m*/

        double x, y;
        x = bounds.getX();
        minX = Math.min(minX, x);
        x += bounds.getWidth();
        maxX = Math.max(maxX, x);
        y = bounds.getY();
        minY = Math.min(minY, y);
        y += bounds.getHeight();
        maxY = Math.max(maxY, y);
    }

    width = Math.abs(minX) + Math.abs(maxX);
    height = Math.abs(minY) + Math.abs(maxY);

    try {
        robot = new Robot();
        robot.setAutoDelay(0);
    } catch (AWTException e) {
        if (LOG.isErrorEnabled())
            LOG.error("Could not initialize Robot.");
        publishFailure(e);
    }

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

    if (directInput && isWindows) {
        if (cdim == null) {
            createDirectInputMouse();
            if (cdim != null) {
                if (cdim.Init(0) != 0) {
                    cdim = null;
                    publishFailure(new SquidyException("Could not initialize DirectInput mouse."));
                }
            }
        }
        if (cdim != null) {
            if (cdim.StartCapture() != 0)
                publishFailure(new SquidyException("Could not start DirectInput mouse."));
            else
                new Thread(new Runnable() {
                    public void run() {
                        while (processing) {
                            cdim.WaitForBufferedData();
                            if (processing)
                                processDirectInputMouseBufferedData();
                        }
                    }
                }, getId() + "_DIM").start();
        }
    }
}