When I upload the file using awt.Robot class, the file is uploaded properly but my laptop keys don't function properly after my test cases execution

56 views Asked by At

When I upload the file using awt.Robot class, the file is uploaded properly but my laptop keys don't function properly after my test cases execution. I have to restart my laptop.

For example, after executing my test cases which has file upload method using Robot class, if I try to open any other folder in my system, it won't work,, in notepad if I press "S" or any key on the keyboard some random actions happen such as save popup opens or print popup opens or Find popup opens but the required action won't.

Below is the method that I am using to upload the file:

    public void fileUploadFile(String fileName) {
    logger.info("Inside - " + new Exception().getStackTrace()[0].getMethodName());
    String filePath = System.getProperty("user.dir") + File.separator + "src" + File.separator + "test"
            + File.separator + "resources" + File.separator + fileName;
    
    try {
        
        javascriptExecutor.executeScript("arguments[0].click()", fileUploadPO.fileUpload());
        Thread.sleep(3000);

        // creating object of Robot class
        Robot robot = new Robot();

        // copying File path to Clipboard
        StringSelection stringSelection = new StringSelection(filePath);
    //  Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        clipboard.setContents(stringSelection, null);
     
        // press Contol+V for pasting
        robot.keyPress(KeyEvent.VK_CONTROL);
        Thread.sleep(500);
        robot.keyPress(KeyEvent.VK_V);
        Thread.sleep(500);

        // release Contol+V for pasting
        robot.keyRelease(KeyEvent.VK_CONTROL);
        Thread.sleep(500);
        robot.keyRelease(KeyEvent.VK_V);
        Thread.sleep(500);

        // for pressing and releasing Enter
        robot.keyPress(KeyEvent.VK_CONTROL);
        Thread.sleep(500);
        robot.keyPress(KeyEvent.VK_ENTER);
        Thread.sleep(500);
    } catch (AWTException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
} 
1

There are 1 answers

1
Prophet On

I see you are pressing keys here:

robot.keyPress(KeyEvent.VK_CONTROL);
Thread.sleep(500);
robot.keyPress(KeyEvent.VK_V);
Thread.sleep(500);

Then you release these keys here

robot.keyRelease(KeyEvent.VK_CONTROL);
Thread.sleep(500);
robot.keyRelease(KeyEvent.VK_V);
Thread.sleep(500);

Then you press keys here

robot.keyPress(KeyEvent.VK_CONTROL);
Thread.sleep(500);
robot.keyPress(KeyEvent.VK_ENTER);
Thread.sleep(500);

but never releasing them. So your keys are stay pressed forever.