0% found this document useful (0 votes)
4 views36 pages

Programs

Uploaded by

sindhu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views36 pages

Programs

Uploaded by

sindhu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

element.

sendKeys("SoftwareTestingHelp");
element.sendKeys(Keys.ENTER);

java.util.List<WebElement> link =
driver.findElements(By.tagName("a"));
System.out.println(link.size());

for (WebElement link2: link) {

//print the links i.e. http://google.com or https://www.gmail.com


System.out.println(link2.getAttribute("href"));

//print the links text


System.out.println(link2.getText());

Robot robot = new Robot(); // instantiated robot class


robot.keyPress(KeyEvent.VK_CONTROL); // with robot class you can
easily achieve anything if you know the shortcut keys
robot.keyPress(KeyEvent.VK_2); // here, we have just pressed
ctrl+2
robot.keyRelease(KeyEvent.VK_CONTROL); // once we press and
release ctrl+2, it will go to the second tab.
robot.keyRelease(KeyEvent.VK_2); //if you again want to go back
to first tab press and release vk_1
}

public class DuplicateCharacters {

public static void main(String[] args) {


// TODO Auto-generated method stub
String str = new String("Sakkett");
int count = 0;
char[] chars = str.toCharArray();
System.out.println("Duplicate characters are:");
for (int i=0; i<str.length();i++) {
for(int j=i+1; j<str.length();j++) {
if (chars[i] == chars[j]) {
System.out.println(chars[j
]);
count++;
break;
}
}
}
}

package codes;
public class SecondHighestNumberInArray {
public static void main(String[] args)
{
int arr[] = { 100,14, 46, 47, 94, 94, 52, 86, 36, 94, 89 };
int largest = 0;
int secondLargest = 0;
System.out.println("The given array is:");
for (int i = 0; i < arr.length; i++)
{
System.out.print(arr[i] + "\t");
}
for (int i = 0; i < arr.length; i++)
{
if (arr[i] > largest)
{
secondLargest = largest;
largest = arr[i];
}
else if (arr[i] > secondLargest)
{
secondLargest = arr[i];
}
}
System.out.println("\nSecond largest number is:" + secondLargest);
System.out.println("Largest Number is: " +largest);
}
}

class Armstrong{
public static void main(String[] args) {
int c=0,a,temp;
int n=153;//It is the number to check Armstrong
temp=n;
while(n&gt;0)
{
a=n%10;
n=n/10;
c=c+(a*a*a);
}
if(temp==c)
System.out.println("armstrong number");
else
System.out.println("Not armstrong number");
}
}

class RemoveWhiteSpaces
{
public static void main(String[] args)
{
String str1 = "Saket Saurav is a QualityAna list";

//1. Using replaceAll() Method

String str2 = str1.replaceAll("\\s", "");

System.out.println(str2);
}
}
}

class RemoveWhiteSpaces
{
public static void main(String[] args)
{
String str1 = "Saket Saurav is an Autom ation Engi ne er";

char[] chars = str1.toCharArray();

StringBuffer sb = new StringBuffer();

for (int i = 0; i &lt; chars.length; i++)


{
if( (chars[i] != ' ') &amp;&amp; (chars[i] != '\t') )
{
sb.append(chars[i]);
}
}
System.out.println(sb); //Output :
CoreJavajspservletsjdbcstrutshibernatespring
}
}

@Test
public void ReadData() throws IOException
{
// Import excel sheet from a webdriver directory which is inside c drive.
//DataSource is the name of the excel
File src=new File("C:\\webdriver\\DataSource.xls");

//This step is for loading the file. We have used FileInputStream as


//we are reading the excel. In case you want to write into the file,
//you need to use FileOutputStream. The path of the file is passed as an
argument to FileInputStream
FileInputStream finput = new FileInputStream(src);

//This step is to load the workbook of the excel which is done by global
HSSFWorkbook in which we have
//passed finput as an argument.
workbook = new HSSFWorkbook(finput);

//This step is to load the sheet in which data is stored.


sheet= workbook.getSheetAt(0);

for(int i=1; i&lt;=sheet.getLastRowNum(); i++)


{
// Import data for Email.
cell = sheet.getRow(i).getCell(1);
cell.setCellType(Cell.CELL_TYPE_STRING);
driver.findElement(By.id("email")).sendKeys(cell.getStringCellValue()
);
// Import data for the password.
cell = sheet.getRow(i).getCell(2);
cell.setCellType(Cell.CELL_TYPE_STRING);
driver.findElement(By.id("password")).sendKeys(cell.getStringCellValu
e());

}
}

Log 4j
PropertyConfigurator.configure("./src/test/resources/properties/
log4j.properties");

@FindBy(css = "#location-field-destination-menu > div:nth-child(1) >


button:nth-child(3)")
public WebElement goingToCity;

Page Object
public HomePageLocators home;

public HomePage(){
this.home = new HomePageLocators();
AjaxElementLocatorFactory factory = new
AjaxElementLocatorFactory(driver,10);
PageFactory.initElements(factory, this.home);

Fluent Wait

Wait wait = new FluentWait(WebDriver reference)


.withTimeout(timeout, SECONDS)
.pollingEvery(timeout, SECONDS)
.ignoring(Exception.class);

Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)

.withTimeout(30, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);

1. presenceOfAllElementsLocatedBy()
2. presenceOfElementLocated()
3. textToBePresentInElement()
4. textToBePresentInElementLocated()

Explicit

WebDriverWait wait=new WebDriverWait(driver, 20);


guru99seleniumlink=
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(
"/html/body/div[1]/section/div[2]/div/div[1]/div/div[1]/div/div/div/div[2]/
div[2]/div/div/div/div/div[1]/div/div/a/i")));

5. WebDriverWait wait = new WebDriverWait(WebDriverRefrence,TimeOut);

Take screen shot


System.setProperty("org.uncommons.reportng.escape-output", "false");
String scrShotName = d.toString().replace(":", "_").replace(" ",
"_")+".jpg";

File screenshot =
((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new
File(".//screenshot//"+scrShotName));

Count Words using Has map

package com.basicconcepts.java;

import java.util.HashMap;

public class FinalCountWordsUsingHashMap {

public static void main(String[] args) {


// TODO Auto-generated method stub

String str = "This this is is done by Saket Saket";


String split[] = str.split(" ");

HashMap<String, Integer> map = new HashMap<String, Integer>();


for (int i = 0; i < split.length; i++) {
if (map.containsKey(split[i])) {
int count = map.get(split[i]);
System.out.println(count+split[i]);
map.put(split[i], count + 1);
} else {
map.put(split[i], 1);
}
map.entrySet().iterator();
}
System.out.println(map);
}

package com.basicconcepts.java;

import java.util.Scanner;

public class ReverseAString {

public static void main(String[] args) {


// TODO Auto-generated method stub

stringReverseSplit();

public static void stringReverseStringBuider() {

String str = "Automation";


StringBuilder str2 = new StringBuilder();
StringBuffer str3 = new StringBuffer();
str3.append(str);
str2.append(str); // appeneding str to str2
str2 = str2.reverse(); // used string builder to reverse
str3 = str3.reverse();

System.out.println(str3);

// difference between string builder and string buffer is strig


builder does not
// generate syncronization

public static void stringReverseWithoutStringBuider() {

String str = "Sindhu";


char chars[] = str.toCharArray(); // converted to character array
and printed in reverse order
for (int i = chars.length - 1; i >= 0; i--) {
System.out.print(chars[i]);
}
}

public static void stringReverseSplit() {

String str;
Scanner in = new Scanner(System.in);
System.out.println("Enter your String");
str = in.nextLine();
String[] token = str.split(""); // used split method to print in
reverse order
for (int i = token.length - 1; i >= 0; i--) {
System.out.print(token[i] + "");
}
}

public static void reverseSplit() {

String original, reverse = "";


System.out.println("Enter the string to be reversed");
Scanner in = new Scanner(System.in);
original = in.nextLine();
int length = original.length();
for (int i = length - 1; i >= 0; i--) {
reverse = reverse + original.charAt(i); // used inbuilt
method charAt() to reverse the string
}
System.out.println(reverse);
}

public void toGetaplhabetsCount() {


Scanner in = new Scanner(System.in);
System.out.println("Enter the string to get the words count");
String str = in.nextLine();
Map<String, Integer> map = new HashMap<String, Integer>();
String split[] = str.split("");
for (int i = 0; i < split.length; i++) {

if(map.containsKey(split[i])) {
int count = map.get(split[i]);
System.out.println(count+split[i]);
map.put(split[i], count + 1);
}else {
map.put(split[i], 1);
}
map.entrySet().iterator();
}
System.out.println(map);
}

public void hashMapIterator() {


Map<Integer,String> map = new HashMap<Integer,String>();
map.put(24, "test");
map.put(10, "test1");
map.put(15, "test2");
Iterator itr = map.entrySet().iterator();
System.out.println(map.size());
System.out.println(map.get(10));
while(itr.hasNext()) {
Map.Entry mapItr1 = (Map.Entry) itr.next();
System.out.println("The key and the value
is"+mapItr1.getKey()+mapItr1.getValue());

}
for(Map.Entry me2: map.entrySet()) {
System.out.println("Key is: " + me2.getKey() + " Value is: " +
me2.getValue());
}

}
public void getCountString() {
Scanner in = new Scanner(System.in);
System.out.println("Enter teh string");
String str = in.nextLine();
int count=0;
for(int i=0;i<str.length();i++) {
if(str.charAt(i)!=' ') {
count++;
}
}
System.out.println(count);
System.out.println(str.length());
}

public void anagram() {


Scanner in = new Scanner(System.in);
System.out.println("Enter the 2 strings");
String str1 = in.nextLine();
String str2 = in.nextLine();

str1 = str1.toLowerCase();
str2 = str2.toLowerCase();

char char1[] = str1.toCharArray();


char char2[] = str2.toCharArray();

Arrays.sort(char1);
Arrays.sort(char2);

if(Arrays.equals(char1, char2)== true) {


System.out.println("The strings are anagram");

}else {
System.out.println("The string is not anagram");
}
}
Excel

package com.w2a.utilities;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.util.Calendar;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;

import org.apache.poi.hssf.usermodel.HSSFDateUtil;

import org.apache.poi.hssf.util.HSSFColor;

import org.apache.poi.ss.usermodel.Cell;

import org.apache.poi.ss.usermodel.CellStyle;

import org.apache.poi.ss.usermodel.IndexedColors;

import org.apache.poi.xssf.usermodel.XSSFCell;

import org.apache.poi.xssf.usermodel.XSSFCellStyle;

import org.apache.poi.xssf.usermodel.XSSFCreationHelper;

import org.apache.poi.xssf.usermodel.XSSFFont;

import org.apache.poi.xssf.usermodel.XSSFHyperlink;

import org.apache.poi.xssf.usermodel.XSSFRow;

import org.apache.poi.xssf.usermodel.XSSFSheet;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelReader {

public String path;

public FileInputStream fis = null;


public FileOutputStream fileOut =null;

private XSSFWorkbook workbook = null;

private XSSFSheet sheet = null;

private XSSFRow row =null;

private XSSFCell cell = null;

public ExcelReader(String path) {

this.path=path;

try {

fis = new FileInputStream(path);

workbook = new XSSFWorkbook(fis);

sheet = workbook.getSheetAt(0);

fis.close();

} catch (Exception e) {

e.printStackTrace();

// returns the row count in a sheet

public int getRowCount(String sheetName){

int index = workbook.getSheetIndex(sheetName);

if(index==-1)

return 0;

else{

sheet = workbook.getSheetAt(index);
int number=sheet.getLastRowNum()+1;

return number;

// returns the data from a cell

public String getCellData(String sheetName,String colName,int rowNum){

try{

if(rowNum <=0)

return "";

int index = workbook.getSheetIndex(sheetName);

int col_Num=-1;

if(index==-1)

return "";

sheet = workbook.getSheetAt(index);

row=sheet.getRow(0);

for(int i=0;i<row.getLastCellNum();i++){

//System.out.println(row.getCell(i).getStringCellValue().trim());

if(row.getCell(i).getStringCellValue().trim().equals(colName.trim()))

col_Num=i;

if(col_Num==-1)

return "";
sheet = workbook.getSheetAt(index);

row = sheet.getRow(rowNum-1);

if(row==null)

return "";

cell = row.getCell(col_Num);

if(cell==null)

return "";

if(cell.getCellType()==Cell.CELL_TYPE_STRING)

return cell.getStringCellValue();

else if(cell.getCellType()==Cell.CELL_TYPE_NUMERIC ||
cell.getCellType()==Cell.CELL_TYPE_FORMULA ){

String cellText = String.valueOf(cell.getNumericCellValue());

if (HSSFDateUtil.isCellDateFormatted(cell)) {

double d = cell.getNumericCellValue();

Calendar cal =Calendar.getInstance();

cal.setTime(HSSFDateUtil.getJavaDate(d));

cellText =

(String.valueOf(cal.get(Calendar.YEAR))).substring(2);

cellText = cal.get(Calendar.DAY_OF_MONTH) + "/" +

cal.get(Calendar.MONTH)+1 + "/" +

cellText;
}

return cellText;

}else if(cell.getCellType()==Cell.CELL_TYPE_BLANK)

return "";

else

return String.valueOf(cell.getBooleanCellValue());

catch(Exception e){

e.printStackTrace();

return "row "+rowNum+" or column "+colName +" does not exist in xls";

// returns the data from a cell

public String getCellData(String sheetName,int colNum,int rowNum){

try{

if(rowNum <=0)

return "";

int index = workbook.getSheetIndex(sheetName);

if(index==-1)
return "";

sheet = workbook.getSheetAt(index);

row = sheet.getRow(rowNum-1);

if(row==null)

return "";

cell = row.getCell(colNum);

if(cell==null)

return "";

if(cell.getCellType()==Cell.CELL_TYPE_STRING)

return cell.getStringCellValue();

else if(cell.getCellType()==Cell.CELL_TYPE_NUMERIC ||
cell.getCellType()==Cell.CELL_TYPE_FORMULA ){

String cellText = String.valueOf(cell.getNumericCellValue());

if (HSSFDateUtil.isCellDateFormatted(cell)) {

// format in form of M/D/YY

double d = cell.getNumericCellValue();

Calendar cal =Calendar.getInstance();

cal.setTime(HSSFDateUtil.getJavaDate(d));

cellText =

(String.valueOf(cal.get(Calendar.YEAR))).substring(2);

cellText = cal.get(Calendar.MONTH)+1 + "/" +

cal.get(Calendar.DAY_OF_MONTH) + "/" +

cellText;
}

return cellText;

}else if(cell.getCellType()==Cell.CELL_TYPE_BLANK)

return "";

else

return String.valueOf(cell.getBooleanCellValue());

catch(Exception e){

e.printStackTrace();

return "row "+rowNum+" or column "+colNum +" does not exist in xls";

// returns true if data is set successfully else false

public boolean setCellData(String sheetName,String colName,int rowNum, String data){

try{

fis = new FileInputStream(path);

workbook = new XSSFWorkbook(fis);

if(rowNum<=0)
return false;

int index = workbook.getSheetIndex(sheetName);

int colNum=-1;

if(index==-1)

return false;

sheet = workbook.getSheetAt(index);

row=sheet.getRow(0);

for(int i=0;i<row.getLastCellNum();i++){

//System.out.println(row.getCell(i).getStringCellValue().trim());

if(row.getCell(i).getStringCellValue().trim().equals(colName))

colNum=i;

if(colNum==-1)

return false;

sheet.autoSizeColumn(colNum);

row = sheet.getRow(rowNum-1);

if (row == null)

row = sheet.createRow(rowNum-1);

cell = row.getCell(colNum);

if (cell == null)

cell = row.createCell(colNum);
cell.setCellValue(data);

fileOut = new FileOutputStream(path);

workbook.write(fileOut);

fileOut.close();

catch(Exception e){

e.printStackTrace();

return false;

return true;

// returns true if data is set successfully else false

public boolean setCellData(String sheetName,String colName,int rowNum, String data,String url)


{

try{

fis = new FileInputStream(path);

workbook = new XSSFWorkbook(fis);

if(rowNum<=0)

return false;
int index = workbook.getSheetIndex(sheetName);

int colNum=-1;

if(index==-1)

return false;

sheet = workbook.getSheetAt(index);

row=sheet.getRow(0);

for(int i=0;i<row.getLastCellNum();i++){

if(row.getCell(i).getStringCellValue().trim().equalsIgnoreCase(colName))

colNum=i;

if(colNum==-1)

return false;

sheet.autoSizeColumn(colNum);

row = sheet.getRow(rowNum-1);

if (row == null)

row = sheet.createRow(rowNum-1);

cell = row.getCell(colNum);

if (cell == null)

cell = row.createCell(colNum);

cell.setCellValue(data);

XSSFCreationHelper createHelper = workbook.getCreationHelper();


//cell style for hyperlinks

CellStyle hlink_style = workbook.createCellStyle();

XSSFFont hlink_font = workbook.createFont();

hlink_font.setUnderline(XSSFFont.U_SINGLE);

hlink_font.setColor(IndexedColors.BLUE.getIndex());

hlink_style.setFont(hlink_font);

//hlink_style.setWrapText(true);

XSSFHyperlink link = createHelper.createHyperlink(XSSFHyperlink.LINK_FILE);

link.setAddress(url);

cell.setHyperlink(link);

cell.setCellStyle(hlink_style);

fileOut = new FileOutputStream(path);

workbook.write(fileOut);

fileOut.close();

catch(Exception e){

e.printStackTrace();

return false;

return true;

}
// returns true if sheet is created successfully else false

public boolean addSheet(String sheetname){

FileOutputStream fileOut;

try {

workbook.createSheet(sheetname);

fileOut = new FileOutputStream(path);

workbook.write(fileOut);

fileOut.close();

} catch (Exception e) {

e.printStackTrace();

return false;

return true;

// returns true if sheet is removed successfully else false if sheet does not exist

public boolean removeSheet(String sheetName){

int index = workbook.getSheetIndex(sheetName);

if(index==-1)

return false;

FileOutputStream fileOut;

try {

workbook.removeSheetAt(index);

fileOut = new FileOutputStream(path);

workbook.write(fileOut);

fileOut.close();
} catch (Exception e) {

e.printStackTrace();

return false;

return true;

// returns true if column is created successfully

public boolean addColumn(String sheetName,String colName){

try{

fis = new FileInputStream(path);

workbook = new XSSFWorkbook(fis);

int index = workbook.getSheetIndex(sheetName);

if(index==-1)

return false;

XSSFCellStyle style = workbook.createCellStyle();

style.setFillForegroundColor(HSSFColor.GREY_40_PERCENT.index);

style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

sheet=workbook.getSheetAt(index);

row = sheet.getRow(0);

if (row == null)

row = sheet.createRow(0);

if(row.getLastCellNum() == -1)
cell = row.createCell(0);

else

cell = row.createCell(row.getLastCellNum());

cell.setCellValue(colName);

cell.setCellStyle(style);

fileOut = new FileOutputStream(path);

workbook.write(fileOut);

fileOut.close();

}catch(Exception e){

e.printStackTrace();

return false;

return true;

// removes a column and all the contents

public boolean removeColumn(String sheetName, int colNum) {

try{

if(!isSheetExist(sheetName))

return false;

fis = new FileInputStream(path);


workbook = new XSSFWorkbook(fis);

sheet=workbook.getSheet(sheetName);

XSSFCellStyle style = workbook.createCellStyle();

style.setFillForegroundColor(HSSFColor.GREY_40_PERCENT.index);

XSSFCreationHelper createHelper = workbook.getCreationHelper();

style.setFillPattern(HSSFCellStyle.NO_FILL);

for(int i =0;i<getRowCount(sheetName);i++){

row=sheet.getRow(i);

if(row!=null){

cell=row.getCell(colNum);

if(cell!=null){

cell.setCellStyle(style);

row.removeCell(cell);

fileOut = new FileOutputStream(path);

workbook.write(fileOut);

fileOut.close();

catch(Exception e){

e.printStackTrace();

return false;

return true;
}

// find whether sheets exists

public boolean isSheetExist(String sheetName){

int index = workbook.getSheetIndex(sheetName);

if(index==-1){

index=workbook.getSheetIndex(sheetName.toUpperCase());

if(index==-1)

return false;

else

return true;

else

return true;

// returns number of columns in a sheet

public int getColumnCount(String sheetName){

// check if sheet exists

if(!isSheetExist(sheetName))

return -1;

sheet = workbook.getSheet(sheetName);

row = sheet.getRow(0);

if(row==null)

return -1;
return row.getLastCellNum();

//String sheetName, String testCaseName,String keyword ,String URL,String message

public boolean addHyperLink(String sheetName,String screenShotColName,String


testCaseName,int index,String url,String message){

url=url.replace('\\', '/');

if(!isSheetExist(sheetName))

return false;

sheet = workbook.getSheet(sheetName);

for(int i=2;i<=getRowCount(sheetName);i++){

if(getCellData(sheetName, 0, i).equalsIgnoreCase(testCaseName)){

setCellData(sheetName, screenShotColName, i+index, message,url);

break;

return true;
}

public int getCellRowNum(String sheetName,String colName,String cellValue){

for(int i=2;i<=getRowCount(sheetName);i++){

if(getCellData(sheetName,colName , i).equalsIgnoreCase(cellValue)){

return i;

return -1;

// to run this on stand alone

public static void main(String arg[]) throws IOException{

ExcelReader datatable = null;

datatable = new ExcelReader("C:\\CM3.0\\app\\test\\Framework\\


AutomationBvt\\src\\config\\xlfiles\\Controller.xlsx");

for(int col=0 ;col< datatable.getColumnCount("TC5"); col++){

System.out.println(datatable.getCellData("TC5", col, 1));

}
@DataProvider(name="dp")
public Object[][] getData(Method m) {

String sheetName = m.getName();


int rows = excel.getRowCount(sheetName);
int cols = excel.getColumnCount(sheetName);

Object[][] data = new Object[rows - 1][1];

Hashtable<String,String> table = null;

for (int rowNum = 2; rowNum <= rows; rowNum++) { // 2

table = new Hashtable<String,String>();

for (int colNum = 0; colNum < cols; colNum++) {

// data[0][0]
table.put(excel.getCellData(sheetName, colNum, 1),
excel.getCellData(sheetName, colNum, rowNum));
data[rowNum - 2][0] = table;
}

return data;

WebElement dropdownElement = driver.findElement(By.id("locator"));


Select select = new Select(dropdownElement); //select.getoptions() returns
all options belonging to select tag List<WebElement> options =
select.getOptions(); for (WebElement option : options) { for (int
i = 0; i < values.length; i++) { if
(option.getText().equals(values[i])) { count++; }
} }

Prime or not
import java.util.Scanner;

public class Prime {

public static void main(String[] args) {


// TODO Auto-generated method stub
int temp, num;
boolean isPrime = true;
Scanner in = new Scanner(System.in);
num = in.nextInt();
in.close();
for (int i = 2; i&lt;= num/2; i++) {
temp = num%i;
if (temp == 0) {
isPrime = false;
break;
}
}
if(isPrime)
System.out.println(num + "number is prime");
else
System.out.println(num + "number is not a prime");

public class Fibonacci {


public static void main(String[] args) {
int num, a = 0,b=0, c =1;
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of times");
num = in.nextInt();
System.out.println("Fibonacci Series of the number is:");
for (int i=0; i<num; i++) {
a = b;
b = c;
c = a+b;
System.out.println(a + ""); //if you want to print on the same
line, use print()
}
}
}

Array list
import java.util.*;

public class arrayList {


public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add("20");
list.add("30");
list.add("40");
System.out.println(list.size());
System.out.println("While Loop:");
Iterator itr = list.iterator();
while(itr.hasNext()) {
System.out.println(itr.next());
}
System.out.println("Advanced For Loop:");
for(Object obj : list) {
System.out.println(obj);
}
System.out.println("For Loop:");
for(int i=0; i&lt;list.size(); i++) {
System.out.println(list.get(i));
}
}
}

WebDriverWait wait = new WebDriverWait(driver, 20);


WebElement element2 =
wait.until(ExpectedConditions.visibilityOfElementLocated(By.partialLinkText("S
oftware testing - Wikipedia")));
element2.click();

Event Reports

package extentlisteners;

import java.util.Arrays;

import java.util.Date;

import org.testng.ITestContext;

import org.testng.ITestListener;

import org.testng.ITestResult;

import com.aventstack.extentreports.ExtentReports;

import com.aventstack.extentreports.ExtentTest;

import com.aventstack.extentreports.Status;

import com.aventstack.extentreports.markuputils.ExtentColor;

import com.aventstack.extentreports.markuputils.Markup;

import com.aventstack.extentreports.markuputils.MarkupHelper;

public class ExtentListeners implements ITestListener {


static Date d = new Date();

static String fileName = "Extent_" + d.toString().replace(":", "_").replace(" ", "_") + ".html";

private static ExtentReports extent =


ExtentManager.createInstance(System.getProperty("user.dir")+"\\reports\\"+fileName);

public static ThreadLocal<ExtentTest> testReport = new ThreadLocal<ExtentTest>();

public void onTestStart(ITestResult result) {

ExtentTest test = extent.createTest(result.getTestClass().getName()+" @TestCase :


"+result.getMethod().getMethodName());

testReport.set(test);

public void onTestSuccess(ITestResult result) {

String methodName=result.getMethod().getMethodName();

String logText="<b>"+"TEST CASE:- "+ methodName.toUpperCase()+ " PASSED"+"</b>";

Markup m=MarkupHelper.createLabel(logText, ExtentColor.GREEN);

testReport.get().pass(m);

}
public void onTestFailure(ITestResult result) {

String excepionMessage=Arrays.toString(result.getThrowable().getStackTrace());

testReport.get().fail("<details>" + "<summary>" + "<b>" + "<font color=" + "red>" +


"Exception Occured:Click to see"

+ "</font>" + "</b >" + "</summary>" +excepionMessage.replaceAll(",",


"<br>")+"</details>"+" \n");

/* try {

ExtentManager.captureScreenshot();

testReport.get().fail("<b>" + "<font color=" + "red>" + "Screenshot of failure" +


"</font>" + "</b>",

MediaEntityBuilder.createScreenCaptureFromPath(ExtentManager.screenshotName)

.build());

} catch (IOException e) {

}*/

String failureLogg="TEST CASE FAILED";

Markup m = MarkupHelper.createLabel(failureLogg, ExtentColor.RED);

testReport.get().log(Status.FAIL, m);

}
public void onTestSkipped(ITestResult result) {

String methodName=result.getMethod().getMethodName();

String logText="<b>"+"Test Case:- "+ methodName+ " Skipped"+"</b>";

Markup m=MarkupHelper.createLabel(logText, ExtentColor.YELLOW);

testReport.get().skip(m);

public void onTestFailedButWithinSuccessPercentage(ITestResult result) {

// TODO Auto-generated method stub

public void onStart(ITestContext context) {

public void onFinish(ITestContext context) {

if (extent != null) {

extent.flush();

}
package extentlisteners;

import com.aventstack.extentreports.ExtentReports;

import com.aventstack.extentreports.reporter.ExtentHtmlReporter;

import com.aventstack.extentreports.reporter.configuration.Theme;

public class ExtentManager {

private static ExtentReports extent;

public static ExtentReports createInstance(String fileName) {

ExtentHtmlReporter htmlReporter = new ExtentHtmlReporter(fileName);

htmlReporter.config().setTheme(Theme.STANDARD);

htmlReporter.config().setDocumentTitle(fileName);

htmlReporter.config().setEncoding("utf-8");

htmlReporter.config().setReportName(fileName);

extent = new ExtentReports();

extent.attachReporter(htmlReporter);

extent.setSystemInfo("Automation Tester", "Rahul Arora");

extent.setSystemInfo("Organization", "Way2Automation");

extent.setSystemInfo("Build no", "W2A-1234");


return extent;

/* public static String screenshotPath;

public static String screenshotName;

public static void captureScreenshot() {

File scrFile = ((TakesScreenshot)


DriverManager.getDriver()).getScreenshotAs(OutputType.FILE);

Date d = new Date();

screenshotName = d.toString().replace(":", "_").replace(" ", "_") + ".jpg";

try {

FileUtils.copyFile(scrFile, new File(System.getProperty("user.dir") + "\\


reports\\" + screenshotName));

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}*/
}

public boolean isElementPresent(By by) {

try {

driver.findElement(by);
return true;

} catch (NoSuchElementException e) {

return false;
}

@DataProvider(name="dp")
public Object[][] getData(Method m) {

String sheetName = m.getName();


int rows = excel.getRowCount(sheetName);
int cols = excel.getColumnCount(sheetName);

Object[][] data = new Object[rows - 1][1];

Hashtable<String,String> table = null;

for (int rowNum = 2; rowNum <= rows; rowNum++) { // 2

table = new Hashtable<String,String>();

for (int colNum = 0; colNum < cols; colNum++) {

// data[0][0]
table.put(excel.getCellData(sheetName, colNum, 1),
excel.getCellData(sheetName, colNum, rowNum));
data[rowNum - 2][0] = table;
}

return data;

public static boolean isTestRunnable(String testName, ExcelReader


excel){

String sheetName="test_suite";
int rows = excel.getRowCount(sheetName);
for(int rNum=2; rNum<=rows; rNum++){

String testCase = excel.getCellData(sheetName, "TCID",


rNum);

if(testCase.equalsIgnoreCase(testName)){

String runmode = excel.getCellData(sheetName,


"Runmode", rNum);

if(runmode.equalsIgnoreCase("Y"))
return true;
else
return false;
}

}
return false;
}

You might also like