Entering Username/Password in Authentication pop-up window - java

When I launch a website from Eclipse (selenium) it pops up a authentication box as below:
Here I am unable to enter Username and password, here are the things I tried:
1) Switching of Handle to pop up and identifying Xpath
2) Sending Username and Password in the URL (How to handle login pop up window using Selenium WebDriver?)
3) Sikuli (but requires image capture when executed in different system)
4) Using Robot function
Robot rb = new Robot();
StringSelection username = new StringSelection("XXXXX");
System.out.println("Entering username");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(username, null);
rb.keyPress(KeyEvent.VK_CONTROL);
rb.keyPress(KeyEvent.VK_V);
rb.keyRelease(KeyEvent.VK_V);
rb.keyRelease(KeyEvent.VK_CONTROL);
//tab to password entry field
rb.keyPress(KeyEvent.VK_TAB);
rb.keyRelease(KeyEvent.VK_TAB);
Thread.sleep(2000);
//Enter password by ctrl-v
StringSelection pwd = new StringSelection("YYYYYYY");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(pwd, null);
rb.keyPress(KeyEvent.VK_CONTROL);
rb.keyPress(KeyEvent.VK_V);
rb.keyRelease(KeyEvent.VK_V);
rb.keyRelease(KeyEvent.VK_CONTROL);
//press enter
rb.keyPress(KeyEvent.VK_ENTER);
rb.keyRelease(KeyEvent.VK_ENTER);
None of the above worked till now, just after reaching the website (driver.get(URL)) the control does not seem to come back to eclipse

Use AutoIT scripts to fill that windows. That is the only way to elegantly handle this issue in Windows with Selenium. Check Handle Windows based Authentication Pop Up in Selenium using AutoIt at http://www.toolsqa.com/selenium-webdriver/autoit-selenium-webdriver/

The below code should work, it can be refactored :)
driver.navigate().to("url");
StringSelection selection = new StringSelection("username");
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(selection, selection);
Thread.sleep(5000);
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.delay(2000);
selection = new StringSelection("password");
clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(selection, selection);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.delay(1000);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);

Related

File not getting uploaded using java.awt.Robot class in Java

I tried implementing Robot class in my Selenium Test cases written using Java. I am getting a strange issue there. So when I am trying to run those test cases on my local machine (Windows 10 Enterprise Edition) and monitoring it's working fine and the file is getting uploaded. But when I am trying to run those in a remote server (Windows Server 2012) and monitoring those it's again working fine but when I am leaving those test cases for the entire night to run I found that the File Explorer dialogue box is opening but it's never getting close. It might be that the file path is not getting pasted and the Enter (Ok) button is not getting clicked.
public void uploadFile(String path) {
String abspath = _getAbsolutePath(path);
StringSelection stringSelection = new StringSelection(abspath);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
Robot robot = null;
try {
// native key strokes for CTRL, V and ENTER keys
robot = new Robot();
robot.setAutoDelay(5000);
robot.keyPress(KeyEvent.VK_CONTROL); // Press Ctrl
robot.keyPress(KeyEvent.VK_V); // Pres V
robot.keyRelease(KeyEvent.VK_V); // Release Ctrl
robot.keyRelease(KeyEvent.VK_CONTROL); // Release V
robot.setAutoDelay(5000);
robot.keyPress(KeyEvent.VK_ENTER); // Press Enter
robot.keyRelease(KeyEvent.VK_ENTER); // Release Enter
} catch (Exception exp) {
exp.printStackTrace();
}
}

How do I handle Proxy Authentication with Selenium using Java?

I've tried this code, but I doesn't do anything. Probably because it doesn't handle this kind of alert.
driver.switchTo().alert().sendKeys("asd");
// Handling Password alert
driver.switchTo().alert().sendKeys("asd");
driver.switchTo().alert().accept();
Am I missing something here? Thanks for your help.
you can do it by using Java robot class.
//set first variable in system clipboard
StringSelection variable1 = new StringSelection("username");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(variable1,null);
//use robot class to paste the content
Robot r = new Robot();
r.keyPress(KeyEvent.VK_CONTROL);
r.keyPress(KeyEvent.VK_V);
r.keyRelease(KeyEvent.VK_V);
r.keyRelease(KeyEvent.VK_CONTROL);
//use robot class to enter tab, so the focus will be shifted in to next field
r.keyPress(KeyEvent.VK_TAB);
r.keyRelease(KeyEvent.VK_TAB);
//set second variable in system clipboard
StringSelection variable2 = new StringSelection("password");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(variable2,null);
//use robot class to paste the content
r.keyPress(KeyEvent.VK_CONTROL);
r.keyPress(KeyEvent.VK_V);
r.keyRelease(KeyEvent.VK_V);
r.keyRelease(KeyEvent.VK_CONTROL);
use robot class to press tab, so the focus will be shifted in to next field if it is ok button, use robot class to enter enter key other wise again use tab
r.keyPress(KeyEvent.VK_TAB);
r.keyRelease(KeyEvent.VK_TAB);
r.keyPress(KeyEvent.VK_ENTER);
r.keyRelease(KeyEvent.VK_ENTER);

Download a file in IE using Selenium

OK, so I am trying to export a file using Selenium. My browser is IE. When I click on the export button a native windows dialogue box comes up.
Image of the pop up
I have to click on the Save button. For this I tried using AutoIT but its not working.
exportbutton.click();
Thread.sleep(2000);
driver.switchTo().activeElement();
AutoItX x = new AutoItX();
x.winActivate("window name");
x.winWaitActive("window name");
x.controlClick("window name", "", "[CLASS:Button; INSTANCE:2]");
This did not work. So I decided to use Robot class and perform the keyboard clicks Atl + S, as this will also enable the browser to Save the file. That did not work either.
try
{
Robot robot = new Robot();
robot.setAutoDelay(250);
robot.keyPress(KeyEvent.VK_ALT);
Thread.sleep(1000);
robot.keyPress(KeyEvent.VK_S);
robot.keyRelease(KeyEvent.VK_ALT);
robot.keyRelease(KeyEvent.VK_S);
}
catch (AWTException e)
{
e.printStackTrace();
}
There is some problem with the web driver I suppose because I tried printing a line after exportbutton.click() and it did not get printed either.
I am new so I can't understand the problem. Please help me out.
So, the problem was that the cursor gets stuck sometimes when you call the click() function. So as a solution I used the Robot class to move my cursor and click on the export button and then I used Robot class to press Alt+S, which is a keyboard shortcut to save a file in IE.
To click on the button I used
try
{
Robot robot = new Robot();
Thread.sleep(2000);
robot.mouseMove(coordinates.getX()+100,coordinates.getY()-400);
Thread.sleep(2000);
robot.mousePress( InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
}
catch (AWTException e)
{
e.printStackTrace();
}
To get the coordinates in the above snippet I used the following line
Point coordinates = driver.findElement(By.id("id")).getLocation();
System.out.println("Co-ordinates"+coordinates);
And to press Alt+S I used the following code
try
{
Robot robot = new Robot();
robot.setAutoDelay(250);
robot.keyPress(KeyEvent.VK_ALT);
Thread.sleep(1000);
robot.keyPress(KeyEvent.VK_S);
robot.keyRelease(KeyEvent.VK_ALT);
robot.keyRelease(KeyEvent.VK_S);
}
catch (AWTException e)
{
e.printStackTrace();
}
I had the same problem. I came to realization that
button.click()
does not work very well in this case (with IE driver). So instead of clicking the button I tried this:
robot = new Robot();
button.sendKeys("""");
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
This just gives focus on button and 'presses' it by hitting enter.
Sorry, I wrote approach how to upload the file. If you want to download - use the same approach, but use another buttons: Instead buttons Cntrl + V you can use button Tab to find control of Save/Save as and then Press Enter. Before it, you can paste String with file path ( directory where you want to upload your file).
Auto IT is not required to handle this. just use the below code and it works fine.
If we give element.click on the element, control stops there and hence we use element.sendkeys("") and robot.keyPress(KeyEvent.VK_ENTER);
Below is the complete code:
Robot robot = new Robot();
//get the focus on the element..don't use click since it stalls the driver
element.sendKeys("");
//simulate pressing enter
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
//wait for the modal dialog to open
Thread.sleep(2000);
//press s key to save
robot.keyPress(KeyEvent.VK_ALT);
robot.keyPress(KeyEvent.VK_N);
robot.keyRelease(KeyEvent.VK_N);
robot.keyRelease(KeyEvent.VK_ALT);
Thread.sleep(2000);
//press enter to save the file with default name and in default location
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_TAB);
Thread.sleep(2000);
robot.keyPress(KeyEvent.VK_DOWN);
robot.keyRelease(KeyEvent.VK_DOWN);
Thread.sleep(2000);
robot.keyPress(KeyEvent.VK_DOWN);
robot.keyRelease(KeyEvent.VK_DOWN);
Thread.sleep(2000);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
Thread.sleep(2000);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
I used AutoIt and it works in windows 10. Refer to the below AutoIt script :
Sleep(9000);
Local $hIE = WinGetHandle("[Class:IEFrame]");
Local $hCtrl = ControlGetHandle($hIE, "", "[ClassNN:DirectUIHWND1]");
If WinExists($hIE,"") Then
WinActivate($hIE,"");
ControlSend($hIE ,"",$hCtrl,"{F6}");
Sleep(1500);
ControlSend($hIE ,"",$hCtrl,"{TAB}");
Sleep(1500);
ControlSend($hIE ,"",$hCtrl,"{ENTER}");
EndIf
Sleep(5000);
If WinExists($hIE,"") Then
WinActivate($hIE,"");
ControlSend($hIE ,"",$hCtrl,"{F6}");
Sleep(1500);
ControlSend($hIE ,"",$hCtrl,"{TAB}");
Sleep(1500);
ControlSend($hIE ,"",$hCtrl,"{TAB}");
Sleep(1500);
ControlSend($hIE ,"",$hCtrl,"{TAB}");
Sleep(1500);
ControlSend($hIE ,"",$hCtrl,"{ENTER}");
EndIf
Sleep(5000);
It clicks the save button and also closes the next alert.
Please adjust Sleep() accordingly.
This is a hack by Dave Haefner. If you don't care if a file was downloaded or not and you want to confirm only that a file can be downloaded, you can use an HTTP request. Instead of downloading the file you'll receive the header information for the file which contains things like the content type and length. With this information, you can confirm the file is you expect.
String link = driver.findElement(By.cssSelector("download-link-element")).getAttribute("href");
HttpClient httpClient = HttpClientBuilder.create().build();
HttpHead request = new HttpHead(link);
HttpResponse response = httpClient.execute(request);
String contentType = response.getFirstHeader("Content-Type").getValue();
int contentLength = Integer.parseInt(response.getFirstHeader("Content-Length").getValue());
assertThat(contentType, is("application/octet-stream"));
assertThat(contentLength, is(not(0)));

Handle Login/Password Popup Selenium JAVA

we are trying to authenticate our website https://staging.rockettes.com.
It asks for a user name and password, which we have to supply via our selenium java code.
Can you help?
Thanks,
Rachit
You will need to construct a testURL before you call your driver.get command.
So assuming that the username=admin and pass=pass
String testURL = "https://" + "admin" + ":" + "pass" + "#" + "staging.rockettes.com/";
Now you can safely call your driver.get as following:
driver.get(testURL);
Best of luck!
Updated answer after op's comment:
Okay then, so in order to accept the alert you can use:
WebDriverWait waitTime = new WebDriverWait(driver, 5);
Boolean isAlertPresent = wait.until(ExpectedConditions.alertIsPresent());
if(isAlertPresent==true){
Alert alert = driver.switchTo().alert();
alertText = alert.getText();
alert.accept();
}
else{
System.out.println("No alert was present!")
}
I think that, the pop-up on hitting the ur URL is not web based alert rather it's a window alert, so you can handle it with the help of AutoIT or you can do this using Robot class as follows (though not recommended):
String userName = "ADMIN";
StringSelection stringSelection = new StringSelection(userName);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, stringSelection);
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_TAB);
String password = "PASS";
StringSelection stringSelection1 = new StringSelection(password);
Clipboard clipboard1 = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard1.setContents(stringSelection1, stringSelection1);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_TAB);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
if your handling popups, use the following command before passing username and password
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
You can used any ways below:
1. By pass with URL:
String url= "https://" + "username" + ":" + "password" + "#" + "staging.rockettes.com";
driver.get(url);
2. Alert
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
alert.authenticateUsing(new UserAndPassword("username", "password"));
3. AutoIT
Autoit script to handle the authentication window:
WinWaitActive("Windows Security")
Send("username")
Send("{TAB}")
Send("password")
Send("{ENTER}")
Save this file as “auth.au3"
Right click on the file and chose “Compile Script (x86)” option and it will make “auth.exe”
Now write the sample java code to use it:
driver.get("https://staging.rockettes.com/");
Runtime.getRuntime().exec("E:\\AutoIT\\auth.exe");
4. Sikuli
Screen screen = new Screen();
driver = new FirefoxDriver();
driver.get("https://staging.rockettes.com/");
screen.type("C:\\username.png"),"username");
screen.type("C:\\password.png","password");
screen.click("C:\\okButton.png");
Try this,
below solution is specific to chrome and the same approach can be applied for different browsers as well
public String getBaseUrl() {
StringBuilder stagingURl = new StringBuilder();
try {
URL url = new URL(baseUrl);
stagingURl
.append(url.getProtocol())
.append("://")
.append(URLEncoder.encode(stagingUsername, "utf-8"))
.append(":")
.append(URLEncoder.encode(stagingPassword, "utf-8"))
.append("#")
.append("staging.rockettes.com");
return stagingURl.toString();
} catch (UnsupportedEncodingException | MalformedURLException e) {
return "Issue while encoding URL" + e.getMessage();
}
The given solutions wouldn't work using the selenium get() method to load such a URL prompting for authentication with a JavaScript Popup, I was also stuck here for a long time. It's because of Chrome driver will not allow such authentication techniques after the update 59 (probably). There are still backdoors via Selenium using the JavaScript engine in the browser to load such URLs.
driver.get("https://www.google.com");
JavascriptExecutor jse = (JavascriptExecutor) driver;
URL = "https://username:password#www.example.com";
jse.executeScript("window.open('"+URL+"')");

Send caps text to a text box using Robot class & Selenium WebDriver

How to send capital text to a text box using Robot class and Selenium WebDriver.
You need to do two things to:
1- First to get focus to the textfield, where you want to enter the value, like this:
driver.findElement(By.xpath("//xpath of the element")).sendKeys("")// id or class can be used as locators too.
2- Then use 'Robot class' to send values to the field (using CAPSLOCK or SHIFT keys for changing the letters to uppercase).
Try this code. It works for sending "HELLO" (all caps) in Google.com's search field using "CAPSLOCK":
//Navigating to the site
driver.get("http://www.google.com");
//To get the focus on the searchbox (NOT ENTERING ANYTHING)
driver.findElement(By.id("gbqfq")).sendKeys("");
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CAPS_LOCK);
robot.keyRelease(KeyEvent.VK_CAPS_LOCK);
robot.keyPress(KeyEvent.VK_H);
robot.keyRelease(KeyEvent.VK_H);
robot.keyPress(KeyEvent.VK_E);
robot.keyRelease(KeyEvent.VK_E);
robot.keyPress(KeyEvent.VK_L);
robot.keyRelease(KeyEvent.VK_L);
robot.keyPress(KeyEvent.VK_L);
robot.keyRelease(KeyEvent.VK_L);
robot.keyPress(KeyEvent.VK_O);
robot.keyRelease(KeyEvent.VK_O);
robot.keyPress(KeyEvent.VK_CAPS_LOCK);
robot.keyRelease(KeyEvent.VK_CAPS_LOCK);
OR you can try using "SHIFT" as below:
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_H);
robot.keyRelease(KeyEvent.VK_H);
robot.keyPress(KeyEvent.VK_E);
robot.keyRelease(KeyEvent.VK_E);
robot.keyPress(KeyEvent.VK_L);
robot.keyRelease(KeyEvent.VK_L);
robot.keyPress(KeyEvent.VK_L);
robot.keyRelease(KeyEvent.VK_L);
robot.keyPress(KeyEvent.VK_O);
robot.keyRelease(KeyEvent.VK_O);
robot.keyRelease(KeyEvent.VK_SHIFT);
You can send caps text to a text box using Robot class in following manner.
Below i am sending String OK using Robot class
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CAPS_LOCK);
robot.keyPress(KeyEvent.VK_O);
robot.keyRelease(KeyEvent.VK_O);
robot.keyRelease(KeyEvent.VK_CAPS_LOCK);
robot.keyPress(KeyEvent.VK_CAPS_LOCK);
robot.keyPress(KeyEvent.VK_K);
robot.keyRelease(KeyEvent.VK_K);
robot.keyRelease(KeyEvent.VK_CAPS_LOCK);
It can be done by using "Caps Lock" or "Shift" key, that code has been mentioned here in another answer by Subh.
You can also do it by using StringSelection in Java. The code is as below:
//First of all declare the method setClipboardData as below:
public void setClipboardData(String string) {
StringSelection stringSelection = new StringSelection(string);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
}
//Call the method setClipboardData and write other Robot code:
driver.get("https://www.google.com/");
driver.findElement(By.id("lst-ib")).clear();
driver.findElement(By.id("lst-ib")).sendKeys("");
Robot robot = new Robot();
setClipboardData("ALL CAPS");
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);

Categories

Resources