Wednesday, December 16, 2015

Updating testng xml at runtime


import java.util.ArrayList;
import java.util.List;
import org.openqa.selenium.WebDriver;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
import org.testng.xml.XmlClass;
import org.testng.xml.XmlSuite;
import org.testng.xml.XmlTest;
public class WebdriverITestListener implements ITestListener {
boolean ischecked=true;
public static XmlSuite suite ;
@Override
public void onFinish(ITestContext arg0) {
// TODO Auto-generated method stub
}
@Override
public void onTestFailedButWithinSuccessPercentage(ITestResult arg0) {
// TODO Auto-generated method stub
}
@Override
public void onTestFailure(ITestResult test) {
// TODO Auto-generated method stub
}
@Override
public void onTestSkipped(ITestResult arg0) {
// TODO Auto-generated method stub
}
@Override
public void onTestStart(ITestResult test) {
// TODO Auto-generated method stub
String browserName=test.getMethod().getXmlTest().getParameter("browserName");
if(ischecked)
{
List tests = new ArrayList();
XmlTest testsuite = new XmlTest(test.getMethod().getXmlTest().getSuite());
testsuite.setName("defalut");

List xmlclasses = new ArrayList();
xmlclasses.add(new XmlClass("TESTCASE NAME"));

testsuite.addParameter("browserName","firefox");
testsuite.setXmlClasses(xmlclasses);
tests.add(testsuite);
suite.setTests(tests);
test.getMethod().getXmlTest().setXmlSuite(suite);
ischecked=false;
}
System.out.println(test.getMethod().getXmlTest().getSuite()+"  ------------------   ");
WebDriver driver;
try {
driver = LocalDriverFactory.createInstance(browserName);
LocalDriverManager.setWebDriver(driver);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onTestSuccess(ITestResult arg0) {
// TODO Auto-generated method stub
}
@Override
public void onStart(ITestContext test) {
- hide quoted text -

}
}

Thursday, December 10, 2015

TestNG Parallel Execution

  • Methods: This will run the parallel tests on all @Test methods in TestNG.
  • Tests: All the test cases present inside the <test> tag will run with this value.
  • Classes: All the test cases present inside the classes that exist in the XML will run in parallel.

package com.parallel;
import org.testng.annotations.Test;

public class TestParallelOne {

    @Test
    public void testCaseOne() {
        //Printing Id of the thread on using which test method got executed
        System.out.println("Test Case One with Thread Id:- "
                + Thread.currentThread().getId());
    }

    @Test
    public void testCaseTwo() {
        ////Printing Id of the thread on using which test method got executed
        System.out.println("Test Case two with Thread Id:- "
                + Thread.currentThread().getId());
    }
}

Running test methods parallelly in TestNG using Selenium
http://testng.org/testng-1.0.dtd">
<suite name="Parallel test suite" parallel="methods" thread-count="2">
  <test name="Regression 1">
    <classes>
      <class name="com.parallel.TestParallelOne"/>
    </classes>
  </test>
</suite>

Running tests parallelly in TestNG using Selenium

<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd" >
<suite name = "Parallel Testing Suite" parallel = "tests" thread-count = "2">
   <test name = "Parallel Tests1">
      <classes>
        <class name="com.parallel.TestParallelOne"/>
      </classes>
   </test>
   <test name = "Parallel Tests2">
      <classes>
         <class name="com.parallel.TestParallelOne"/>
      </classes>
   </test>
</suite>
 Running test classes parallelly in TestNG using Selenium
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd" >
<suite name = "Parallel Testing Suite">
   <test name = "Parallel Tests" parallel = "classes" thread-count = "2">
      <classes>
         <class name="com.parallel.TestParallelOne"/>
         <class name="com.parallel.TestParallelOne"/>
      </classes>
   </test>
</suite>
   
 

Tuesday, October 27, 2015

Delete files in a Directory?

/**
     * Delete file
     *
     * @param filePath
     */
    public void deleteFile(String filePath) throws Exception {
        try {
            File file = new File(filePath);

            if (file.delete()) {
                System.out.println(file.getName() + " is deleted..!");
            }
        } catch (Exception e) {
            throw new Exception(">>>Error while deleting " + filePath + " file :<<<" + e.toString());
        }
    }
 
public void deleteFilesFromFolder(File directoryPath) {
        String[] myFiles;
        if (directoryPath.isDirectory()) {
            myFiles = directoryPath.list();
            for (int i = 0; i < myFiles.length; i++) {
                File myFile = new File(directoryPath, myFiles[i]);
                myFile.delete();
            }
        }
    }

EX: File directoryPath = new File("C:\\Example");

Thursday, September 10, 2015

Using log4j in Java Program

public static Logger logger_name = Logger.getLogger(classname.class);

PropertyConfigurator.configure(System.getProperty("user.dir") + "\\config\\log4j.properties");

EX:
public static Logger APP_LOGS = Logger.getLogger(DriverScript.class.getName());

log4j.properties:

# Define the root logger with appender file
log = TestOutput/Logs
log4j.rootLogger = INFO, FILE
# log4j.rootLogger = INFO,console, FILE ( To print all logging messages to both the console and a log file)

# Define the file appender(RollingFileAppender OR ConsoleAppender(to print in console))
log4j.appender.FILE=org.apache.log4j.RollingFileAppender
log4j.appender.FILE.File=${log}/SFDCTests.html

# Constrole the maximum log file size
log4j.appender.FILE.maxFileSize=10000KB

# Archive log files (one backup file here)
log4j.appender.FILE.maxBackupIndex=3

# Define the layout for file appender
(HTMLLayout OR PatternLayout)
log4j.appender.FILE.layout=org.apache.log4j.HTMLLayout
log4j.appender.FILE.layout.Title=Logger For SFDC Test Cases
log4j.appender.FILE.layout.LocationInfo=true

#do not append the old file. Create a new log file everytime
log4j.appender.FILE.Append=false
 
#Prevent internal log4j DEBUG messages from polluting the output.
#log4j.logger.org.apache.log4j.PropertyConfigurator=INFO
#log4j.logger.org.apache.log4j.config.PropertySetter=INFO
#log4j.logger.org.apache.log4j.FileAppender=INFO
 

Friday, September 4, 2015

Right Click Function With Selenium Webdriver



public void RightClickAndChooseAnOption()
    {
               
        WebElement oWE=driver.findElement(By.linkText("About Google"));
       
        Actions oAction=new Actions(driver);
        oAction.moveToElement(oWE);
        oAction.contextClick(oWE).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build().perform();
       
    }

Friday, August 28, 2015

Upload and Download file using AutoIT and Robots


 Upload with AutoIT:

Upload_File()
Func Upload_File()
   $File_Path = $cmdline[1]

 ;MsgBox(0,"Temp",$File_Path,"Temp")
   Sleep(5000)
   if WinExists("[CLASS:#32770]") Then 
   WinActivate("[CLASS:#32770]")
   ControlSetText("[CLASS:#32770]", "", "[ID:1148]", $File_Path)
   ;MsgBox(0,"Temp","Temp","Temp")
   Sleep(2000)
   ControlClick("[CLASS:#32770]", "", "[ID:1]")
   ControlClick("[CLASS:#32770]", "", "[ID:1]")
   EndIf
 EndFunc

(OR)
ControlFocus(“File Upload”,””,”Edit1″)
ControlSetText(“File Upload”,””,”Edit1″,$CmdLine[1])
ControlClick(“File Upload”,””,”Button1″)

Save the above script with '.au3' and compiling it into a standalone executable.

We can pass multiple arguments in AutoIT.
$CmdLine[0] ; Contains the total number of items in the array.
$CmdLine[1] ; The first parameter.
$CmdLine[2] ; The second parameter.
$CmdLine[nth] ; The nth parameter e.g. 10 if the array contains 10 items.


How to get the window element information:
1.Open'Au3Info.exe' file
2.Drag the finder tool on the " File Name" box element of file upload window to find the basic attributes info.
3.Get the required element info (Title, Class, Instance..)

How to compile AutoIt file '.au3' to '.exe' file:
There are multiple ways to do that. But the simple way is using Right Click option. To do that, we will follow the below steps

Step-1: Navigate to the .au3 file that you wish to compile.
Step-2: Select the file and Right-click on it to access the pop-up menu.
Step-3: You will get an option as 'Compile Script'. Click on 'Compile Script.
Step-4: You will get .exe file generated.

Run it like :
Runtime.getRuntime().exec("E:\\AutoIT\\FileUpload.exe");
(OR)
Runtime.getRuntime().exec("AutoITCompiled.exe filepath"+" "+UploadFilePath");
(OR)
Runtime.getRuntime().exec(cmd /c start "+"AutoITCompiled.exe filepath"+" "+UploadFilePath");

Download with AutoIT:

WinWaitActive("Opening", "", 60)
If WinExists("Opening") Then
   WinFlash("Opening","", 4, 500) ; Just to Flash the window
   Send("!s")
   Send("{ENTER}")
   Sleep(10000)
EndIf

Run it Like:

Runtime.getRuntime().exec("E:\\AutoIT\\FileDownload.exe");
(OR)
Runtime.getRuntime().exec("cmd /c start " + AutoIt.exeFilePath+ " ");
 
 Robots:

public void uploadFile(String absolutePath)  {
        if (absolutePath != null) {
            try {
                // StringSelection is a class that can be used for copy and
                // paste operations.
                StringSelection stringSelection = new StringSelection(absolutePath);
                Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
                 //native key strokes for CTRL, V and ENTER keys
                Robot robot = new Robot();
                robot.keyPress(KeyEvent.VK_ENTER);
                robot.keyRelease(KeyEvent.VK_ENTER);
                robot.keyPress(KeyEvent.VK_CONTROL);
                robot.keyPress(KeyEvent.VK_V);
                robot.keyRelease(KeyEvent.VK_V);
                robot.keyRelease(KeyEvent.VK_CONTROL);
                robot.delay(1000);
                robot.keyPress(KeyEvent.VK_ENTER);
                robot.keyRelease(KeyEvent.VK_ENTER);
                robot.delay(5000);
            } catch (AWTException e) {
                System.out.println("Failed to upload a file" + absolutePath + " Please try by some delay ");
            }
        } else {
            System.out.println("please provide file path");
        }
    }

USAGE of Jacob API:


Pre-requisites:
  1. Create a simple Selenium Webdriver project or add a TestNG project in Eclipse(or any IDE of any choice).
  2. Download the AutoIt software from here and install it on your system. If you are using a 64-bit system, then do select the suitable option during installation. Also, make sure you just don’t copy the AutoIt files from another system, instead, let the installer run, as it not only copies all the required files but registers them with your system. It’s helpful in the application where you use AutoIt interfaces to work with the window based dialogs.
  3. Download the AutoItX4Java jar file which is a Java API wrapper for the AutoIt functions. Use the Eclipse <Build Path->Configure> option to Add this file as an external library in your project
  4. Download the Jacob library package, it comes as a zip file. Unzip the <jacob-1.18.zip> file. You’ll the find the following files under the <jacob-1.18> folder.
  • jacob.jar.
  • jacob-1.18-x64.dll.
  • jacob-1.18-x86.dll.
Add the <jacob.jar> as an external jar into your Eclipse project while copy/paste the <jacob-1.18-x86.dll> to your project. It’ll get the DLL file added to it.
Now, time to begin out work.
Jacob will give you full control to write Java code that can manage any GUI Window.
But you need to make sure all the prerequisites are in place before you get to run the below code.

    public void UploadFileUsingJacobDll()
       throws InterruptedException {
      String workingDir = System.getProperty("user.dir");
      final String jacobdllarch = System.getProperty("sun.arch.data.model")
        .contains("32") ? "jacob-1.18-x86.dll" : "jacob-1.18-x64.dll";
      String jacobdllpath = workingDir + "\\" + jacobdllarch;
      File filejacob = new File(jacobdllpath);
      System.setProperty(LibraryLoader.JACOB_DLL_PATH,
        filejacob.getAbsolutePath());
      AutoItX uploadWindow = new AutoItX();
      driver = new FirefoxDriver();
      String filepath = workingDir + "\\SeleniumWebdriverUploadFile.html";
      driver.get(filepath);
      Thread.sleep(1000);
      driver.findElement(By.id("uploadfile")).click();
      Thread.sleep(1000);
      if (uploadWindow.winWaitActive("File Upload", "", 5)) {
       if (uploadWindow.winExists("File Upload")) {
        uploadWindow.sleep(100);
        uploadWindow.send(filepath);
        uploadWindow.controlClick("File Upload", "", "&Open");
       }
      }
     }

Wednesday, August 26, 2015

Retry executing only Failed Tests using TestNG

package com.pack.test;
import org.testng.IRetryAnalyzer;
import org.testng.ITestResult;
public class Retry implements IRetryAnalyzer {
    private int retryCount = 0;
    private int maxRetryCount = 1;
// Below method returns 'true' if the test method has to be retried else 'false'
//and it takes the 'Result' as parameter of the test method that just ran
    public boolean retry(ITestResult result) {
        if (retryCount < maxRetryCount) {
            System.out.println("Retrying test " + result.getName() + " with status "
                    + getResultStatusName(result.getStatus()) + " for the " + (retryCount+1) + " time(s).");
            retryCount++;
            return true;
        }
        return false;
    }
   
    public String getResultStatusName(int status) {
     String resultName = null;
     if(status==1)
      resultName = "SUCCESS";
     if(status==2)
      resultName = "FAILURE";
     if(status==3)
      resultName = "SKIP";
  return resultName;
    }
}

package com.pack.test;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import org.testng.IAnnotationTransformer;
import org.testng.IRetryAnalyzer;
import org.testng.annotations.ITestAnnotation;
public class RetryListener implements IAnnotationTransformer {
 @Override
 public void transform(ITestAnnotation testannotation, Class testClass,
   Constructor testConstructor, Method testMethod) {
  IRetryAnalyzer retry = testannotation.getRetryAnalyzer();
  if (retry == null) {
   testannotation.setRetryAnalyzer(Retry.class);
  }
 }
}


       
 

Tuesday, August 18, 2015

Separate ReportNG Report Table to send through mail


String filePath = System.getProperty("user.dir")
     + "\\test-output\\html\\overview.html";
   Document document = Jsoup.parse(new File(filePath), "UTF-8");
   Elements tableContentElement = document
     .select("table[class=overviewTable]");
   String tableHtml = tableContentElement.html();
   String[] msgBody = new String[] { config.getProperty("emailBody"),
     tableHtml, config.getProperty("emailSignature") };

Tuesday, August 11, 2015

How to add screenshot in ReportNG HTML report


public void catchExceptions(ITestResult result) {
    System.out.println("result" + result);
    String methodName = result.getName();
    System.out.println(methodName);
    if (!result.isSuccess()) {
        try {
        String failureImageFileName =  new SimpleDateFormat("MM-dd-yyyy_HH-ss").format(new GregorianCalendar().getTime())+ ".png";
        File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(scrFile, new File(failureImageFileName));

// To add screenshot to ReportNG HTML report as a link
  private static final String ESCAPE_PROPERTY = "org.uncommons.reportng.escape-output";
            System.setProperty(ESCAPE_PROPERTY, "false");
   Reporter.setCurrentTestResult(result);
   Reporter.log("failureImageFileName+ "\"> Screenshot
");
(OR)
// To add screenshot to ReportNG HTML report as a image
private static final String ESCAPE_PROPERTY = "org.uncommons.reportng.escape-output";
            System.setProperty(ESCAPE_PROPERTY, "false");
Reporter.log("" +"");


        } catch (IOException e1) {
            e1.printStackTrace();
        }
}
}

Wednesday, May 13, 2015

How to Run TestNG xml Programmatically

public static void main(String[] args) {
  TestNG testng = null;
  List suites = null;
  try {
   testing = new TestNG();
   suites = Lists.newArrayList();
         suites.add("D:/Projects/SeleniumTests/testng1.xml");//path to xml..
         suites.add("D:/Projects/SeleniumTests/testng2.xml");//If need to execute more xml files
   testng.setTestSuites(suites);
   testing.run();
  } catch (Exception e) {
   e.printStackTrace();
  }
}


Using Bat File:
D:
cd Projects\SeleniumTests
set MyProjectPath=D:\Projects\SeleniumTests
echo %MyProjectPath%
set classpath=%MyProjectPath%\bin;%MyProjectPath%\lib\*
echo %classpath%
java org.testng.TestNG %MyProjectPath%\testng.xml

Friday, February 13, 2015

Exceptions that may happen in all the webdriver code

Exceptions that may happen in all the webdriver code.
exception selenium.common.exceptions.ElementNotSelectableException(msg=None, screen=None, stacktrace=None)
exception selenium.common.exceptions.ElementNotVisibleException(msg=None, screen=None, stacktrace=None)
Thrown to indicate that although an element is present on the DOM, it is not visible, and so is not able to be interacted with.
exception selenium.common.exceptions.ErrorInResponseException(response, msg)
An error has occurred on the server side.
This may happen when communicating with the firefox extension or the remote driver server.
exception selenium.common.exceptions.ImeActivationFailedException(msg=None, screen=None, stacktrace=None)
Indicates that activating an IME engine has failed.
exception selenium.common.exceptions.ImeNotAvailableException(msg=None, screen=None, stacktrace=None)
Indicates that IME support is not available. This exception is thrown for every IME-related method call if IME support is not available on the machine.
exception selenium.common.exceptions.InvalidCookieDomainException(msg=None, screen=None, stacktrace=None)
Thrown when attempting to add a cookie under a different domain than the current URL.
exception selenium.common.exceptions.InvalidElementStateException(msg=None, screen=None, stacktrace=None)
exception selenium.common.exceptions.InvalidSelectorException(msg=None, screen=None, stacktrace=None)
Thrown when the selector which is used to find an element does not return a WebElement. Currently this only happens when the selector is an xpath expression is used which is either syntactically invalid (i.e. it is not a xpath expression) or the expression does not select WebElements (e.g. “count(//input)”).
exception selenium.common.exceptions.InvalidSwitchToTargetException(msg=None, screen=None, stacktrace=None)
The frame or window target to be switched doesn’t exist.
exception selenium.common.exceptions.MoveTargetOutOfBoundsException(msg=None, screen=None, stacktrace=None)
Indicates that the target provided to the actions move() method is invalid
exception selenium.common.exceptions.NoAlertPresentException(msg=None, screen=None, stacktrace=None)
exception selenium.common.exceptions.NoSuchAttributeException(msg=None, screen=None, stacktrace=None)
find_element_by_* can’t find the element.
exception selenium.common.exceptions.NoSuchElementException(msg=None, screen=None, stacktrace=None)
find_element_by_* can’t find the element.
exception selenium.common.exceptions.NoSuchFrameException(msg=None, screen=None, stacktrace=None)
exception selenium.common.exceptions.NoSuchWindowException(msg=None, screen=None, stacktrace=None)
exception selenium.common.exceptions.RemoteDriverServerException(msg=None, screen=None, stacktrace=None)
exception selenium.common.exceptions.StaleElementReferenceException(msg=None, screen=None, stacktrace=None)
Indicates that a reference to an element is now “stale” — the element no longer appears on the DOM of the page.
exception selenium.common.exceptions.TimeoutException(msg=None, screen=None, stacktrace=None)
Thrown when a command does not complete in enough time.
exception selenium.common.exceptions.UnableToSetCookieException(msg=None, screen=None, stacktrace=None)
Thrown when a driver fails to set a cookie.
exception selenium.common.exceptions.UnexpectedTagNameException(msg=None, screen=None, stacktrace=None)
Thrown when a support class did not get an expected web element
exception selenium.common.exceptions.WebDriverException(msg=None, screen=None, stacktrace=None)

Thursday, January 29, 2015

XLS Reading for DDF

package com.stta.utility;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;



public class Read_XLS {   
    public  String filelocation;
    public  FileInputStream ipstr = null;
    public  FileOutputStream opstr =null;
    private HSSFWorkbook wb = null;
    private HSSFSheet ws = null;   
   
    public Read_XLS(String filelocation) {       
        this.filelocation=filelocation;
        try {
            ipstr = new FileInputStream(filelocation);
            wb = new HSSFWorkbook(ipstr);
            ws = wb.getSheetAt(0);
            ipstr.close();
        } catch (Exception e) {           
            e.printStackTrace();
        }
       
    }
   
    //To retrieve No Of Rows from .xls file's sheets.
    public int retrieveNoOfRows(String wsName){       
        int sheetIndex=wb.getSheetIndex(wsName);
        if(sheetIndex==-1)
            return 0;
        else{
            ws = wb.getSheetAt(sheetIndex);
            int rowCount=ws.getLastRowNum()+1;       
            return rowCount;       
        }
    }
   
    //To retrieve No Of Columns from .xls file's sheets.
    public int retrieveNoOfCols(String wsName){
        int sheetIndex=wb.getSheetIndex(wsName);
        if(sheetIndex==-1)
            return 0;
        else{
            ws = wb.getSheetAt(sheetIndex);
            int colCount=ws.getRow(0).getLastCellNum();           
            return colCount;
        }
    }
   
    //To retrieve SuiteToRun and CaseToRun flag of test suite and test case.
    public String retrieveToRunFlag(String wsName, String colName, String rowName){
       
        int sheetIndex=wb.getSheetIndex(wsName);
        if(sheetIndex==-1)
            return null;
        else{
            int rowNum = retrieveNoOfRows(wsName);
            int colNum = retrieveNoOfCols(wsName);
            int colNumber=-1;
            int rowNumber=-1;           
           
            HSSFRow Suiterow = ws.getRow(0);               
           
            for(int i=0; i                if(Suiterow.getCell(i).getStringCellValue().equals(colName.trim())){
                    colNumber=i;                   
                }                   
            }
           
            if(colNumber==-1){
                return "";               
            }
           
           
            for(int j=0; j                HSSFRow Suitecol = ws.getRow(j);               
                if(Suitecol.getCell(0).getStringCellValue().equals(rowName.trim())){
                    rowNumber=j;   
                }                   
            }
           
            if(rowNumber==-1){
                return "";               
            }
           
            HSSFRow row = ws.getRow(rowNumber);
            HSSFCell cell = row.getCell(colNumber);
            if(cell==null){
                return "";
            }
            String value = cellToString(cell);
            return value;           
        }           
    }
   
    //To retrieve DataToRun flag of test data.
    public String[] retrieveToRunFlagTestData(String wsName, String colName){
       
        int sheetIndex=wb.getSheetIndex(wsName);
        if(sheetIndex==-1)
            return null;
        else{
            int rowNum = retrieveNoOfRows(wsName);
            int colNum = retrieveNoOfCols(wsName);
            int colNumber=-1;
                   
           
            HSSFRow Suiterow = ws.getRow(0);               
            String data[] = new String[rowNum-1];
            for(int i=0; i                if(Suiterow.getCell(i).getStringCellValue().equals(colName.trim())){
                    colNumber=i;                   
                }                   
            }
           
            if(colNumber==-1){
                return null;               
            }
           
            for(int j=0; j                HSSFRow Row = ws.getRow(j+1);
                if(Row==null){
                    data[j] = "";
                }
                else{
                    HSSFCell cell = Row.getCell(colNumber);
                    if(cell==null){
                        data[j] = "";
                    }
                    else{
                        String value = cellToString(cell);
                        data[j] = value;   
                    }   
                }
            }
           
            return data;           
        }           
    }
   
    //To retrieve test data from test case data sheets.
    public Object[][] retrieveTestData(String wsName){
        int sheetIndex=wb.getSheetIndex(wsName);
        if(sheetIndex==-1)
            return null;
        else{
                int rowNum = retrieveNoOfRows(wsName);
                int colNum = retrieveNoOfCols(wsName);
       
                Object data[][] = new Object[rowNum-1][colNum-2];
       
                for (int i=0; i                    HSSFRow row = ws.getRow(i+1);
                    for(int j=0; j< colNum-2; j++){                   
                        if(row==null){
                            data[i][j] = "";
                        }
                        else{
                            HSSFCell cell = row.getCell(j);   
                   
                            if(cell==null){
                                data[i][j] = "";                           
                            }
                            else{
                                cell.setCellType(Cell.CELL_TYPE_STRING);
                                String value = cellToString(cell);
                                data[i][j] = value;                       
                            }
                        }
                    }               
                }           
                return data;       
        }
   
    }       
   
   
    public static String cellToString(HSSFCell cell){
        int type;
        Object result;
        type = cell.getCellType();           
        switch (type){
            case 0 :
                result = cell.getNumericCellValue();
                break;
               
            case 1 :
                result = cell.getStringCellValue();
                break;
               
            default :
                throw new RuntimeException("Unsupportd cell.");           
        }
        return result.toString();
    }
   
    //To write result In test data and test case list sheet.
    public boolean writeResult(String wsName, String colName, int rowNumber, String Result){
        try{
            int sheetIndex=wb.getSheetIndex(wsName);
            if(sheetIndex==-1)
                return false;           
            int colNum = retrieveNoOfCols(wsName);
            int colNumber=-1;
                   
           
            HSSFRow Suiterow = ws.getRow(0);           
            for(int i=0; i                if(Suiterow.getCell(i).getStringCellValue().equals(colName.trim())){
                    colNumber=i;                   
                }                   
            }
           
            if(colNumber==-1){
                return false;               
            }
           
            HSSFRow Row = ws.getRow(rowNumber);
            HSSFCell cell = Row.getCell(colNumber);
            if (cell == null)
                cell = Row.createCell(colNumber);           
           
            cell.setCellValue(Result);
           
            opstr = new FileOutputStream(filelocation);
            wb.write(opstr);
            opstr.close();
           
           
        }catch(Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }
   
    //To write result In test suite list sheet.
    public boolean writeResult(String wsName, String colName, String rowName, String Result){
        try{
            int rowNum = retrieveNoOfRows(wsName);
            int rowNumber=-1;
            int sheetIndex=wb.getSheetIndex(wsName);
            if(sheetIndex==-1)
                return false;           
            int colNum = retrieveNoOfCols(wsName);
            int colNumber=-1;
                   
           
            HSSFRow Suiterow = ws.getRow(0);           
            for(int i=0; i                if(Suiterow.getCell(i).getStringCellValue().equals(colName.trim())){
                    colNumber=i;                   
                }                   
            }
           
            if(colNumber==-1){
                return false;               
            }
           
            for (int i=0; i                HSSFRow row = ws.getRow(i+1);               
                HSSFCell cell = row.getCell(0);   
                cell.setCellType(Cell.CELL_TYPE_STRING);
                String value = cellToString(cell);   
                if(value.equals(rowName)){
                    rowNumber=i+1;
                    break;
                }
            }       
           
            HSSFRow Row = ws.getRow(rowNumber);
            HSSFCell cell = Row.getCell(colNumber);
            if (cell == null)
                cell = Row.createCell(colNumber);           
           
            cell.setCellValue(Result);
           
            opstr = new FileOutputStream(filelocation);
            wb.write(opstr);
            opstr.close();
           
           
        }catch(Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }
}