Maven Dependencies: (KevonLotion)
Selenium :
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.0.1</version>
</dependency>
TestNG :
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.10</version>
<scope>test</scope>
</dependency>
Apache.poi :
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.15</version>
</dependency>
Launch4j :
<dependency>
<groupId>com.akathist.maven.plugins.launch4j</groupId>
<artifactId>launch4j-maven-plugin</artifactId>
<version>1.7.12</version>
</dependency>
Log4j :
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
Log4j Version 2:
<dependencies>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.7</version>
</dependency>
</dependencies>
package package1;
import java.awt.AWTException;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Demo {
public static void main(String[] args) throws AWTException, InterruptedException {
String url = "https://accounts.google.com/ServiceLogin#identifier";
System.setProperty("webdriver.chrome.driver","c:\\SRP\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get(url);
Logger logger = Logger.getLogger(Demo.class);
Logger.getRootLogger().setLevel(Level.INFO);
BasicConfigurator.configure();
logger.info("this is a debug log message 1");
public static void myWaitAndClick(WebElement elementToBeClicked) throws InterruptedException, IOException {
System.out.println("In ExplicitWait");
try
{
System.out.println("In Try");
WebDriverWait wait = new WebDriverWait(DataLibrary.driver, 20);
WebDriverWait wait1 = new WebDriverWait(DataLibrary.driver, 20);
/*
FluentWait wait = new FluentWait(driver)
.withTimeout(20, TimeUnit.SECONDS)
.pollingEvery(1000, TimeUnit.MILLISECONDS)
.ignoring(NoSuchElementException.class, TimeoutException.class)
.ignoring(StaleElementReferenceException.class);
FluentWait wait1 =wait;
*/
long startTime = System.currentTimeMillis();
wait.until(ExpectedConditions.visibilityOf(elementToBeClicked));
System.out.println("Visible");
wait1.until(ExpectedConditions.elementToBeClickable(elementToBeClicked));
System.out.println("Clickable");
long durationMs = System.currentTimeMillis() - startTime;
System.out.println("Time Waited for -->" + elementToBeClicked + ": " + durationMs/1000 + " Seconds");
elementToBeClicked.click();
}
catch(Exception e)
{
System.out.println("Wait Counter = " + DataLibrary.getWaitCounter() + "\n" +"Element not cklicked yet. waiting some more for " + elementToBeClicked + e);
if(DataLibrary.getWaitCounter()<3){
DataLibrary.setWaitCounter(DataLibrary.getWaitCounter() + 1);
WaitAndClick(elementToBeClicked);
}
DataLibrary.setWaitCounter(1);
//testRunDuration = (System.currentTimeMillis() - testStartTime)/1000;
System.out.println("Test run encountered an error.....!!!" + "\n" + "Test run duration : Secs.");
/*
driver.quit();
System.exit(1);
*/
}
TakeSnapshot();
}
public static void TakeSnapshot() throws IOException, InterruptedException{
if(MethodLibrary.ReadXL(7,3, "E2E Flow").equals("Yes")){
Thread.sleep(3000);
File scrFile = ((TakesScreenshot)DataLibrary.driver).getScreenshotAs(OutputType.FILE);
if(DataLibrary.getUserType().equals("User1")){
FileUtils.copyFile(scrFile, new File("C:\\" +"USER_ID - " + DataLibrary.getCustomerID() + "\User"+"\\Step " + DataLibrary.getScrNo() +" - User1" + ".png"));
}
else if(DataLibrary.getUserType().equals("User1")){
FileUtils.copyFile(scrFile, new File("C:\\" +"USER_ID - " + DataLibrary.getCustomerID() + "\\User"+"\\Step " + DataLibrary.getScrNo() + " - User2" +".png"));
}
MethodLibrary.Logger_Info("Screenshot Captured!!");
DataLibrary.setScrNo(DataLibrary.getScrNo()+1);
}
}
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.0.1</version>
</dependency>
TestNG :
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.10</version>
<scope>test</scope>
</dependency>
Apache.poi :
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.15</version>
</dependency>
Launch4j :
<dependency>
<groupId>com.akathist.maven.plugins.launch4j</groupId>
<artifactId>launch4j-maven-plugin</artifactId>
<version>1.7.12</version>
</dependency>
Log4j :
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
Log4j Version 2:
<dependencies>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.7</version>
</dependency>
</dependencies>
Running Cucumber JUnit from Command Line
mvn test -Dcucumber.options="./features/feature1.feature" -Dcucumber.options="--tags @test1"
IsElementPresnt() function
private boolean isElementPresent(WebElement element) {
try {
element;
} catch (NoSuchElementException e) {
return false;
}
return true;
}
Log4J example:
package package1;private boolean isElementPresent(WebElement element) {
try {
element;
} catch (NoSuchElementException e) {
return false;
}
return true;
}
import java.awt.AWTException;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Demo {
public static void main(String[] args) throws AWTException, InterruptedException {
String url = "https://accounts.google.com/ServiceLogin#identifier";
System.setProperty("webdriver.chrome.driver","c:\\SRP\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get(url);
Logger logger = Logger.getLogger(Demo.class);
Logger.getRootLogger().setLevel(Level.INFO);
BasicConfigurator.configure();
logger.info("this is a debug log message 1");
My Wait()
public static void myWaitAndClick(WebElement elementToBeClicked) throws InterruptedException, IOException {
System.out.println("In ExplicitWait");
try
{
System.out.println("In Try");
WebDriverWait wait = new WebDriverWait(DataLibrary.driver, 20);
WebDriverWait wait1 = new WebDriverWait(DataLibrary.driver, 20);
/*
FluentWait wait = new FluentWait(driver)
.withTimeout(20, TimeUnit.SECONDS)
.pollingEvery(1000, TimeUnit.MILLISECONDS)
.ignoring(NoSuchElementException.class, TimeoutException.class)
.ignoring(StaleElementReferenceException.class);
FluentWait wait1 =wait;
*/
long startTime = System.currentTimeMillis();
wait.until(ExpectedConditions.visibilityOf(elementToBeClicked));
System.out.println("Visible");
wait1.until(ExpectedConditions.elementToBeClickable(elementToBeClicked));
System.out.println("Clickable");
long durationMs = System.currentTimeMillis() - startTime;
System.out.println("Time Waited for -->" + elementToBeClicked + ": " + durationMs/1000 + " Seconds");
elementToBeClicked.click();
}
catch(Exception e)
{
System.out.println("Wait Counter = " + DataLibrary.getWaitCounter() + "\n" +"Element not cklicked yet. waiting some more for " + elementToBeClicked + e);
if(DataLibrary.getWaitCounter()<3){
DataLibrary.setWaitCounter(DataLibrary.getWaitCounter() + 1);
WaitAndClick(elementToBeClicked);
}
DataLibrary.setWaitCounter(1);
//testRunDuration = (System.currentTimeMillis() - testStartTime)/1000;
System.out.println("Test run encountered an error.....!!!" + "\n" + "Test run duration : Secs.");
/*
driver.quit();
System.exit(1);
*/
}
TakeSnapshot();
}
TakeSnapshot():
public static void TakeSnapshot() throws IOException, InterruptedException{
if(MethodLibrary.ReadXL(7,3, "E2E Flow").equals("Yes")){
Thread.sleep(3000);
File scrFile = ((TakesScreenshot)DataLibrary.driver).getScreenshotAs(OutputType.FILE);
if(DataLibrary.getUserType().equals("User1")){
FileUtils.copyFile(scrFile, new File("C:\\" +"USER_ID - " + DataLibrary.getCustomerID() + "\User"+"\\Step " + DataLibrary.getScrNo() +" - User1" + ".png"));
}
else if(DataLibrary.getUserType().equals("User1")){
FileUtils.copyFile(scrFile, new File("C:\\" +"USER_ID - " + DataLibrary.getCustomerID() + "\\User"+"\\Step " + DataLibrary.getScrNo() + " - User2" +".png"));
}
MethodLibrary.Logger_Info("Screenshot Captured!!");
DataLibrary.setScrNo(DataLibrary.getScrNo()+1);
}
}
Handling Frames:
package package1;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class HandleFrames {
public static void main(String[] args) throws InterruptedException {
String url = "https://netbanking.hdfcbank.com/netbanking/?_ga=1.249656256.715290868.1479125272";
System.setProperty("webdriver.chrome.driver","C:\\Users\\kushal\\Documents\\Selenium\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get(url);
Thread.sleep(20000);
String window1 = driver.getWindowHandle();
System.out.println("3rd window handle :" + window1);
driver.switchTo().frame("login_page");
driver.findElement(By.xpath("html/body/form/table[2]/tbody/tr/td[2]/table/tbody/tr[1]/td[1]/table/tbody/tr[3]/td[2]/table/tbody/tr[2]/td[2]/span/input")).sendKeys("9593436");
}
}
Handling MouseOver:
package package1;
import java.util.ArrayList;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
public class HandleNewTab {
public static void main(String[] args) throws InterruptedException {
String url = "http://www.hdfcbank.com/";
// String url2 = "http://buy.mi.com/in/buy/product/mi5";
System.setProperty("webdriver.chrome.driver","C:\\Users\\kushal\\Documents\\Selenium\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get(url);
Thread.sleep(20000);
String oldTab = driver.getWindowHandle();
System.out.println("OldTab : " + oldTab);
Actions action = new Actions(driver);
WebElement customerCare = driver.findElement(By.xpath("html/body/div[1]/div[1]/div[2]/div[2]/ul/li[8]/div[1]/a"));
WebElement secondElementInDropDown = driver.findElement(By.xpath("html/body/div[1]/div[1]/div[2]/div[2]/ul/li[8]/div[2]/div[2]/div/ul/li[2]/a"));
while(!driver.findElement(By.xpath("html/body/div[1]/div[1]/div[2]/div[2]/ul/li[8]/div[2]/div[2]/div/ul/li[1]/a")).isDisplayed())
{
action.moveToElement(customerCare).build().perform();
//action.moveToElement(customerCare).moveToElement(secondElementInDropDown).click().build().perform();
Thread.sleep(1000);
}
action.moveToElement(customerCare).moveToElement(secondElementInDropDown).click().build().perform();
ArrayList<String> allTabHandles = new ArrayList<String> (driver.getWindowHandles());
System.out.println("allTabHandles : " + allTabHandles);
allTabHandles.remove(oldTab);
String newTab = allTabHandles.get(0);
System.out.println("newTab : " + newTab);
driver.switchTo().window(newTab);
System.out.println("Control in new tab!");
newTab =driver.getWindowHandle();
System.out.println("newTab (after switch to new): " + newTab);
Thread.sleep(1000);
String value= driver.findElement(By.xpath(".//*[@id='accordian2']/h3")).getText();
System.out.println("Value in New TAB: " + value);
driver.switchTo().window(oldTab);
System.out.println("Control in old tab!");
Thread.sleep(1000);
oldTab=driver.getWindowHandle();
System.out.println("oldTab (after switch to old): " + oldTab);
value=driver.findElement(By.xpath(".//*[@id='hometab1']/div[1]/div[2]/h2")).getText();
System.out.println("Value in Old TAB: " + value);
System.out.println("Success!!!");
}
}
Handling New Tab:
package package1;
import java.util.ArrayList;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
public class HandleNewTab {
public static void main(String[] args) throws InterruptedException {
String url = "http://www.hdfcbank.com/";
// String url2 = "http://buy.mi.com/in/buy/product/mi5";
System.setProperty("webdriver.chrome.driver","C:\\Users\\kushal\\Documents\\Selenium\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get(url);
Thread.sleep(20000);
String oldTab = driver.getWindowHandle();
System.out.println("OldTab : " + oldTab);
Actions action = new Actions(driver);
WebElement customerCare = driver.findElement(By.xpath("html/body/div[1]/div[1]/div[2]/div[2]/ul/li[8]/div[1]/a"));
WebElement secondElementInDropDown = driver.findElement(By.xpath("html/body/div[1]/div[1]/div[2]/div[2]/ul/li[8]/div[2]/div[2]/div/ul/li[2]/a"));
while(!driver.findElement(By.xpath("html/body/div[1]/div[1]/div[2]/div[2]/ul/li[8]/div[2]/div[2]/div/ul/li[1]/a")).isDisplayed())
{
action.moveToElement(customerCare).build().perform();
//action.moveToElement(customerCare).moveToElement(secondElementInDropDown).click().build().perform();
Thread.sleep(1000);
}
action.moveToElement(customerCare).moveToElement(secondElementInDropDown).click().build().perform();
ArrayList<String> allTabHandles = new ArrayList<String> (driver.getWindowHandles());
System.out.println("allTabHandles : " + allTabHandles);
allTabHandles.remove(oldTab);
String newTab = allTabHandles.get(0);
System.out.println("newTab : " + newTab);
driver.switchTo().window(newTab);
System.out.println("Control in new tab!");
newTab =driver.getWindowHandle();
System.out.println("newTab (after switch to new): " + newTab);
Thread.sleep(1000);
String value= driver.findElement(By.xpath(".//*[@id='accordian2']/h3")).getText();
System.out.println("Value in New TAB: " + value);
driver.switchTo().window(oldTab);
System.out.println("Control in old tab!");
Thread.sleep(1000);
oldTab=driver.getWindowHandle();
System.out.println("oldTab (after switch to old): " + oldTab);
value=driver.findElement(By.xpath(".//*[@id='hometab1']/div[1]/div[2]/h2")).getText();
System.out.println("Value in Old TAB: " + value);
System.out.println("Success!!!");
}
}
Handling NEW Window:
package package1;
import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class HandleNewWindow {
public static void main(String[] args) throws InterruptedException {
String url = "http://www.hdfcbank.com/";
// String url2 = "http://buy.mi.com/in/buy/product/mi5";
System.setProperty("webdriver.chrome.driver","C:\\Users\\kushal\\Documents\\Selenium\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get(url);
Thread.sleep(40000);
String window1 = driver.getWindowHandle();
System.out.println("Window 1 handle : " + window1);
driver.findElement(By.id("loginsubmit")).click();
Thread.sleep(20000);
Set<String> handles = driver.getWindowHandles();
System.out.println("Handles : " + handles);
Iterator<String> itr = handles.iterator();
while(itr.hasNext()){
String newHandle = itr.next();
if(!newHandle.equals(window1)) {
System.out.println("NewHandle Value:" + newHandle);
Thread.sleep(10000);
driver.switchTo().window(newHandle);
System.out.println("Window 2 Handle :" + driver.getWindowHandle());
driver.findElement(By.xpath(".//*[@id='wrapper']/div[6]/a/img")).click();
}
}
}
}
Handling Web Alerts:
package package1;
import java.util.ArrayList;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class HandleWebAlerts {
public static void main(String[] args) throws InterruptedException {
String url = "file://client.barclayscorp.com/Homeshare/Home0075/G09637255/My%20Documents/My%20Music/Selenium/Handle%20Alerts%20WebPage/WebPopUPprompt.htm";
System.setProperty("webdriver.chrome.driver","C:\\Users\\kushal\\Documents\\Selenium\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get(url);
Thread.sleep(20000);
String oldTab = driver.getWindowHandle();
System.out.println("oldTab : " + oldTab);
driver.findElement(By.xpath("/html/body/button")).click();
Thread.sleep(20000);
ArrayList<String> allHandles = new ArrayList<String> (driver.getWindowHandles()) ;
System.out.println("All Handles:" + allHandles);
Alert alert = driver.switchTo().alert();
System.out.println("Alert Text : " + alert.getText());
//alert.accept();
alert.sendKeys("Kushal");
alert.accept();
System.out.println(driver.findElement(By.xpath("//*[@id='demo']")).getText());
}
}
Html File:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to demonstrate the prompt box.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var person = prompt("Please enter your name", "Harry Potter");
if (person != null) {
document.getElementById("demo").innerHTML =
"Hello " + person + "! How are you today?";
}
}
</script>
</body>
</html>
public class ExcelOperations {
static String filePath = "C:\\Eclipse\\Workspace\\Resources\\Scenarios.xlsx";
public static void main(String[] args) throws IOException{
Dictionary <String, String> fetched = readExcelFile(filePath, "Standard Checkout","PCIEncryptedTC01");
System.out.println("Tokenization = " + fetched.get("Tokenization"));
}
public static void CreateExcelFile(String fileName) throws IOException {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("MySheet1");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
//cell.setCellType(CellType.STRING);
cell.setCellValue("Kushal entered first value!");
FileOutputStream fos = new FileOutputStream("C:/" + fileName);
workbook.write(fos);
fos.flush();
fos.close();
workbook.close();
}
//reading single cell
public static void readFromExcel(String fileName) throws IOException {
FileInputStream fis = new FileInputStream("C:/" + fileName);
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheet("MySheet1");
Row row = sheet.getRow(1);
Cell cell = row.getCell(1);
System.out.println("Value from Excel is : " + cell.getStringCellValue());
fis.close();
workbook.close();
}
//reading whole row
public static Dictionary<String, String> readExcelFile(String filePath, String sheetName, String currTestName) throws IOException {
FileInputStream fis = new FileInputStream(filePath);
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheet(sheetName);
int rowCount =sheet.getLastRowNum();
int colCount = sheet.getRow(0).getLastCellNum();
Row matchedRow =null;
System.out.println("RowCount : " + rowCount);
System.out.println("ColCount : " + colCount);
int i;
for( i=0; i<=rowCount; i++){
matchedRow = sheet.getRow(i);
Cell cell = matchedRow.getCell(0);
try{
String testName = cell.getStringCellValue();
//System.out.println(testName + currTestName);
if(testName.contains(currTestName)){
System.out.println("break called at" + i);
break;
};
}
catch(NullPointerException e){
e.printStackTrace();
}
}
System.out.println("Matched Row:" + i);
Dictionary <String, String> testDataRecord = new Hashtable<String, String>();
for(int j=0 ;j <colCount; j++){
try{
System.out.println("Header : " + sheet.getRow(0).getCell(j).getStringCellValue() + " : " + matchedRow.getCell(j).getStringCellValue());
testDataRecord.put(sheet.getRow(0).getCell(j).toString(), matchedRow.getCell(j).toString());
}
catch(NullPointerException e){
DataFormatter df = new DataFormatter();
String value = df.formatCellValue(matchedRow.getCell(j));
testDataRecord.put(sheet.getRow(0).getCell(j).toString(), value);
System.out.println("Header : " + sheet.getRow(0).getCell(j).getStringCellValue() + " : " + null);
}
catch(IllegalStateException e){
DataFormatter df = new DataFormatter();
String value = df.formatCellValue(matchedRow.getCell(j));
testDataRecord.put(sheet.getRow(0).getCell(j).toString(), value);
System.out.println("Header : " + sheet.getRow(0).getCell(j).getStringCellValue() + " : " + value);
}
}
System.out.println(" - -- -- - --- ");
fis.close();
workbook.close();
return testDataRecord;
}
public static void WriteExcelFile(String fileName) throws IOException {
FileInputStream fis = new FileInputStream("C:/" + fileName);
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheet("MySheet1");
Row row = sheet.getRow(5);
Cell cell = row.getCell(5);
//cell.setCellType(CellType.STRING);
cell.setCellValue("Kushal entered 55 value!");
FileOutputStream fos = new FileOutputStream("C:/" + fileName);
workbook.write(fos);
fos.flush();
fos.close();
fis.close();
workbook.close();
}
}
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Dictionary;
import java.util.Hashtable;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelOperations {
static String filePath = "C:\\Eclipse\\Workspace\\Resources\\Scenarios.xlsx";
public static void main(String[] args) throws IOException{
Dictionary <String, String> fetched = readRecordFromExcel(filePath, "Standard Checkout","PCIEncryptedTC01");
System.out.println("Tokenization = " + fetched.get("Tokenization"));
}
public static void CreateExcelFile(String fileName) {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("MySheet1");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
//cell.setCellType(CellType.STRING);
cell.setCellValue("Kushal entered first value!");
FileOutputStream fos;
try {
fos = new FileOutputStream("C:/" + fileName);
workbook.write(fos);
fos.flush();
fos.close();
workbook.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//reading single cell
public static void readFromExcel(String fileName) {
FileInputStream fis;
try {
fis = new FileInputStream("C:/" + fileName);
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheet("MySheet1");
Row row = sheet.getRow(1);
Cell cell = row.getCell(1);
System.out.println("Value from Excel is : " + cell.getStringCellValue());
fis.close();
workbook.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//reading whole row
public static Dictionary<String, String> readRecordFromExcel(String filePath, String sheetName, String currTestName) {
FileInputStream fis = null;
Dictionary <String, String> testDataRecord = null;
try {
fis = new FileInputStream(filePath);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
XSSFWorkbook workbook;
try {
workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheet(sheetName);
int rowCount =sheet.getLastRowNum();
int colCount = sheet.getRow(0).getLastCellNum();
Row matchedRow =null;
System.out.println("Row Count : " + rowCount);
System.out.println("Column Count : " + colCount);
int i;
for( i=0; i<=rowCount; i++){
matchedRow = sheet.getRow(i);
Cell cell = matchedRow.getCell(0);
try{
String testName = cell.getStringCellValue();
//System.out.println(testName + currTestName);
if(testName.contains(currTestName)){
break;
};
}
catch(NullPointerException e){
e.printStackTrace();
}
}
System.out.println("Matched Row#:" + i);
testDataRecord = new Hashtable<String, String>();
for(int j=0 ;j <colCount; j++){
try{
System.out.println("Header : " + sheet.getRow(0).getCell(j).getStringCellValue() + " : " + matchedRow.getCell(j).getStringCellValue());
testDataRecord.put(sheet.getRow(0).getCell(j).toString(), matchedRow.getCell(j).toString());
}
catch(NullPointerException e){
DataFormatter df = new DataFormatter();
String value = df.formatCellValue(matchedRow.getCell(j));
testDataRecord.put(sheet.getRow(0).getCell(j).toString(), value);
System.out.println("null : " + sheet.getRow(0).getCell(j).getStringCellValue() + " : " + null);
}
catch(IllegalStateException e){
DataFormatter df = new DataFormatter();
String value = df.formatCellValue(matchedRow.getCell(j));
testDataRecord.put(sheet.getRow(0).getCell(j).toString(), value);
System.out.println("IOex : " + sheet.getRow(0).getCell(j).getStringCellValue() + " : " + value);
}
}
System.out.println(" - -- -- - --- ");
fis.close();
workbook.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return testDataRecord;
}
public static void WriteExcelFile(String fileName) throws IOException {
FileInputStream fis = new FileInputStream("C:/" + fileName);
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheet("MySheet1");
Row row = sheet.getRow(5);
Cell cell = row.getCell(5);
//cell.setCellType(CellType.STRING);
cell.setCellValue("Kushal entered 55 value!");
FileOutputStream fos = new FileOutputStream("C:/" + fileName);
workbook.write(fos);
fos.flush();
fos.close();
fis.close();
workbook.close();
}
}
package scraper;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class TableExample {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "c:\\SRP\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("file:///C:/Users/G09637255/Desktop/tables.htm");
System.out.println("Element is " + getTableElement(driver,2,4).getText());
}
public static WebElement getTableElement(WebDriver driver, int rowIndex, int colIndex){
WebElement table = driver.findElement(By.tagName("table"));
List<WebElement> tableRow = table.findElements(By.tagName("tr"));
Integer rows = tableRow.size();
System.out.println("Total Rows in table :" + rows.toString());
int c=0;
for(int i=0;i<rows;i++){
if(c==0){
List<WebElement> tableHeader = tableRow.get(i).findElements(By.tagName("th"));
Integer cols = tableHeader.size();
System.out.println("Total Header in the current row " + i + " : " + cols.toString());
c++;
continue;
}
List<WebElement> tableCol = tableRow.get(i).findElements(By.tagName("td"));
Integer cols = tableCol.size();
System.out.println("Total columns in the current row " + i + " : " + cols.toString());
for(int j=0;j<cols;j++){
if(i==rowIndex && j==colIndex){
System.out.println("i + j : " + i + j);
return tableCol.get(j);
}
}
}
return table;
}
}
Read, Write & Create Excel Sheets:
public class ExcelOperations {
static String filePath = "C:\\Eclipse\\Workspace\\Resources\\Scenarios.xlsx";
public static void main(String[] args) throws IOException{
Dictionary <String, String> fetched = readExcelFile(filePath, "Standard Checkout","PCIEncryptedTC01");
System.out.println("Tokenization = " + fetched.get("Tokenization"));
}
public static void CreateExcelFile(String fileName) throws IOException {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("MySheet1");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
//cell.setCellType(CellType.STRING);
cell.setCellValue("Kushal entered first value!");
FileOutputStream fos = new FileOutputStream("C:/" + fileName);
workbook.write(fos);
fos.flush();
fos.close();
workbook.close();
}
//reading single cell
public static void readFromExcel(String fileName) throws IOException {
FileInputStream fis = new FileInputStream("C:/" + fileName);
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheet("MySheet1");
Row row = sheet.getRow(1);
Cell cell = row.getCell(1);
System.out.println("Value from Excel is : " + cell.getStringCellValue());
fis.close();
workbook.close();
}
//reading whole row
public static Dictionary<String, String> readExcelFile(String filePath, String sheetName, String currTestName) throws IOException {
FileInputStream fis = new FileInputStream(filePath);
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheet(sheetName);
int rowCount =sheet.getLastRowNum();
int colCount = sheet.getRow(0).getLastCellNum();
Row matchedRow =null;
System.out.println("RowCount : " + rowCount);
System.out.println("ColCount : " + colCount);
int i;
for( i=0; i<=rowCount; i++){
matchedRow = sheet.getRow(i);
Cell cell = matchedRow.getCell(0);
try{
String testName = cell.getStringCellValue();
//System.out.println(testName + currTestName);
if(testName.contains(currTestName)){
System.out.println("break called at" + i);
break;
};
}
catch(NullPointerException e){
e.printStackTrace();
}
}
System.out.println("Matched Row:" + i);
Dictionary <String, String> testDataRecord = new Hashtable<String, String>();
for(int j=0 ;j <colCount; j++){
try{
System.out.println("Header : " + sheet.getRow(0).getCell(j).getStringCellValue() + " : " + matchedRow.getCell(j).getStringCellValue());
testDataRecord.put(sheet.getRow(0).getCell(j).toString(), matchedRow.getCell(j).toString());
}
catch(NullPointerException e){
DataFormatter df = new DataFormatter();
String value = df.formatCellValue(matchedRow.getCell(j));
testDataRecord.put(sheet.getRow(0).getCell(j).toString(), value);
System.out.println("Header : " + sheet.getRow(0).getCell(j).getStringCellValue() + " : " + null);
}
catch(IllegalStateException e){
DataFormatter df = new DataFormatter();
String value = df.formatCellValue(matchedRow.getCell(j));
testDataRecord.put(sheet.getRow(0).getCell(j).toString(), value);
System.out.println("Header : " + sheet.getRow(0).getCell(j).getStringCellValue() + " : " + value);
}
}
System.out.println(" - -- -- - --- ");
fis.close();
workbook.close();
return testDataRecord;
}
public static void WriteExcelFile(String fileName) throws IOException {
FileInputStream fis = new FileInputStream("C:/" + fileName);
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheet("MySheet1");
Row row = sheet.getRow(5);
Cell cell = row.getCell(5);
//cell.setCellType(CellType.STRING);
cell.setCellValue("Kushal entered 55 value!");
FileOutputStream fos = new FileOutputStream("C:/" + fileName);
workbook.write(fos);
fos.flush();
fos.close();
fis.close();
workbook.close();
}
}
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Dictionary;
import java.util.Hashtable;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelOperations {
static String filePath = "C:\\Eclipse\\Workspace\\Resources\\Scenarios.xlsx";
public static void main(String[] args) throws IOException{
Dictionary <String, String> fetched = readRecordFromExcel(filePath, "Standard Checkout","PCIEncryptedTC01");
System.out.println("Tokenization = " + fetched.get("Tokenization"));
}
public static void CreateExcelFile(String fileName) {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("MySheet1");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
//cell.setCellType(CellType.STRING);
cell.setCellValue("Kushal entered first value!");
FileOutputStream fos;
try {
fos = new FileOutputStream("C:/" + fileName);
workbook.write(fos);
fos.flush();
fos.close();
workbook.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//reading single cell
public static void readFromExcel(String fileName) {
FileInputStream fis;
try {
fis = new FileInputStream("C:/" + fileName);
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheet("MySheet1");
Row row = sheet.getRow(1);
Cell cell = row.getCell(1);
System.out.println("Value from Excel is : " + cell.getStringCellValue());
fis.close();
workbook.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//reading whole row
public static Dictionary<String, String> readRecordFromExcel(String filePath, String sheetName, String currTestName) {
FileInputStream fis = null;
Dictionary <String, String> testDataRecord = null;
try {
fis = new FileInputStream(filePath);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
XSSFWorkbook workbook;
try {
workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheet(sheetName);
int rowCount =sheet.getLastRowNum();
int colCount = sheet.getRow(0).getLastCellNum();
Row matchedRow =null;
System.out.println("Row Count : " + rowCount);
System.out.println("Column Count : " + colCount);
int i;
for( i=0; i<=rowCount; i++){
matchedRow = sheet.getRow(i);
Cell cell = matchedRow.getCell(0);
try{
String testName = cell.getStringCellValue();
//System.out.println(testName + currTestName);
if(testName.contains(currTestName)){
break;
};
}
catch(NullPointerException e){
e.printStackTrace();
}
}
System.out.println("Matched Row#:" + i);
testDataRecord = new Hashtable<String, String>();
for(int j=0 ;j <colCount; j++){
try{
System.out.println("Header : " + sheet.getRow(0).getCell(j).getStringCellValue() + " : " + matchedRow.getCell(j).getStringCellValue());
testDataRecord.put(sheet.getRow(0).getCell(j).toString(), matchedRow.getCell(j).toString());
}
catch(NullPointerException e){
DataFormatter df = new DataFormatter();
String value = df.formatCellValue(matchedRow.getCell(j));
testDataRecord.put(sheet.getRow(0).getCell(j).toString(), value);
System.out.println("null : " + sheet.getRow(0).getCell(j).getStringCellValue() + " : " + null);
}
catch(IllegalStateException e){
DataFormatter df = new DataFormatter();
String value = df.formatCellValue(matchedRow.getCell(j));
testDataRecord.put(sheet.getRow(0).getCell(j).toString(), value);
System.out.println("IOex : " + sheet.getRow(0).getCell(j).getStringCellValue() + " : " + value);
}
}
System.out.println(" - -- -- - --- ");
fis.close();
workbook.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return testDataRecord;
}
public static void WriteExcelFile(String fileName) throws IOException {
FileInputStream fis = new FileInputStream("C:/" + fileName);
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheet("MySheet1");
Row row = sheet.getRow(5);
Cell cell = row.getCell(5);
//cell.setCellType(CellType.STRING);
cell.setCellValue("Kushal entered 55 value!");
FileOutputStream fos = new FileOutputStream("C:/" + fileName);
workbook.write(fos);
fos.flush();
fos.close();
fis.close();
workbook.close();
}
}
Handling Table Data:
package scraper;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class TableExample {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "c:\\SRP\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("file:///C:/Users/G09637255/Desktop/tables.htm");
System.out.println("Element is " + getTableElement(driver,2,4).getText());
}
public static WebElement getTableElement(WebDriver driver, int rowIndex, int colIndex){
WebElement table = driver.findElement(By.tagName("table"));
List<WebElement> tableRow = table.findElements(By.tagName("tr"));
Integer rows = tableRow.size();
System.out.println("Total Rows in table :" + rows.toString());
int c=0;
for(int i=0;i<rows;i++){
if(c==0){
List<WebElement> tableHeader = tableRow.get(i).findElements(By.tagName("th"));
Integer cols = tableHeader.size();
System.out.println("Total Header in the current row " + i + " : " + cols.toString());
c++;
continue;
}
List<WebElement> tableCol = tableRow.get(i).findElements(By.tagName("td"));
Integer cols = tableCol.size();
System.out.println("Total columns in the current row " + i + " : " + cols.toString());
for(int j=0;j<cols;j++){
if(i==rowIndex && j==colIndex){
System.out.println("i + j : " + i + j);
return tableCol.get(j);
}
}
}
return table;
}
}
Receive Input From User:
package examples;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Alert;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class InputFromUser{
public static void main(String[] args) throws InterruptedException{
System.setProperty("webdriver.chrome.driver", "C:\\Eclipse\\Selenium\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("file:///C:/Users/G09637255/Desktop/Basic.html");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
String userValue;
int i=0;
Alert alert = null;
long elapsedTime;
long currentTime;
long startTime = System.currentTimeMillis()/1000;
do{
if(i==0){
((JavascriptExecutor) driver).executeScript("var aa = prompt('Enter Value',''); alert(aa);");
}
alert=driver.switchTo().alert();
userValue= alert.getText();
Thread.sleep(5000);
i++;
currentTime = System.currentTimeMillis()/1000;
elapsedTime = currentTime - startTime;
}while(userValue.contains("Enter Value") & elapsedTime <1000);
if(alert!= null){
alert.accept();
}
System.out.println("User input value: " + userValue );
}
}
File Reader:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FileReader {
private static final Logger LOGGER = LoggerFactory.getLogger(FileReader.class);
static FileInputStream fis = null;
static Properties pro = new Properties();
public static String getProperty(String filePath, String propName) {
try {
LOGGER.info("FileReader searching for file at = " + filePath);
fis = new FileInputStream(new File(filePath));
}
catch(FileNotFoundException e){
LOGGER.error("FileReader could not find the requested file...!!");
}
try {
pro.load(fis);
}
catch(IOException e){
LOGGER.error("FileReader could not load the requested file...!!");
}
LOGGER.info("Retrieving value for property [" + propName +"] as :" + pro.getProperty(propName));
return pro.getProperty(propName);
}
}
JSON Handler
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.json.*;
public class JSONOperations {
public static void main(String[] args) throws Exception {
String str = FileUtils.readFileToString( new File("./Config/JSON.properties"), "utf-8");
String JSONString = str;
JSONObject shippingInfo = JSONOperations.getJSONObject(JSONString,"shippingAddress");
JSONArray cryptoOptions = getJSONArray(JSONString, "cryptoOptions");
for (Object curr : cryptoOptions){
System.out.println(getJSONElement((JSONObject) curr, "master"));
JSONArray formatArray = getJSONArray((JSONObject) curr, "format");
System.out.println(formatArray);
for (Object currNT : formatArray){
System.out.println(currNT);
}
}
}
public static String getJSONElement(String jsonInput, String element) {
JSONObject base = new JSONObject(jsonInput);
String jarray = base.getString(element);
return jarray;
}
public static String getJSONElement(JSONObject jsonInput, String element) {
String jarray = jsonInput.getString(element);
return jarray;
}
public static String getJSONElementInt(String jsonInput, String element) {
JSONObject base = new JSONObject(jsonInput);
String jarray = base.get(element).toString();
return jarray;
}
public static String getJSONElementInt(JSONObject jsonInput, String element) {
String jarray = jsonInput.get(element).toString();
return jarray;
}
public static boolean getJSONElementBool(String jsonInput, String element) {
JSONObject base = new JSONObject(jsonInput);
boolean jarray = base.getBoolean(element);
return jarray;
}
public static boolean getJSONElementBool(JSONObject jsonInput, String element) {
boolean jarray = jsonInput.getBoolean(element);
return jarray;
}
public static JSONObject getJSONObject(String jsonInput, String childObject) {
JSONObject base = new JSONObject(jsonInput);
JSONObject child = base.getJSONObject(childObject);
return child;
}
public static JSONArray getJSONArray(String jsonInput, String element) {
JSONObject base = new JSONObject(jsonInput);
JSONArray jarray = base.getJSONArray(element);
return jarray;
}
public static JSONArray getJSONArray(JSONObject jsonInput, String element) {
JSONArray jarray = jsonInput.getJSONArray(element);
return jarray;
}
public static String formatJSON(String jsonInput){
String[] str = jsonInput.split(",");
for(int i =1; i< str.length ;i++){
if(i==1){
str[0]= str[0]+ ", \n";
}
str[0]= str[0] +(str[i] +", \n");
}
String context = str[0];
return context;
}
public static String formattoHtml(String jsonInput){
String[] str = jsonInput.split(",");
for(int i =1; i< str.length ;i++){
if(i==1){
str[0]= "<pre>sdsadsadsad" + str[0]+ ", <pre>";
}
str[0]= str[0] +(str[i] +", <pre>");
}
String context = str[0];
return context;
}
}
No comments:
Post a Comment