Tuesday, 9 August 2016

How to switch window using Selenium


Selenium provides the function windowhandle for the driver. this functions can be used to find out all the available windows in a driver and then can be switched if it is different from the previously opened window.

Below is the logic which i have used:

String a = driver.getWindowHandle();

Set<String> b = driver.getWindowHandles();

if(b.size() > 1){
for(String windowHandle  : b)
       {
if(windowHandle.equals(a))
{
       //Do Nothing
}
else
{
driver.switchTo().window(windowHandle);
}

       }

Monday, 29 February 2016

How to create and update a word document in Java

Below code snippets will help you to create a new word document and update an existing word document. We are using apache poi libraries to access word documents.

Below code will create a word document of name FileName.
                 //Blank Document
                   XWPFDocument document= new XWPFDocument();
                //Write the Document in file system
                   FileOutputStream out = new FileOutputStream(new File(FileName));
                   document.write(out);
                   out.close();

Below code will update a word document of name FileName and will insert a local image.

                   XWPFDocument document = new XWPFDocument(new FileInputStream(FileName));
  XWPFParagraph a = document.createParagraph();
  XWPFRun run=a.createRun();
  run.setText(ImageText);
 
  String imgFile = ImagePath;
  FileInputStream is = new FileInputStream(imgFile);
  run.addBreak();
  run.addPicture(is, XWPFDocument.PICTURE_TYPE_JPEG, imgFile,                                                  Units.toEMU(500), Units.toEMU(300));
  FileOutputStream out = new FileOutputStream(new File(FileName));
  document.write(out);
  out.close();


Please let me know if you face any issues while using the above code.

Tuesday, 19 January 2016

How to read Excel file using java for Selenium

To read an excel file using java we need to download 4 jar files which will help to read excel files. So whenever you are starting to read the file below is the list of jar files to be used:

1. dom4j<latest ver>.jar
2. poi<latest ver>.jar
3. poi ooxml <latest ver>.jar
4. poi ooxml shcemas <latest ver>.jar

As soon as you configure these jar files in your build path, below code can be used which can extract data from excel files:

        FileInputStream ExcelFile = new FileInputStream("<File Name>.xlsx");
        XSSFWorkbook ExcelWBook = new XSSFWorkbook(ExcelFile);
  XSSFSheet ExcelWSheet = ExcelWBook.getSheet(SheetName);
      XSSFCell Cell = ExcelWSheet.getRow(rownum).getCell(column);
        String Celldata = Cell.getStringCellValue();

XSSF is used for .xlsx files and HSSF is used for .xls files.