BrowserMob Proxy is not opening 2nd page in chrome (Internet connection goes off after landing to 2nd page) - selenium-webdriver

I'm running Windows 10 virtual machine on ubuntu, and on VM I have following versions :-
Eclipse neon, Selenium Webdriver 3.0.1, Mozilla Firefox 51.0.1, Google Chrome 55, geckoDriver v0.11.1, Chromedriver v2.27, BrowserMob Proxy jar 2.1.4, jackson-all-1.7.3.jar, harlib-1.1.2.jar
I wanted to read browser traffics in selenium and for that i opted for BrowserMob proxy. I have 2 page of communication on the browser like Authenticates url, Lands on the 1st page clicks a dropdown menu (link) and lands on the 2nd page
When the second page opens the page does not load but the calls are going behind. What i noticed is in the VM when the second page loads internet connectivity goes off at that page only (internet sign stops blinking).
When i Reboot both the VM & the host machine and then execute the code. It loads the page at first attempt after fresh reboot of the system then again, if i execute the same code same problem persists.
But the traffic data is getting logged in the file. The same code if i try to execute in geckodriver(Firefox) then the page is getting loaded but traffic is not getting captured.capturing only specific urls from the log data
I have stuck in both the ways. Please find below the code :-
class 1 :-
public class BrowserMobExample{
public static String sFileName = System.getProperty("user.dir") + "\\CaptureNetworkTraffic\\BrowserMob.har";
WebDriver driver = null;
BrowserMobProxy proxy = null;
#BeforeTest
public void setUp() throws Exception {
// start the proxy
proxy = new BrowserMobProxyServer();
proxy.start(0);
//get the Selenium proxy object - org.openqa.selenium.Proxy;
Proxy seleniumProxy = ClientUtil.createSeleniumProxy(proxy);
// configure it as a desired capability
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.PROXY, seleniumProxy);
//set chromedriver system property
System.setProperty("webdriver.chrome.driver", "path to chromedriver");
driver = new ChromeDriver(capabilities);
/*System.setProperty("webdriver.gecko.driver", "path to geckodriver");
driver = new FirefoxDriver(capabilities);*/
// enable more detailed HAR capture, if desired (see CaptureType for the complete list)
proxy.enableHarCaptureTypes(CaptureType.REQUEST_HEADERS, CaptureType.RESPONSE_HEADERS);
proxy.newHar("label_for_har");
driver.manage().window().maximize();
driver.get("http://username:pswd#url.com");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Robot rb = new Robot();
rb.keyPress(KeyEvent.VK_ENTER);
//do something on page
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
WebElement citySelect = driver.findElement(By.xpath("dropdown_xpath"));
Select dropdown= new Select(select_a_dropdown_menuitem);
dropdown.selectByVisibleText("Text_displayed");
//driver.navigate().refresh();
}
#Test
public void testCaseOne() throws AWTException {
/*driver.manage().window().maximize();
driver.get("http://username:pswd#url.com");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Robot rb = new Robot();
rb.keyPress(KeyEvent.VK_ENTER);
//do something on page
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
WebElement citySelect = driver.findElement(By.xpath("dropdown_xpath"));
Select dropdown= new Select(select_a_dropdown_menuitem);
dropdown.selectByVisibleText("Text_displayed");
//driver.navigate().refresh();*/
}
#AfterTest
public void tearDown() {
// get the HAR data
Har har = proxy.getHar();
// Write HAR Data in a File
File harFile = new File(sFileName);
try {
har.writeTo(harFile);
ReadHAR reading = new ReadHAR();
reading.main(null);
} catch (IOException ex) {
System.out.println (ex.toString());
System.out.println("Could not find file " + sFileName);
}
/*if (driver != null) {
proxy.stop();
//driver.quit();
}*/
}
}
class 2 :-
public class ReadHAR {
public static void main(String[] args) {
String filename = new String();
filename = BrowserMobExample.sFileName;
// System.out.println("This is the file location " + filename);
File f = new File(filename);
HarFileReader r = new HarFileReader();
HarFileWriter w = new HarFileWriter();
try
{
System.out.println("Reading " + filename);
HarLog log = r.readHarFile(f);
// Access all elements as objects
HarBrowser browser = log.getBrowser();
HarEntries entries = log.getEntries();
// Used for loops
List<HarPage> pages = log.getPages().getPages();
List<HarEntry> hentry = entries.getEntries();
String string1 = "p_still_media";
String string2 = "m_still_media";
String string3 = "T-Map";
/* for (HarPage page : pages)
{
System.out.println("page start time: "
+ ISO8601DateFormatter.format(page.getStartedDateTime()));
System.out.println("page id: " + page.getId());
System.out.println("page title: " + page.getTitle());
}*/
File varTmpDir = new File(System.getProperty("user.dir") + "\\CaptureNetworkTraffic\\results.txt");
boolean exists = varTmpDir.exists();
System.out.println(" result.txt : " +exists);
System.out.println(" file path:"+ varTmpDir);
if(exists){
varTmpDir.delete();
}
File result = new File(System.getProperty("user.dir") + "\\CaptureNetworkTraffic\\results.txt");
// result.createNewFile();
result.setWritable(true);
//FileWriter fw = new FileWriter(result, false);
// PrintWriter out = new PrintWriter(fw);
//Output "response" code of entries.
for (HarEntry entry : hentry)
{
// System.out.println("IP is : " + entry.getServerIPAddress());
if(entry.getRequest().getUrl().contains(string2)/* & entry.getResponse().getStatus() !=200*/){
System.out.println(" Url is : " + entry.getRequest().getUrl() + " response code: " + entry.getResponse().getStatus()); //Output url of request
// Files.newBufferedWriter(result, StandardOpenOption.APPEND);
// out.write(" Url is : " + entry.getRequest().getUrl() + " response code: " + entry.getResponse().getStatus());
// BufferedWriter bw = new BufferedWriter(fw);
System.out.println("IP is :- "+entry.getServerIPAddress());
FileWriter fw = new FileWriter(result, true);
BufferedWriter out = new BufferedWriter(fw);
out.write(" Url is : " + entry.getRequest().getUrl() + " response code: " + entry.getResponse().getStatus());
out.newLine();
out.close();
fw.close();
}
else if(entry.getRequest().getUrl().contains(string3) /*& entry.getResponse().getStatus() !=200*/){
// System.out.println("request code: " + entry.getRequest().getMethod()); //Output request type
System.out.println(" Url is: " + entry.getRequest().getUrl() + " response code: " + entry.getResponse().getStatus()); //Output url of request
// out.write(" Url is : " + entry.getRequest().getUrl() + " response code: " + entry.getResponse().getStatus());
FileWriter fw = new FileWriter(result, true);
BufferedWriter out = new BufferedWriter(fw);
out.write(" Url is : " + entry.getRequest().getUrl() + " response code: " + entry.getResponse().getStatus());
out.newLine();
out.close();
fw.close();
}
else if(entry.getRequest().getUrl().contains(string1) /*& entry.getResponse().getStatus() !=200*/){
// System.out.println("request code: " + entry.getRequest().getMethod()); //Output request type
System.out.println(" Url is: " + entry.getRequest().getUrl() + " response code: " + entry.getResponse().getStatus()); //Output url of request
//out.write(" Url is : " + entry.getRequest().getUrl() + " response code: " + entry.getResponse().getStatus());
// out.close();
//System.out.println(" response code: " + entry.getResponse().getStatus()); // Output the
FileWriter fw = new FileWriter(result, true);
BufferedWriter out = new BufferedWriter(fw);
out.write(" Url is : " + entry.getRequest().getUrl() + " response code: " + entry.getResponse().getStatus());
out.newLine();
out.close();
fw.close();
}
}
/*
// Once you are done manipulating the objects, write back to a file
System.out.println("Writing " + "fileName" + ".test");
File f2 = new File("fileName" + ".test");
w.writeHarFile(log, f2);
*/
}
catch (JsonParseException e)
{
e.printStackTrace();
//fail("Parsing error during test");
}
catch (IOException e)
{
e.printStackTrace();
//fail("IO exception during test");
}
}
}
With ChromeDriver logs are getting generated but the page is not loading. With firefox page is loading but logs are not captured (I think for geckodriver browsermob proxy is not compatible or this feature isn't available yet)
Am i missing anything or what is the issue ? Stuck on this since more than a week. Tried the above on ubuntu to but facing the same issue.
Any help on this issue is much appreciated.

Related

How do i filter using a partial VM name (string) in vmware vSphere client REST API?

Good day!
i am trying to automate some actions to be done to VM's in my organisation.
The action to be done depends on the a substring in the VM name.
for eg, i would need to delete all VM's whose name starts with 'delete', etc.
I can use the below API to fetch the list of VM's:
GET https://{{vc}}/rest/vcenter/vm
However, this API can only fetch a maximum of 1000 VM's.
Is there any way i can filter and get only the list of VM's with the expected substring from this API?
from what i understand, appending filter.names.1 to the above API works but for that i need to input the exact and entire VM name.
is there a way where i can search for a list of VM's with partial text?
Apologies, i am a newbie to this.
thank you for your time!
Since vSphere API does not provide such capability to search by partial VM name there is a tricky way to do this.
I am using the search functionality in vSphere Client 6.7.0.
Prerequisite is to get the following cookies first:
VSPHERE-USERNAME
VSPHERE-CLIENT-SESSION-INDEX
VSPHERE-UI-JSESSIONID
You have to do three calls in order to get them:
1. GET "https://[URL]/ui/login" you will be forwarded to a new URL from where you can take "SAMLRequest token"
2. POST "https://[URL]/websso/SAML2/SSO/vsphere.local?SAMLRequest=[SAMLRequest token]", set as header "CastleAuthorization=Basic%20[credentials]" where credentials is the Base64 encoding of "User:Password". Get the value of "SAMLResponse" hidden field from the response.
3. POST "https://[URL]/ui/saml/websso/sso", set "SAMLResponse=[SAMLResponse value]", where "SAMLResponse value" you have it from the previous response. From this response you will get the cookies.
Once you have those three cookies, make a new call as you set the cookies
4. GET "https://[URL]/ui/search/quicksearch/?opId=0&query=[partial VM name]"
For example for this call "https://[URL]/ui/search/quicksearch/?opId=0&query=test"
you will get response like this:
[{
"icon": "vsphere-icon-vm",
"labelPlural": "Virtual Machines",
"label": "Virtual Machine",
"results": [{
"id": "urn:vmomi:VirtualMachine:vm-2153:103ac083-e314-47ea-942a-c685d9a4e6c9",
"type": "VirtualMachine",
"name": "TestVM1"
}, {
"id": "urn:vmomi:VirtualMachine:vm-3391:103ac083-e314-47ea-942a-c685d9a4e6c9",
"type": "VirtualMachine",
"name": "TestVM2"
}, {
"id": "urn:vmomi:VirtualMachine:vm-3438:103ac083-e314-47ea-942a-c685d9a4e6c9",
"type": "VirtualMachine",
"name": "TestVM3"
}
]
}
]
Below is my own vSphere Search Proxy Client written in C#:
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
namespace VsphereSearchProxy
{
static class Program
{
const string VSPHERE_URL = "VSPHERE_URL";
static string VSPHERE_CRED_BASE64
{
get
{
var plainTextCred = Encoding.UTF8.GetBytes("USER:PASS");
return Convert.ToBase64String(plainTextCred);
}
}
static void Main(string[] args)
{
if (args.Length == 0)
{
Console.WriteLine("Expected one argument: Virtual Machine name");
return;
}
var vmName = args[0];
var vsphereUri = VSPHERE_URL.TrimEnd('/');
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
ServicePointManager.Expect100Continue = true;
//=================================================================
Console.WriteLine("\nStep 1\n");
var url1 = vsphereUri + "/ui/login";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url1);
request.Method = "GET";
request.KeepAlive = true;
request.AllowAutoRedirect = true;
var response = (HttpWebResponse)request.GetResponse();
var url2 = response.ResponseUri.AbsoluteUri;
Console.WriteLine("url2: " + url2);
WebHeaderCollection headerCollection = response.Headers;
Console.WriteLine("\nResponse headers\n");
for (int i = 0; i < headerCollection.Count; i++)
{
Console.WriteLine("\t" + headerCollection.GetKey(i) + " = " + headerCollection.Get(i));
}
//=================================================================
Console.WriteLine("\nStep 2\n");
request = (HttpWebRequest)WebRequest.Create(url2);
request.Method = "POST";
request.Headers.Add("Authorization: Basic " + VSPHERE_CRED_BASE64);
request.ContentType = "application/x-www-form-urlencoded";
request.KeepAlive = true;
request.AllowAutoRedirect = false;
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write("CastleAuthorization=Basic%20" + VSPHERE_CRED_BASE64);
streamWriter.Flush();
streamWriter.Close();
}
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode != HttpStatusCode.OK)
{
throw new Exception("Expected 200 OK, but got " + response.StatusCode);
}
headerCollection = response.Headers;
Console.WriteLine("\nResponse headers\n");
for (int i = 0; i < headerCollection.Count; i++)
{
Console.WriteLine("\t" + headerCollection.GetKey(i) + " = " + headerCollection.Get(i));
}
var responseString = "";
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
responseString = reader.ReadToEnd();
}
var SAMLResponse = "";
Match match = Regex.Match(responseString, "<input[^>]*type=\"hidden\"\\s+name=\"SAMLResponse\"[^>]*value=\"([^\"]*)\"");
if (match.Success)
{
SAMLResponse = match.Groups[1].Value;
SAMLResponse = SAMLResponse.Replace("\n", "");
//Console.WriteLine("SAMLResponse: " + SAMLResponse);
}
if (string.IsNullOrWhiteSpace(SAMLResponse))
{
throw new Exception("SAMLResponse is missing or blank");
}
//=================================================================
Console.WriteLine("\nStep 3\n");
var url3 = vsphereUri + "/ui/saml/websso/sso";
request = (HttpWebRequest)WebRequest.Create(url3);
request.Method = "POST";
request.Headers.Add("Authorization: Basic " + VSPHERE_CRED_BASE64);
request.ContentType = "application/x-www-form-urlencoded";
request.KeepAlive = true;
request.AllowAutoRedirect = false;
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write("SAMLResponse=" + HttpUtility.UrlEncode(SAMLResponse));
streamWriter.Flush();
streamWriter.Close();
}
response = (HttpWebResponse)request.GetResponse();
var cookies = response.Headers["Set-Cookie"];
Console.WriteLine("cookies: " + cookies);
headerCollection = response.Headers;
Console.WriteLine("\nResponse headers\n");
for (int i = 0; i < headerCollection.Count; i++)
{
Console.WriteLine("\t" + headerCollection.GetKey(i) + " = " + headerCollection.Get(i));
}
//=================================================================
Console.WriteLine("\nStep 4\n");
var url4 = vsphereUri + "/ui/search/quicksearch/?opId=:1&query=" + vmName;
request = (HttpWebRequest)WebRequest.Create(url4);
request.Method = "GET";
request.Headers.Add("Cookie: " + cookies);
request.KeepAlive = true;
request.AllowAutoRedirect = false;
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode != HttpStatusCode.OK)
{
throw new Exception("Expected 200 OK, but got " + response.StatusCode);
}
var jsonResp = "";
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
jsonResp = reader.ReadToEnd();
}
Console.WriteLine(jsonResp);
}
}
}
Unfortunately the vSphere Automation API isn't setup to filter on partial names or even when using a wildcard. Some of the available filters may help you limit the output to be under the 1000 object limit (example: filter on specific clusters and/or folders).
Hopefully this is something that's added in a future release.

Codename One Capture API correct usage

I tried to use the following code with the purpose to record some videos with real devices (Android and iPhone) and to see the resulting file sizes. But it doesn't work... it seems to record, but it doesn't play the resulting videos neither on Android nor iOS.
I wrote the following code merging some examples in the Codename One API. What's wrong?
Form hi = new Form("Capture", BorderLayout.center());
Container cnt = new Container(BoxLayout.y());
hi.setToolbar(new Toolbar());
Style s = UIManager.getInstance().getComponentStyle("Title");
FontImage icon = FontImage.createMaterial(FontImage.MATERIAL_VIDEOCAM, s);
FileSystemStorage fs = FileSystemStorage.getInstance();
String recordingsDir = fs.getAppHomePath() + "recordings/";
fs.mkdir(recordingsDir);
try {
for (String file : fs.listFiles(recordingsDir)) {
Button mb = new Button(file.substring(file.lastIndexOf("/") + 1) + " - " + (int) (fs.getLength(recordingsDir + file) / 1024.0 / 1024.0 * 100) / 100.0 + " MB");
mb.addActionListener((e) -> {
try {
Media video = MediaManager.createMedia(recordingsDir + file, true);
hi.removeAll();
hi.add(BorderLayout.CENTER, new MediaPlayer(video));
hi.revalidate();
} catch (IOException err) {
Log.e(err);
}
});
cnt.add(mb);
}
hi.add(BorderLayout.CENTER, cnt);
hi.getToolbar().addCommandToRightBar("", icon, (ev) -> {
try {
String file = Capture.captureVideo();
if (file != null) {
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MMM-dd-kk-mm");
String fileName = sd.format(new Date());
String filePath = recordingsDir + fileName;
Util.copy(fs.openInputStream(file), fs.openOutputStream(filePath));
Button mb = new Button(file.substring(file.lastIndexOf("/") + 1) + " - " + (int) (fs.getLength(filePath) / 1024.0 / 1024.0 * 100) / 100.0 + " MB");
mb.addActionListener((e) -> {
try {
Media video = MediaManager.createMedia(filePath, true);
hi.removeAll();
hi.add(BorderLayout.CENTER, new MediaPlayer(video));
hi.revalidate();
} catch (IOException err) {
Log.e(err);
}
});
cnt.add(mb);
cnt.getParent().revalidate();
}
} catch (IOException err) {
Log.e(err);
}
});
} catch (IOException err) {
Log.e(err);
}
hi.show();
This is what I see on iPhone X after tapping a Button to open a recorded video (that is very similar to what I see on Android 7):
I spent so much time looking at this it's embarrassing...
Change this:
Form hi = new Form("Capture", BorderLayout.center());
To this:
Form hi = new Form("Capture", new BorderLayout());
The former gives the component its preferred size. The latter scales it to take up available space. The preferred size is zero on most platforms since the video needs to load for preferred size to apply. When it loads one would need to reflow the layout.

Displaying Blank page in which PDF link is included

Android OS version 7.1.1, following code display blank screen first time after download the App. Have to kill the App and open it again to work normally. Please advise.
Code:
Container cc = new Container(BoxLayout.y());
cc.setScrollableY(true);
TextArea ta = new TextArea(Util.readToString(is));
ta.setEditable(false);
ta.setUIID("Label");
Button b = new Button("Terms of Service");
b.addActionListener(e3 -> {
try {
FileSystemStorage fs = FileSystemStorage.getInstance();
final String homePath = fs.getAppHomePath();
String fileName = homePath + "Terms of Service.pdf";
Util.copy(Display.getInstance().getResourceAsStream(getClass(), "/Terms of Service.pdf"), fs.openOutputStream(fileName));
Display.getInstance().execute(fileName);
} catch (IOException ex) {
}
});
cc.add(ta);
CheckBox rememberMe1 = new CheckBox();
rememberMe1.setSelected(false);
rememberMe1.setHeight(Display.getInstance().convertToPixels(10.0f));
rememberMe1.setAutoSizeMode(true);
b.setAutoSizeMode(true);
setSameHeight(rememberMe1, l11, b);
cc.add(FlowLayout.encloseIn(rememberMe1, b));

Get the Ip Info from Client to Web Api

fist at all sorry for my bad English.
I'm trying to get the IP in the login option to save them as a "Session" in the database and register who and where is using the app.
I try this, but it obvious that it isn't going to work.
var ip = new System.Net.WebClient().DownloadString("http://ipinfo.io/json");
It Gets the IP Client. So it logical that I need to do this get in the Client side. But the problem is that the Client can change this values before its send to the Web API
$http.get("http://ipinfo.io/json").then(function (response) {
return response.data;
}).catch(function (response) {
console.log(response.data);
});
The users can change this value to send me a false data in the login and I don't have how to validate if this information is valid or real. So, the question is ¿How can I do this without let the user manipulate this data?
Create a method in web API, and we can save all the information needed directly to database.
public static string UserIp()
{
string ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ip))
{
ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
try
{
string url1 = "http://geoip.nekudo.com/api/" + ip.ToString(); // passing IP address will return location information.
WebClient client = new WebClient(); // Intialize the webclient
string jsonstring = client.DownloadString(url1);
dynamic dynObj = JsonConvert.DeserializeObject(jsonstring); // De-serialize the JSON string
string filePath = AppDomain.CurrentDomain.BaseDirectory + "\\App_Data\\Logs\\" + "Ip.txt";
using (System.IO.StreamWriter writer = new StreamWriter(filePath, true))
{
// you can save the information to database instead of writing to a file
writer.WriteLine("UserIp:" + ip);
writer.WriteLine("Date:" + DateTime.Now);
writer.WriteLine("JsonString:" + jsonstring);
writer.WriteLine("Country name:" + dynObj.country.code);
}
return dynObj;
}
catch (Exception ex)
{
string filePath = AppDomain.CurrentDomain.BaseDirectory + "\\App_Data\\Logs\\" + "I.txt";
string url1 = "http://geoip.nekudo.com/api/" + ip.ToString();
WebClient client = new WebClient(); // Intialize the webclient
string jsonstring = client.DownloadString(url1);
dynamic dynObj = JsonConvert.DeserializeObject(jsonstring);
// string a = dynObj.country.code;
using (System.IO.StreamWriter writer = new StreamWriter(filePath, true))
{
writer.WriteLine("Message :" + ex.Message + "<br/>" + Environment.NewLine + "StackTrace :" +
ex.StackTrace +
"" + Environment.NewLine + "Date :" + DateTime.Now.ToString());
writer.WriteLine("UserIp:" + ip);
writer.WriteLine("Dynamic obj:" + dynObj);
}
return null;
}
}

How to switch to Iframe in selenium

I am finding difficult to enter the user name and password present on the iframe which gets popped up when we click on the signin link.
Can somebody help me on this.
Site link given below
link : http://cashkaro.iamsavings.co.uk/
With Regards,
There is a predefined method exists in Selenium which you can use to switch to a Frame or an IFrame.
WebDriver driver = new FirefoxDriver();
There are 3 overloaded methods which you can use to switch to a frame.
1. driver.switchTo().frame(String frameId);
2. driver.switchTo().frame(int frameNumber);
3. driver.switchTo().frame(WebElement frame);
You can either of the above 3 methods to switch on a frame.
Hope it helps!
For the switch to an iframe, you can use:
public void switchToFrame(WebElement element) {
getDriver().switchTo().frame(element);
}
or
wati.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By locator)
wati.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(WebElement element)
To work with iframe you must switch from your current page to iframe.
Try the below code and let me know your result.
WebDriver driver = new FirefoxDriver();
driver.get("http://cashkaro.iamsavings.co.uk/");
String linkText = "SIGN IN";
WebElement eventElement = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.linkText(linkText)));
eventElement.click();
WebElement frame = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.xpath("html/body/div[14]/div[1]/div[2]/div[2]/div[1]/iframe")));
driver.switchTo().frame(frame);
driver.findElement(By.id("uname")).sendKeys("username#domain.com");
driver.findElement(By.id("uname")).sendKeys(Keys.TAB);
driver.findElement(By.id("pwd")).sendKeys("enteryourpassword");
driver.findElement(By.id("sign_in")).click();
Use your valid login credentials to sign in.
Please find the answer below
public void login_normally() {
navigate_to_url(prop.getProperty("url_prod_Locale"));
// Parent window
String parent_window = driver.getWindowHandle();
System.out.println("Parent windiow :" + parent_window);
driver.findElement(By.xpath(prop.getProperty("singin_link"))).click();
WebDriverWait wait = new WebDriverWait(driver, 7);
String iframe_xpath = prop.getProperty("iframe_com_xpath");
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By
.xpath(iframe_xpath)));
driver.findElement(By.xpath(prop.getProperty("email_id_InSignIn")))
.sendKeys(prop.getProperty("user_email_id_signIn"));
driver.findElement(By.cssSelector(prop.getProperty("password_InSign")))
.sendKeys(prop.getProperty("pwd_signIn"));
boolean check_box_flag = driver.findElement(
By.xpath(prop.getProperty("Keep_me_signed_in"))).isSelected();
System.out.println("check_box_flag" + check_box_flag);
if (check_box_flag == false) {
driver.findElement(By.xpath(prop.getProperty("Keep_me_signed_in")))
.click();
}
driver.findElement(By.xpath(prop.getProperty("sign_button_signIn")))
.click();
//=================================================================================
/* String login_mesg_error = driver.findElement(
By.cssSelector(prop.getProperty("loginerror"))).getText();
System.out.println(" login Error : " + login_mesg_error);
if (login_mesg_error.length()<0 ) {
System.out.println("Sucessfully Loggedin");
Assert.assertTrue(true, "Sucessfull Login");
APPLICATION_LOG.debug(login_mesg_error);
} else {
System.out.println("Login Failed");
Assert.assertTrue(false, login_mesg_error);
APPLICATION_LOG.debug(login_mesg_error);
}*/
//==============================================================================
String login_mesg_error=" ";
List<WebElement> li=driver.findElements(By.cssSelector(prop.getProperty("logout_button_css")));
System.out.println(" list size :" +li.size());
if(li.size()>0)
{
System.out.println("Sucessfully Loggedin");
Assert.assertTrue(true, "Sucessfull Login");
APPLICATION_LOG.debug("Sucessfull Login");
} else {
login_mesg_error = driver.findElement(
By.xpath(prop.getProperty("login_error_mesg"))).getText();
System.out.println(" login Error : " + login_mesg_error);
System.out.println("Login Failed");
Assert.assertTrue(false, "Login failed - Incorrect username or password");
APPLICATION_LOG.debug(login_mesg_error + "Login failed");
}
driver.switchTo().defaultContent();
}

Resources