Friday, March 14, 2014

Writing Excel Using Apache POI

Writing excel is another important thing to do,here we learn how to write xls and xlsx file using apache POI.

In Apache POI also have some problem when we write large excel file....we know later how to overcome this situation.

In below code we combined the write .xls and .xlsx file according to the file extention.Below code is self descriptive so we no need to more now to deep down to the code.



import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;



public class WriteExcel {

    public static void main(String args[]) {
        try {


            //Sample data to fill the sheet.
          
            Map<Integer, Object[]> data = new HashMap<>();
            data.put(1, new Object[]{"Emp No.", "Name", "Salary"});
            data.put(2, new Object[]{1d, "Ram", 25000d});
            data.put(3, new Object[]{2d, "Sam", 50000d});
            data.put(4, new Object[]{3d, "Rahim", 70000d});


            //Give the File name with file extention

            File fileToWrite = new File("resources/new.xlsx");
            String fileToWritename = fileToWrite.getName();
            String extension = fileToWritename.substring(fileToWritename.lastIndexOf(".")
                    + 1, fileToWritename.length());
           
            if (extension.equalsIgnoreCase("xls")) {
                Workbook workbook = new HSSFWorkbook();
                Sheet sheet = workbook.createSheet("Sample sheet");
                insertToSheet(data, sheet);
                writeToExcel(workbook, fileToWrite);
            } else if (extension.equalsIgnoreCase("xlsx")) {
                Workbook workbook = new XSSFWorkbook();
                Sheet sheet = workbook.createSheet("Sample sheet");
                insertToSheet(data, sheet);
                writeToExcel(workbook, fileToWrite);
            }

        } catch (Exception e) {
            e.getMessage();
        }

    }

    public static void insertToSheet(Map<Integer, Object[]> data, Sheet sheet) {
        int rownum = 0;
        for (Integer key : data.keySet()) {
            Row row = sheet.createRow(rownum++);
            Object[] objArr = data.get(key);
            int cellnum = 0;
            for (Object obj : objArr) {
                Cell cell = row.createCell(cellnum++);
                if (obj instanceof Date) {
                    cell.setCellValue((Date) obj);
                } else if (obj instanceof Boolean) {
                    cell.setCellValue((Boolean) obj);
                } else if (obj instanceof String) {
                    cell.setCellValue((String) obj);
                } else if (obj instanceof Double) {
                    cell.setCellValue((Double) obj);
                } else {
                    System.out.println("error");
                }
            }
        }
    }

    public static void writeToExcel(Workbook workbook, File fileToWrite) {
        try {
            FileOutputStream out
                    = new FileOutputStream(fileToWrite);
            workbook.write(out);
            out.close();
            System.out.println("Excel written successfully..");
           
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Friday, March 7, 2014

Excel Reading using JExcel API

There are so many way to read excel using java.Here we know another good JAVA API to read excel that is JExcel. This API handle .xls(Excel 97) file only it can not handle .xlsx(Excel 2007) file.

Now question is how to use this API to read excel file.

First of all we need to download this API.So we can go to this link and download the latest version(jexcelapi_2_6_12) and extract it.

After extracting , it looks like that










Create a new project from our IDE and add jxl.jar in our project.





Now we write the code as given below:

import java.io.File;
import java.io.IOException;
import jxl.Cell;
import jxl.CellType;
import jxl.Sheet;
import jxl.Workbook;
import jxl.WorkbookSettings;

public class ExcelReadJxl {


    public static void main(String[] args) throws IOException, Exception {
        WorkbookSettings workbookSettings = new WorkbookSettings();
        File file = new File("resources/Test1.xls");
        //set the file location for the .xls file 
        Workbook workbook = Workbook.getWorkbook(file, workbookSettings);
        //create workbook object by the settings

        //getting the first sheet inside excel document       
        Sheet customerSheet = workbook.getSheet(0);
        //start reading Excel document        
       ExcelReadJxl.readSheet(customerSheet);
      
// free the memory by closing workbook
       workbook.close();
    }

    private static void readSheet(Sheet sheet) throws Exception {


        //sheet.getCell(columnIndex,rowIndex)
        //getting all rows inside excel document

        for (int i = 0; i < sheet.getRows(); i++) {
        //start looping over rows
            for (int j = 0; j < sheet.getColumns(); j++) {
                Cell cell = sheet.getCell(j, i);
                CellType type = cell.getType();
                if (type == CellType.LABEL) {
                    System.out.printf(sheet.getCell(j, i).getContents() + "\t");
                } else if (type == CellType.NUMBER) {
                    System.out.printf(sheet.getCell(j, i).getContents() + "\t");
                }
            }
            System.out.printf("\n");
        }
    }
}





Thursday, March 6, 2014

Read Excel With Apache POI Event Model


On our previous post we know that Apache POI have 2 types of model
  • User Model
  • Event Model
On previous post we learn how to read Excel (.xls and .xlsx file) using Apache POI with User Model.
Now we try to learn how to read .xls and .xlsx file using Event Model.

Q.Why Event Model from Apache POI ?
Ans: Though User Model is easy to use from coding part and mostly used from everywhere, but it is not efficient when Excel file is very large maximum time user got error like "Out Of Memory Exception", for this reason we need to know how to manage large excel file using Apache POI Event Model.


Here we need to add this .jar with our projects
                 
1. poi-3.10-FINAL-20140208.jar if we try to read only .xls file then it is enough but if we try to read .xlsx file then we need to add this .jar as given below.
2.poi-ooxml-3.10-FINAL-20140208.jar
3.poi-ooxml-schemas-3.10-FINAL-20140208.jar
4.xmlbeans-2.3.0.jar
5.dom4j-1.6.1.jar

Code For Reading .xls File 



import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import org.apache.poi.hssf.eventusermodel.HSSFEventFactory;
import org.apache.poi.hssf.eventusermodel.HSSFListener;
import org.apache.poi.hssf.eventusermodel.HSSFRequest;
import org.apache.poi.hssf.record.BOFRecord;
import org.apache.poi.hssf.record.BoundSheetRecord;
import org.apache.poi.hssf.record.LabelSSTRecord;
import org.apache.poi.hssf.record.NumberRecord;
import org.apache.poi.hssf.record.Record;
import org.apache.poi.hssf.record.RowRecord;
import org.apache.poi.hssf.record.SSTRecord;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

public class EventModelXls
        implements HSSFListener {

    private SSTRecord sstrec;

   //Give the SheetName which we want to read
    String mySheetName="Sheet2";
    ArrayList allSheetName =new ArrayList();
    int j=0;

    /**
     * This method listens for incoming records and handles them as required.
     *
     * @param record The record that was found while reading.
     */
    @Override
    public void processRecord(Record record) {

        switch (record.getSid()) {
            // the BOFRecord can represent either the beginning of a sheet or the workbook
            case BOFRecord.sid:
                BOFRecord bof = (BOFRecord) record;
                if (bof.getType() == bof.TYPE_WORKBOOK) {
                    System.out.println("Encountered workbook");
                    // assigned to the class level member
                } else if (bof.getType() == bof.TYPE_WORKSHEET) {
                    System.out.println("Encountered sheet reference" +"SheetName ="+allSheetName.get(j));
                    j++;
                }
                break;
            case BoundSheetRecord.sid:
                BoundSheetRecord bsr = (BoundSheetRecord) record;
                System.out.println("New sheet named: " + bsr.getSheetname());
                allSheetName.add(bsr.getSheetname());
                break;
            case RowRecord.sid:
                RowRecord rowrec = (RowRecord) record;
                System.out.println("Row found, first column at "
                        + rowrec.getFirstCol() + " last column at " + rowrec.getLastCol());
                break;
            case NumberRecord.sid:
               
             if(mySheetName.equalsIgnoreCase(allSheetName.get(j-1).toString())){
                NumberRecord numrec = (NumberRecord) record;
                System.out.println("Cell found with value" + numrec.getValue()
                        + " at row " + numrec.getRow() + " and column " + numrec.getColumn());
             }
                break;
            // SSTRecords store a array of unique strings used in Excel.
            case SSTRecord.sid:
                sstrec = (SSTRecord) record;
                for (int k = 0; k < sstrec.getNumUniqueStrings(); k++) {
                    System.out.println("String table value " + k + " = " + sstrec.getString(k) +sstrec.getNumStrings());
                }
                break;
            case LabelSSTRecord.sid:
               
                if(mySheetName.equalsIgnoreCase(allSheetName.get(j-1).toString())){
                LabelSSTRecord lrec = (LabelSSTRecord) record;
                System.out.println("String cell found with value "
                        + sstrec.getString(lrec.getSSTIndex())+ " at row " + lrec.getRow() + " and column " + lrec.getColumn());
               
                }break;
        }
    }



    /**
     * Read an excel file and spit out what we find.
     *
     * @param args Expect one argument that is the file to read.
     * @throws IOException When there is an error processing the file.
     */
    public static void main(String[] args) throws IOException {
        // create a new file input stream with the input file specified
        // at the command line

        FileInputStream fin = new FileInputStream(new File("resources/Test1.xls"));
        // create a new org.apache.poi.poifs.filesystem.Filesystem
        POIFSFileSystem poifs = new POIFSFileSystem(fin);
        // get the Workbook (excel part) stream in a InputStream
        InputStream din = poifs.createDocumentInputStream("Workbook");
        // construct out HSSFRequest object
        HSSFRequest req = new HSSFRequest();
        // lazy listen for ALL records with the listener shown above
        req.addListenerForAllRecords(new EventModelXls());
        // create our event factory
        HSSFEventFactory factory = new HSSFEventFactory();
        // process our events based on the document input stream
        factory.processEvents(req, din);
        // once all the events are processed close our file input stream
        fin.close();
        // and our document input stream (don't want to leak these!)
        din.close();
        System.out.println("done.");
    }

}


 Code For Reading .xlsx File 


import java.io.InputStream;
import java.util.Iterator;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.model.SharedStringsTable;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;


public class XlsxEventModel {

    public void processOneSheet(String filename) throws Exception {
        OPCPackage pkg = OPCPackage.open(filename);
        XSSFReader r = new XSSFReader(pkg);
        SharedStringsTable sst = r.getSharedStringsTable();

        XMLReader parser = fetchSheetParser(sst);


        /********************************
          *rId2 found by processing the Workbook
          * Seems to either be rId# or rSheet#

        */
        InputStream sheet2 = r.getSheet("rId2");
        InputSource sheetSource = new InputSource(sheet2);
        parser.parse(sheetSource);
        sheet2.close();

    }

    public void processAllSheets(String filename) throws Exception {
        OPCPackage pkg = OPCPackage.open(filename);
        XSSFReader r = new XSSFReader(pkg);
        SharedStringsTable sst = r.getSharedStringsTable();
        XMLReader parser = fetchSheetParser(sst);
        XSSFReader.SheetIterator sheets = (XSSFReader.SheetIterator) r.getSheetsData();
        // Iterator<InputStream> sheets = r.getSheetsData();

        while (sheets.hasNext()) {
            System.out.println("Processing new sheet:\n");
            InputStream sheet = sheets.next();
            System.out.println("SheetName" + sheets.getSheetName());
            InputSource sheetSource = new InputSource(sheet);
            parser.parse(sheetSource);
            sheet.close();
            System.out.println("");
        }
    }


    public XMLReader fetchSheetParser(SharedStringsTable sst) throws SAXException {
        /****************************************
         * This Part is commented out because This is required
         * SAX 2(Apache SAX perser) parser and need xerces-2.8.0.jar
         * If xerces-2.8.0.jar is available then commented out
         * another SAX(JRE default) parser part and uncomment this.

         *
         *
         * XMLReader parser =
         *        XMLReaderFactory.createXMLReader(
         *          "org.apache.xerces.parsers.SAXParser");
         *
         */

        XMLReader parser =
                XMLReaderFactory.createXMLReader(
                "com.sun.org.apache.xerces.internal.parsers.SAXParser");
        ContentHandler handler = new SheetHandler(sst);
        parser.setContentHandler(handler);
        return parser;
    }


    /**
     * See org.xml.sax.helpers.DefaultHandler javadocs
     */

    private static class SheetHandler extends DefaultHandler {

        private SharedStringsTable sst;
        private String lastContents;
        private boolean nextIsString;

        private SheetHandler(SharedStringsTable sst) {
            this.sst = sst;
        }

        @Override
        public void startElement(String uri, String localName, String name,
                Attributes attributes) throws SAXException {

            // c => cell
            if (name.equals("c")) {
                // Print the cell reference
                System.out.print(attributes.getValue("r") + " - ");

            // Figure out if the value is an index in the SST
                String cellType = attributes.getValue("t");
                if (cellType != null && cellType.equals("s")) {
                    nextIsString = true;
                } else {
                    nextIsString = false;
                }
            }

            // Clear contents cache
            lastContents = "";
        }

        @Override
        public void endElement(String uri, String localName, String name)
                throws SAXException {

            // Process the last contents as required.
            // Do now, as characters() may be called more than once

            if (nextIsString) {
                int idx = Integer.parseInt(lastContents);
                lastContents = new XSSFRichTextString(sst.getEntryAt(idx)).toString();
                nextIsString = false;
            }

            // v => contents of a cell
            // Output after we've seen the string contents

            if (name.equals("v")) {
                System.out.println(lastContents);
            }
        }


        @Override
        public void characters(char[] ch, int start, int length)
                throws SAXException {
            lastContents += new String(ch, start, length);
        }
    }


    public static void main(String[] args) throws Exception {
        XlsxEventModel howto = new XlsxEventModel();
        howto.processAllSheets(("resources/Test1.xlsx"));
    }
}


Wednesday, March 5, 2014

Read Excel With Apache POI UserModel


If we try to make a framework we need to read and write a file,it may be excel may be xml or may be CSV or even it may be a text file.Here we try to read and write excel using Apache POI.

Q.What is Apache POI ?

Ans:-  Apache POI(Poor Obfuscation Implementation) is a open source API   to read .xls(Excel 97) and .xlsx(Excel 2007) using java.

Q.What type of model should I use to read or write excel file using Apache POI ?

Ans:- Basically Apache POI have  two types of model
  1. UserModel: It can read and write file but need more memory and reading speed is not like EventModel. 
  2. EventModel: It can only read file with better reading speed but hard to implement and it need less memory .
 So we can draw a conclusion that if we have less time and small file we use UserModel to read and write if we have a big size of excel for only read  and have some time to code then choose EventModel.

Q.How to implement UserModel ?
Ans:-
  • At first we need to download Apache POI API. We can download(Apache POI 3.10) this from here.
  • We extract the files from downloaded compressed folder . It looks like below.


 







  •  Open our IDE and create a project to read excel.
  • Here we will read .xls and .xlsx file So we need to import jar from Apache POI which we extracted previously to read both type of file.
  • We need to add this .jar with our projects
                1. poi-3.10-FINAL-20140208.jar if we try to read only .xls file then it is enough but if we try to read .xlsx file also then we need to add this .jar as given below.
                2.poi-ooxml-3.10-FINAL-20140208.jar
                3.poi-ooxml-schemas-3.10-FINAL-20140208.jar
                4.xmlbeans-2.3.0.jar
                5.dom4j-1.6.1.jar
  • Finally it should be shown like that












Total code is given below


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
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.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelFileReadApachePOI {

    /**
     * @param Excel2003FileToRead
     * @throws java.io.IOException
     */
    public static void readXLSFile(FileInputStream Excel2003FileToRead) throws IOException {
        HSSFWorkbook wb = new HSSFWorkbook(Excel2003FileToRead);
        HSSFSheet sheet = wb.getSheetAt(0);
        HSSFRow row;
        HSSFCell cell;
        Iterator rows = sheet.rowIterator();
        while (rows.hasNext()) {
            row = (HSSFRow) rows.next();
            Iterator cells = row.cellIterator();
            while (cells.hasNext()) {
                cell = (HSSFCell) cells.next();
                if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                    System.out.print(cell.getStringCellValue() + " ");
                } else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                    System.out.print(cell.getNumericCellValue() + " ");
                } else {
                    //U Can Handel Boolean, Formula, Errors
                }
            }
            System.out.println();
        }
    }

    public static void readXLSXFile(FileInputStream Excel2007FileToRead) throws IOException{
        XSSFWorkbook xwb = new XSSFWorkbook(Excel2007FileToRead);
        XSSFSheet xsheet = xwb.getSheetAt(0);
        XSSFRow xrow;
        XSSFCell xcell;
        Iterator xrows = xsheet.rowIterator();
        while (xrows.hasNext()) {
            xrow = (XSSFRow) xrows.next();
            Iterator xcells = xrow.cellIterator();
            while (xcells.hasNext()) {
                xcell = (XSSFCell) xcells.next();
                if (xcell.getCellType() == XSSFCell.CELL_TYPE_STRING) {
                    System.out.print(xcell.getStringCellValue() + " ");
                } else if (xcell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {
                    System.out.print(xcell.getNumericCellValue() + " ");
                } else {
                    //U Can Handel Boolean, Formula, Errors
                }
            }
            System.out.println("");
        }
    }

    public static void main(String[] args) {
        try {
            File fileToRead = new File("resources/Test.xlsx");
            String fileToReadname = fileToRead.getName();
            String extension = fileToReadname.substring(fileToReadname.lastIndexOf(".")
                    + 1, fileToReadname.length());
            String excel2003 = "xls";
            String excel2007 = "xlsx";
            if (excel2003.equalsIgnoreCase(extension)) {
                FileInputStream Excel2003FileToRead = new FileInputStream(fileToRead);
                readXLSFile(Excel2003FileToRead);
            } else if (excel2007.equalsIgnoreCase(extension)) {
                FileInputStream Excel2007FileToRead = new FileInputStream(fileToRead);
                readXLSXFile(Excel2007FileToRead);
            }
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        }
    }
}







Tuesday, January 21, 2014

Sikuli API with Selenium WebDriver


Some time we need to integrate different API with Selenium WebDriver  to automate our application.

Here we learn how to integrate Sikuli with Selenium Web Driver.Now question should arise

1.What is sikuli?

Ans:-It is an image based GUI Automation tool.

2.How to integrate Sikuli with Selenium Webdriver?

Ans:-There is 2 way to integrate sikuli with selenium webdriver

i. Install Sikuli and add this jar(which is on installation path) into our selenium webdriver project.
ii. Another way is add sikuli-api-1.0.2-standalone.jar from  Sikuli Java API download page.

We start with second one we may learn first one later.

Step1:

First of all we download sikuli-api-1.0.2-standalone.jar.

Step2:

Add this jar into our Selenium WebDriver project.

Step3:

We know that Sikuli is image based automation tool.So Sikuli understand only picture so on which element we want to click need to save as picture.

Step4:

Now we write the code as given below to automate the Google Search page. Here we type "abcd" on search box and click on search button then we click the link using sikuli.Here one thing should be considered that we should taken the screen shot of the link previously and screenshot text should be present on search.



    public static void main(String args[]) throws IOException {
        WebDriver driver = new FirefoxDriver();
        driver.get("https://www.google.com");
        driver.findElement(By.name("q")).sendKeys("abcd");
        driver.findElement(By.id("gbqfb")).click();
        WebDriverWait wait = new WebDriverWait(driver, 10);
        wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@id='rso']/li[1]/div/h3/a")));

        /*
         * We Define the Screen region
         * as Desktop Screen region.
         */

        ScreenRegion s = new DesktopScreenRegion();
        /*
         * We need to capture the Image
         * and save this as png file extention
         */

        ImageIO.write(s.capture(), "png", new File("E:\\Sikuli\\saved.png"));
        driver.manage().window().maximize();

        /*
         * We need to load the picture
         * on which we click for automation
         */

        Target tg=new ImageTarget(new File("E:\\Sikuli\\1.png"));
         /*
         * Again we Define the Screen region
         * as Desktop Screen region because we
         * maximize the screen.
         */

        ScreenRegion sr=new DesktopScreenRegion();
        /*
         * Initialize the mouse to click on element
         */

        Mouse mouse=new DesktopMouse();
        mouse.click(sr.wait(tg, 5000).getCenter());

    } 
 

Monday, January 13, 2014

Log4j Settings With Selenium WebDriver


Here we learn how to use and configure Log4j for Selenium Web Driver.

Log4j have 3 part
  1. Logger
  2. Appender
  3. Layout or Formatter
1.Logger
 
      This is basically logging the application status.It have 6 level

      a.TRACE
      b.DEBUG
      c.INFO
      d.WARN
      e.ERROR
      f.FATAL

and order of this level is DEBUG < INFO < WARN < ERROR < FATAL means if we set logger as WARN then we get ERROR and FATAL log also.

We set this in properties file like

 # Log levels
log4j.rootLogger=INFO,CONSOLE,R,HTML,TTCC


Here we set INFO as a level for logging.Console,R and HTML are appender we learn later about this.This names are arbitrary.

2.Appender 
    
    This means where it writes log.It may write log in console,text file etc.


We set this in properties file like

# Appender Configuration
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender


# Rolling File Appender
log4j.appender.R=org.apache.log4j.RollingFileAppender

log4j.appender.TTCC=org.apache.log4j.RollingFileAppender
# Path and file name to store the log file
log4j.appender.R.File=./logs/testlog.log

log4j.appender.TTCC.File=./logs/testlog1.log   
# Define the HTML file appender
log4j.appender.HTML=org.apache.log4j.FileAppender
# Path and file name to store the log file
log4j.appender.HTML.File=./logs/application.html


3.Layout or Formatter

   It's name clearly defines what it is.It is use to format the output file.This is used how we want to see the output it may be on Console,Text or even HTML.

We set this in properties file like

This is for console layout:

# Pattern to output the caller's file name and line number
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n



This is for text file layout:

# Layout for Rolling File Appender
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d - %c - %p - %m%n

log4j.appender.TTCC.layout=org.apache.log4j.TTCCLayout
log4j.appender.TTCC.layout.DateFormat=ISO8601


This is for HTML layout:

# Define the html layout for file appender
log4j.appender.HTML.layout=org.apache.log4j.HTMLLayout
#Define Title of the HTML page
log4j.appender.HTML.layout.Title=Application logs
#Define the log location of application class file
log4j.appender.HTML.layout.LocationInfo=true


How to Configure Log4j:

Step 1:
      Add a properties file in our project.


Step 2:
     Configure file Should be looks like
# Log levels
log4j.rootLogger=info,CONSOLE,R,HTML,TTCC
# Rolling File Appender
log4j.appender.TTCC=org.apache.log4j.RollingFileAppender
# Layout for Rolling File Appender
log4j.appender.TTCC.layout=org.apache.log4j.TTCCLayout
log4j.appender.TTCC.layout.DateFormat=ISO8601
# Path and file name to store the log file
log4j.appender.TTCC.File=./logs/testlog1.log
log4j.appender.TTCC.MaxFileSize=200KB
# Number of backup files
log4j.appender.TTCC.MaxBackupIndex=2
# Appender Configuration
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
# Pattern to output the caller's file name and line number
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d [%t] %-5p (%c:%L:%F) - %m%n
# Rolling File Appender
log4j.appender.R=org.apache.log4j.RollingFileAppender
# Path and file name to store the log file
log4j.appender.R.File=./logs/testlog.log
log4j.appender.R.MaxFileSize=200KB
# Number of backup files
log4j.appender.R.MaxBackupIndex=2
# Layout for Rolling File Appender
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d [%t] %-5p (%c:%L:%F) - %m%n
# Define the HTML file appender
log4j.appender.HTML=org.apache.log4j.FileAppender
# Path and file name to store the log file
log4j.appender.HTML.File=./logs/application.html
# Define the html layout for file appender
log4j.appender.HTML.layout=org.apache.log4j.HTMLLayout
#Define Title of the HTML page
log4j.appender.HTML.layout.Title=Application logs
#Define the log location of application class file
log4j.appender.HTML.layout.LocationInfo=true



Step 3:

        We need to pass the class name of the getLogger() method for  which we take this log.

It looks like :
        private static final Logger logger = Logger.getLogger("Log4JSettings"); 

Step 4:
        
         We need to locate confire file using code by this code

PropertyConfigurator.configure("Log4j.properties");

Step 5:
        
        Add different log in our application where we want in our application.
 
It looks like :

Sample Code is given below


package seleniumwebdriver;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class Log4JSettings {
   
    private static final Logger logger = Logger.getLogger("Log4JSettings");
   
    public static void main(String args[]) throws IOException {
        PropertyConfigurator.configure("Log4j.properties");
       
        try {


                 /**
                    * We try to read a File which is not present 
                    * in the path so it get exception which is shown 
                    * in Console Text File as well as HTML Format
                    * as  described in Log4j Properties File.                  */     
            FileInputStream fstream =
                    new FileInputStream("D:\\textfile.txt");
            DataInputStream in =
                    new DataInputStream(fstream);
            BufferedReader br =
                    new BufferedReader(new InputStreamReader(in));
            String strLine;
            while ((strLine = br.readLine()) != null) {
                System.out.println(strLine);
            }
            in.close();
        } catch (FileNotFoundException fe) {

            logger.error("File Not Found", fe);
            logger.warn("This is a warning message");
            logger.trace("This message will not be logged since log "
                    + "level is set as DEBUG");

        } catch (IOException e) {
            logger.error("IOEXception occured:", e);

        }
    }
}
 


  

 

Saturday, January 11, 2014

Taking Screen Shot Using Webdriver


We need to take screen shot of the application for capturing the state of the application.It may be required to store the state when application not behave as per requirement or to store the state after some operation properly happened.

There is two way to take the screen shot.

1.

a. TypeCast the driver object as TakesScreenshot class and use getScreenshotAs(OutputType.FILE) method.


b. Then copy this screen shot file in the desired directory using FileUtils.copyFile(scrFile, new File("src//google.jpg"));


Example Code is given below:

package seleniumwebdriver;

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;



public class ScreenShots{
        public static void main(String[] args) throws IOException {
        WebDriver myTestDriver = new FirefoxDriver();
        myTestDriver.get("http://www.google.com");
        File scrFile = ((TakesScreenshot)myTestDriver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(scrFile, new File("src//google.jpg"));

        myTestDriver.quit();
    }

}

2. On previous example we take the screen shot using Selenium Web Driver but there is no way to take screen shot when any event happen on webdriver.

Here we learn how to take screen shot when any event happen webdriver take the screenshot and store the Image file into the desired path. There is 15 abstract method into the WebDriverEventListener class so when we implement this it will generate 15 methods to overrride.

1.   public void beforeNavigateTo(String url, WebDriver driver) 
2.   public void afterNavigateTo(String url, WebDriver driver)
3.   public void beforeNavigateBack(WebDriver driver)
4.   public void afterNavigateBack(WebDriver driver)
5.   public void beforeNavigateForward(WebDriver driver)
6.   public void afterNavigateForward(WebDriver driver)
7.   public void beforeFindBy(By by, WebElement element, WebDriver driver)
8.   public void afterFindBy(By by, WebElement element, WebDriver driver)
9.   public void beforeClickOn(WebElement element, WebDriver driver)
10  public void afterClickOn(WebElement element, WebDriver driver)
11  public void beforeChangeValueOf(WebElement element, WebDriver driver)
12. public void afterChangeValueOf(WebElement element, WebDriver driver)
13. public void beforeScript(String script, WebDriver driver)
14. public void afterScript(String script, WebDriver driver)
15. public void onException(Throwable throwable, WebDriver driver) 


So we need to follow this septs:




a. Implement WebDriverEventListener class  
b. We also need to register the driver  like this way :

                   WebDriverEventListener evtlistner=new ScreenShots();
                   driver = new EventFiringWebDriver(new FirefoxDriver()).register(evtlistner);


Sample code is given below:


public class ScreenShots implements WebDriverEventListener{
        public static void main(String[] args) throws IOException {
                   WebDriver driver;

                  //WebDriverListner is assigned for the desired class
                  

                   WebDriverEventListener evtlistner=new ScreenShots();
                   
                  //Register Firefox driver with this event listner
                   

                   driver=new EventFiringWebDriver(new FirefoxDriver()).register(evtlistner);
                   driver.navigate().to("https://www.google.com");
                   driver.navigate().back();
                   driver.navigate().forward();
                   driver.navigate().refresh();
               driver.quit();
    }

    @Override
    public void beforeNavigateTo(String url, WebDriver driver) {
        File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        StringBuilder s= new StringBuilder();
        System.out.println(s.append(String.valueOf(Calendar.getInstance().get(Calendar.HOUR))).append(Calendar.getInstance().get(Calendar.HOUR)).append(Calendar.getInstance().get(Calendar.MILLISECOND)));

        try {
                    FileUtils.copyFile(scrFile, new File("src//"+s+".jpg"));
                } catch (IOException ex) {
                    Logger.getLogger(ScreenShots.class.getName()).log(Level.SEVERE, null, ex);
                }
    }

 

Thursday, January 9, 2014

Internet Explorer Configuration With Selenium WebDriver


Previously we execute all test on firefox but here we try to do something with Internet Explorer(IE).

IE driver does not come with Selenium webdriver package so we need to download separately and configure it to run the script properly.Now we learn how to configure IE driver :

Step1

Download IE Driver Server from here.We can download 32 bit 64 bit driver as per our test environment.



 Step 2

 Extract file from downloaded zip file.


Step 3

 Open the extracted folder and get "IEDriverServer.exe" file.

Step 4

Copy the directory path where IEDriverServer.exe file exists and put it into the environment variable under user variable.To open Environment variable path we just need to right click on My Computer -> Properties ->Advanced then click on Environment Variables.



 Step 5

If we use vista onwards machine then we check "Enable Protected Mode" from Security tab for all zone of IE settings.



If enable this option is not possible then put this code on our test script

DesiredCapabilities capabilitiesIE = DesiredCapabilities.internetExplorer();
            capabilitiesIE.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);


WebDriver driver = new InternetExplorerDriver(capabilitiesIE);

Step 6

Set the IE zoom 100% from view option.

After opening the IE it give an Warning in output view of our JAVA IDE like

Started InternetExplorerDriver server (32-bit)
2.39.0.0
Listening on port 54001
Jan 9, 2014 4:39:20 PM org.apache.http.impl.client.DefaultRequestDirector tryExecute
INFO: I/O exception (org.apache.http.NoHttpResponseException) caught when processing request: The target server failed to respond
Jan 9, 2014 4:39:21 PM org.apache.http.impl.client.DefaultRequestDirector tryExecute
INFO: Retrying request 

We can ignore this,actually this shows because IE driver is slow so it cannot communicate quickly with port 54001.

In below a sample code is there

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package seleniumwebdriver;

import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;

/**
 *
 * @author Administrator
 */
public class IEDriverSetUp {

    public static void main(String args[]) {
        try {
            File ieExecutable = new File("C:/IEDriverServer_Win32_2.39.0/IEDriverServer.exe");
            System.setProperty("webdriver.ie.driver", ieExecutable.getAbsolutePath());
            DesiredCapabilities capabilitiesIE = DesiredCapabilities.internetExplorer();
            capabilitiesIE.setCapability(
                    InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
            WebDriver driver = new InternetExplorerDriver(capabilitiesIE);

            driver.navigate().to("http://www.google.com");
        } catch (Exception ex) {
            Logger.getLogger(IEDriverSetUp.class.getName()).logp(Level.SEVERE, IEDriverSetUp.class.getName(), null, null, ex);
        }
    }
}

 




Monday, January 6, 2014

Scroll Page Using Java Script And Find Dynamically Loaded Element


Presently we can see that total webelement is not loaded at one moment rather element loaded when we scroll the pages.

So here we choose "Jabong" for an example page.Here more product list generated when we go down slowly .We stop scrolling when we find our desired product and click on this product.

To Scroll the page we need to fire the java script. For this we follow this steps:

Step1:
import org.openqa.selenium.JavascriptExecutor;

Step2:
((JavascriptExecutor) driver).executeScript("window.scrollBy(0,100)", "");


Now problem is how to find element which we want, because element loaded when page scrolled.
We get exception if element is not present on the page so we should catch this exception and scroll the page again to find the element until the page end.



Sample Code is given below:

import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;

/**
 *
 * @author Administrator
 */
public class Scroll {

    public static void main(String args[]) {

        WebDriver driver = new FirefoxDriver();
        driver.manage().window().maximize();
        driver.navigate().to("http://www.jabong.com/men/clothing/"
                + "?source=topnav");
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        System.out.println("Close the modal popup");
        driver.findElement(By.id("jab-vchr-cls")).click();
 /**
 * while(
!reachedbottom) loop is required to search the
 * element until page end .We put find
 * element within try-catch and if it get
 * exception it scroll the page and again
 * try to find the element.
 */


        boolean reachedbottom = Boolean.parseBoolean(js.executeScript("return $(document)"
                + ".height() == ($(window).height() + $(window).scrollTop());").toString());
        while (!reachedbottom) {
            ((JavascriptExecutor) driver).executeScript("window.scrollBy(0,600)", "");
            try {
                reachedbottom = Boolean.parseBoolean(js.executeScript("return $(document).height() "
                        + "== ($(window).height() + $(window).scrollTop());").toString());
                WebElement element = driver.findElement(By.xpath("//*[@id='http://static3.jassets.com/p/The-Indian-Garage-Co.-Checks-Red-Casual-Shirt-2889-679124-1-catalog.jpg']/img"));
                Wait<WebDriver> wait_element = new WebDriverWait(driver, 10);
                wait_element.until(ExpectedConditions.elementToBeClickable(element));
                element.click();
                System.out.println("!!!!!!!!!!!!!!At Last Get Success!!!!!!!!!!!!!!!!");
                break;
            } catch (Exception ex) {
                Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
                System.out.println(ex.getMessage());
            }
        }
    }
}






Handling Modal Pop Up Of an Web Page


We can see that some webpage show some banner, offer coupon or some registration form after page loaded and background page was disabled.

We choose "Jabong" for an example page to handle modal pop up.Some code is given below:

        WebDriver driver = new FirefoxDriver();
        driver.manage().window().maximize();
        driver.navigate().to("http://www.jabong.com/men/clothing/"
                + "?source=topnav");
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        System.out.println("Close the modal popup");
        driver.findElement(By.id("jab-vchr-cls")).click();


 

Sunday, January 5, 2014

Open Link In New Tab Using Mouse Click


We can Open link in new tab pressing Control + Left mouse click in firefox.So here we take Google as an example page and open "About" and "+You" in new Tab.

 WebDriver driver = new FirefoxDriver();
 driver.navigate().to("http://www.google.com");

 WebElement oWE = driver.findElement(By.linkText("About"));
 WebElement oWE1 = driver.findElement(By.linkText("+You"));
Actions oAction=new Actions(driver);

oAction.moveToElement(oWE).keyDown(Keys.CONTROL).click(oWE)
                             .keyUp(Keys.CONTROL).perform();

Thread.sleep(1000);
Actions oAction1=new Actions(driver);

oAction1.moveToElement(oWE1).keyDown(Keys.CONTROL).click(oWE1)
                             .keyUp(Keys.CONTROL).perform();