Tuesday, August 18, 2020

Eclipse ---- An error has occurred. See the log file E:\Selenium\.metadata\.log.

Eclipse
---------------------------
An error has occurred. See the log file
E:\Selenium\.metadata\.log.
---------------------------
OK   

Solutions
1. Delete metadata folder in Eclipse folder and restart eclipse. It should work.

If the error message exists again follow the below steps

1. Uninstall the Java Installations
2. search java from Oracle website, download and install  jdk-14.0.2.
3. Remove existing eclipse and install Eclipse IDE for developers
4. Restart eclipse
It should work, else
open eclipse.ini and above vmargs statement enter the installation path C:\Program Files\Java\jdk-14.0.2
5. Open Environment variables through control panel and update the Java_Home, Path, SystemPath to C:\Program Files\Java\jdk-14.0.2
It should work

Error: Could not create the Java Virtual Machine.

 ---------------------------

Java Virtual Machine Launcher

---------------------------

Error: Could not create the Java Virtual Machine.

Error: A fatal exception has occurred. Program will exit.

---------------------------

OK   

--------------------------------------------------------------------------------------------------------------------

To resolve the above issue that occurs while opening eclipse, 

1. Open Eclipse.ini file from eclipse folder.

2. Above -vmargs statement enter -vm C:\Program Files\Java\jdk-14.0.2\bin

save and close. Open eclipse again the issue should be resolved.







Friday, May 27, 2016

TestNG DataProvider with Excel Apache POI


How to use DataProvider to read Excel Values in DataProvider Array.

Steps

1. Create Data Table.xlsx
2. Create Class File and Write TestNG functions to read Excel Data
3. Create TestNG XML file to Call it

Test Data Table

UserName Password
KMV20694 VH435363
KMV20697 VS635284
cm279156 Kvhe3004
M3774669 Kvhe3005

TestNG XML File
<suite name="XMLSuite" thread-count="1">
<test name="DPwithExcel">
<classes>
<parameter name="sFilePath" value="G://Sridhar//TestData.xlsx"></parameter>
<parameter name="sSheetName" value="Sheet1"></parameter>
<class name="PkgTestNGDataProvider.ExcelUtils"/>
</classes>
</test>
</suite>

ExcelUtils.Java

import java.io.FileOutputStream;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

public class ExcelUtils {
private static XSSFWorkbook ExcelWBook;
private static XSSFSheet ExcelWSheet;
private static XSSFRow ExcelWRow;
private static XSSFCell ExcelCell;
//Open Excel File
@Test(priority=0)
@Parameters({"sFilePath","sSheetName"})
public static void fOpenExcelFile(String sFilePath,String sSheetName) throws Exception{
FileInputStream sFile = new FileInputStream(sFilePath);
ExcelWBook = new XSSFWorkbook(sFile);
ExcelWSheet = ExcelWBook.getSheet(sSheetName);
System.out.println("In File Open");
}
@Test(dataProvider="XLTestData", priority=1)
public void testDP(String sUserName, String sPassword) {
System.out.println("User Name in Calling DP is : " + sUserName);
System.out.println("User Name in Calling DP is : " + sPassword);
}
@DataProvider(name="XLTestData")
public Object[][] getXlData() throws Exception{
try{
System.out.println("LastRow:"+ExcelWSheet.getLastRowNum());
int iRowCount = ExcelWSheet.getLastRowNum();
Object[][] ReturnXlData = new Object[iRowCount+1][2];
for (int iLoop=0;iLoop<=iRowCount;iLoop++)
{
ExcelWRow = ExcelWSheet.getRow(iLoop);
int iColCount = ExcelWRow.getLastCellNum();
System.out.println("iColCount is"+ iColCount);
for (int jLoop=0;jLoop<iColCount;jLoop++){
System.out.println("Value is"+ getCellData(iLoop,jLoop));
ReturnXlData[iLoop][jLoop]=getCellData(iLoop,jLoop);
}
}
return ReturnXlData;
}catch (Exception e){
throw (e);
}
}
//Read Cell Data
public static String getCellData (int iRowNum, int iColNum) throws Exception{
try{
ExcelCell = ExcelWSheet.getRow(iRowNum).getCell(iColNum);
int iCellType = ExcelCell.getCellType();
if(iCellType==3){
return "";
}else {
String CellData  = ExcelCell.getStringCellValue();
return CellData;
}
}catch (Exception e){
throw (e);
}
}

//set CellData
public static void setCellData(int iRowNum, int iColNum,String sValue,String sFilePath) throws Exception{
try {
ExcelWRow = ExcelWSheet.getRow(iRowNum);
ExcelCell = ExcelWSheet.getRow(iRowNum).getCell(iColNum,ExcelWRow.RETURN_NULL_AND_BLANK);
if(ExcelCell==null){
ExcelCell = ExcelWRow.createCell(iColNum);
ExcelCell.setCellValue(sValue); 
}
else{
ExcelCell.setCellValue(sValue); 
}
//Output file
FileOutputStream sFileOut = new FileOutputStream(sFilePath);
ExcelWBook.write(sFileOut);
sFileOut.flush();
sFileOut.close();
}catch (Exception e){
throw(e);
}
}
//Get TotalRowsCount
public static int getRowCount() throws Exception{
try{
int iRowCount = ExcelWSheet.getPhysicalNumberOfRows();
return iRowCount;
}catch (Exception e)
{
throw (e);
}
}
}

Tuesday, August 18, 2015

Hints 1

String comparison should be done as equals instead of ==

For example

 if(sActionKeyword=="click_MyAccount") should be

if(sActionKeyword.equals("click_MyAccount")


Friday, May 29, 2015

Sample Javascript code in Selenium Web driver

How to use Java script executor

import org.openqa.selenium.JavascriptExecutor;

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript(Script,Arguments);

//Alert
JavascriptExecutor js = (JavascriptExecutor)driver;
Js.executeScript("alert('hello world');");

//click a button
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].click();", element);

//refresh browser window
JavascriptExecutor js = (JavascriptExecutor)driver;
driver.executeScript("history.go(0)");

//get innertext of the entire webpage in Selenium
JavascriptExecutor js = (JavascriptExecutor)driver;
string sText =  js.executeScript("return document.documentElement.innerText;").toString();

//Title of our webpage
JavascriptExecutor js = (JavascriptExecutor)driver;
string sText =  js.executeScript("return document.title;").toString();

//Scroll on application using  Selenium
JavascriptExecutor js = (JavascriptExecutor)driver;
//Vertical scroll - down by 50  pixels
js.executeScript("window.scrollBy(0,50)");

//click on a SubMenu which is only visible on mouse hover on Menu
JavascriptExecutor js = (JavascriptExecutor)driver;
//Hover on Automation Menu on the MenuBar
js.executeScript("$('ul.menus.menu-secondary.sf-js-enabled.sub-menu li').hover()");


// navigate to different page using Javascript
JavascriptExecutor js = (JavascriptExecutor)driver;
//Navigate to new Page
js.executeScript("window.location = 'https://www.facebook.com/uftHelp'");



//hello World
WebDriver driver = new ChromeDriver();
if (driver instanceof JavascriptExecutor) {
 ((JavascriptExecutor) driver).executeScript("alert('hello world');");
}



Thursday, May 28, 2015

How to setup Logging for Selenium web driver script

1. Open http://logging.apache.org/

2. Open Apache log4j link

3. Download from left shoulder tab

4. Extract and add Log4j Jar to eclipse

5. Create log4j.xml in the root folder of the script

<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">

<appender name="fileAppender" class="org.apache.log4j.FileAppender">

<param name="Threshold" value="INFO" />

<param name="File" value="logfile.log"/>

<layout class="org.apache.log4j.PatternLayout">

<param name="ConversionPattern" value="%d %-5p [%c{1}] %m %n" />

</layout>

</appender>

<root>

<level value="INFO"/>

<appender-ref ref="fileAppender"/>

</root>

</log4j:configuration>

6. Use Log.info("New driver instantiated"); comments across your scripting

7. Import following packages into the script

import org.apache.commons.logging.Log;
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;

8. Update below code under class file
private static Logger Log = Logger.getLogger(MLPTweets.class.getName());

9. With main section set the log file config

DOMConfigurator.configure("log4j.xml");

10. Where ever log needed update the following command in Log.Info();

Log.info("Tweets Data file Opened");

11. After the execution, open the logfile.log from the base folder and verify

Tuesday, May 26, 2015

How to create new Maven project from eclipse

1. Eclipse-->File-->New -->Other-->Browse workspace-->Quick-start archetypes-->GroupId,ArtifactId(projectName)-->Update pom.xml with latest jnit version

2. Right click pom.xml and run as maven project

How to setup Maven for Selenium Webdriver

1. Open https://maven.apache.org/

2. Set the folder path D:\Selenium\Eclipse\Maven\apache-maven-3.0.5 at

3. Set the environment variable
  MAVEN_HOME
  D:\Selenium\Eclipse\Maven\apache-maven-3.0.5

4. Set System Environment Variable
JAVA_HOME
C:\Program Files\Java\jdk1.8.0_45

5. Edit Path Environment variable and add

6. Check Maven is installed in the computer or not
   a. open command prompt
   b. enter mvn --version
  it should dipslay the version of the maven installed


How to use read JSON objects/Values into selenium through Java

Step 1
1. Open Json file in JSON parser to identify the object array hierarchy
2. Associate java-json.jar file to the eclipse libraries
3. Paste the json content into the parser to figure out the hierarchy to access http://json.parser.online.fr/
4. The sample tweets are identified through text attribute
5. Go through the following code
Sample Code

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;



public class Test {
private static WebDriver driver = null;
public static void main(String[] args) throws IOException, InterruptedException{

driver = new FirefoxDriver();

driver.get("http://webapptoshowtweets/hilton");
Thread.sleep(10000);
Thread.sleep(5000);

try {

URL url = new URL("http://dallas/tweets.json");

URLConnection urlConnection = url.openConnection();

InputStream in = new BufferedInputStream(urlConnection.getInputStream());

BufferedReader r = new BufferedReader(new InputStreamReader(in));

StringBuilder total = new StringBuilder();

String line;

while ((line = r.readLine()) != null) {

total.append(line);

}

in.close();


JSONArray jsonArray = new JSONArray(total.toString());

String[] values=new String[jsonArray.length()];
//System.out.println("Total Tweets: " + jsonArray.length());
for (int index = 0; index < jsonArray.length(); index++) {

JSONObject jsonObject=jsonArray.getJSONObject(index);

String text=jsonObject.getString("text");

String strActTweetDesc = driver.findElement(By.id("tweetsDescription")).getText();

if(strActTweetDesc.equals(text)){
System.out.println("String Matches: Passed" + text);
}
else
{
System.out.println("Tweet Fails");
System.out.println("Expected String: " +text);
System.out.println("Actual Tweet String: " +strActTweetDesc);
}

//Click Next Button
//Selenium get Div Element
//WebElement btnTweetNext = driver.findElement(By.cssSelector("#tweets > #tweetsContainer > #tweetsDescription"));
WebElement btnTweetNext = driver.findElement(By.cssSelector("#tweets > a > div"));
//*[@id="tweets"]/a/div

btnTweetNext.click();
Thread.sleep(1000);

values[index]=text;
//System.out.println(text);


} // for to navigate Json data



} catch (JSONException e) {

e.printStackTrace();

}

}


}

Monday, May 18, 2015

Set Value to Select Area object

<td>
<input id="txtEditCampaignId-1513" value="" type="hidden">
<textarea id="txtCampaignName-1513" style="width:350px;height:100px"></textarea>
</td>

The following code identifies text area element and sets value to it.

WebElement CmpTxtArea = driver.findElement(By.xpath("//*[starts-with(@id,'txtCampaignName')]"));
CmpTxtArea.sendKeys("Text Area Success");


How to handle the element when Id changes dynamically at the End





driver.findElement(By.cssSelector("button[id^='btnCreateNewCampaign']")).click();



Similarly

driver.findElement(By.cssSelector(“button[id^=’finish’][id$=’_NS_’]”));

it uses the regular expression with CSS  Selector where id^ looks for the word starting with finish and ends with _NS_.

How to click checkbox/link from a WebTable where Table id is unknown in a web page


//Select Link Object
List<WebElement> MainTables = driver.findElements(By.tagName("table"));

int i_TblCount = 0;
String strProjectName = "TestAutomation6";
String strActualProjName;
for (WebElement TblPosition:MainTables)
{
String strText;
strText = TblPosition.getText().trim();

if(strText.startsWith("+ Restructure Opportunities"))
{

System.out.println(strText);
System.out.println(" | ");
List<WebElement> tblPosition1 = TblPosition.findElements(By.tagName("table"));
System.out.println("Tables within Restructure Opp" + tblPosition1.get(1).getText());

List<WebElement> trows = tblPosition1.get(1).findElements(By.tagName("tr"));
for( WebElement TblRow:trows)
{
System.out.println(TblRow.getText());
List<WebElement> tds = TblRow.findElements(By.tagName("td"));
if(tds.size()>2){
strActualProjName = tds.get(1).getText();
System.out.println(strActualProjName);
if(strProjectName.equals(strActualProjName))
  {
//tds.get(0).click();
  //String strtdtext = tds.get(0).findElement(By.tagName("input")).getAttribute("innerhtml");
  //CheckBox
  tds.get(0).findElement(By.tagName("input")).click();
  //tds.get(1).findElement(By.tagName("a")).click();
  String s = tds.get(1).findElement(By.tagName("a")).getText();
  tds.get(1).findElement(By.tagName("a")).click();
  //tds.get(1).findElement(By.linkText(strActualProjName)).click();
  System.out.println(s);
  Thread.sleep(4000);
  driver.findElement(By.linkText("Campaigns")).click();
  Thread.sleep(4000);
  break;
} //If Project Name found in the List

 }//if tds.size

} //For to find Project List Table

}// If table starts with Restructure Opportunities

}//All Table For Loop

Sunday, May 10, 2015

How to fix Eclipse starting Error that returns Java was started but returned exit code = 1

If eclipse couldn't be opened and returns the error message as Java was started but returned exit code = 1




1. Uninstall all the existing java applications
2. Install JDK 8 64 bit based on your windows os
 a. Search JDK 8 64 bit in chrome
 b. Open the first result on oracle site
 c. Under Java SE Development Kit 8u45 select windows *64 link and download it.
 d. Open and Install it
3. The path installed on program files installed should set path default to it. Click open eclipse now, it should open successfully.

If again the same issue exist, open eclipse.ini file and update the -vm C:\Program Files\Java\jdk1.8.0_45\bin\javaw.exe

Save and open eclipse, it should open successfully.


Friday, May 8, 2015

Selecting sub menu while mouse hover top menu

In the above image Tools menu needs to be selected first and then sub menu should be selected.  In selenium webdriver the following package needs to be imported to use class Actions.

Use this class rather than using the Keyboard or Mouse directly. Implements the builder pattern: Builds a CompositeAction containing all actions specified by the method calls.

Pls. refer  http://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/interactions/Actions.html for action class methods and constructors.

To implement Actions class, the following package needs to be imported

import org.openqa.selenium.interactions.Actions;

linkText method of findElement method directly gets the link which has innerText within it. The below code can select the sub menu item.


Actions action = new Actions(driver);

WebElement mnuTools = driver.findElement(By.linkText("Tools"));

action.moveToElement(mnuTools).build().perform();

driver.findElement(By.linkText("Ad Copy Manager Internal")).click();