Saturday, February 7, 2015

Wait in Page Factory

We know that in Selenium WebDriver already have implicit and explicit wait,it is required to wait for an element until some condition is satisfied or to check that element is loaded or not.

In Page Factory model  there is AjaxElementLocatorFactory class by which we can implement another type of waiting technique for web element, it is basically behave same as implicit wait.

We can initialize AjaxElementLocatorFactory into the constructor by which we can avail the wait facility on all WebElements in the same page object class . It is basically used where application have more Ajax component Elements.

Example code is given below
  //***************************************
  // BLOGPAGE Class
  //*************************************** 

package com.core.pageobject;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.pagefactory.AjaxElementLocatorFactory;

public class BlogPage {

    @FindBy(name = "txtbox1")
    private WebElement inputBox;
    @FindBy(name = "btnsub")
    private WebElement submitBtn;
    @FindBy(linkText = "Google")
    private WebElement googleLink;
    private final WebDriver driver;

    public BlogPage(WebDriver driver) {
        this.driver = driver;

        //  Wait 20 Second To Find Element If Element Is Not Present
        PageFactory.initElements(new AjaxElementLocatorFactory(driver, 20), this);
    }

    public BlogPage submitForm(String inputTxt) {
        inputBox.sendKeys(inputTxt);
        return new BlogPage(driver);
    }

    public GooglePage clickOnGoogleLink() {
        googleLink.click();
        return new GooglePage(driver);
    }
}
 

  //***************************************
  // GOOGLEPAGE Class
  //***************************************
package com.core.pageobject;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.pagefactory.AjaxElementLocatorFactory;

public class GooglePage {

    private final WebDriver driver;
    @FindBy(name = "q")
    WebElement searchTxtBox;

    public GooglePage(WebDriver driver) {
        this.driver = driver;

        //  Wait 20 Second To Find Element If Element Is Not Present
        PageFactory.initElements(new AjaxElementLocatorFactory(driver, 20), this);
    }

    public GooglePage searchTxt(String searchTxt) {
        searchTxtBox.sendKeys(searchTxt);
        return new GooglePage(driver);
    }
}


  //***************************************
  // Test Class
  //**************************************
package com.core.pageobject;

import java.io.File;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxBinary;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class PageObjectModelTest {

    WebDriver driver;

    @BeforeTest
    public void testSetUp() {
        FirefoxBinary bin = new FirefoxBinary(new File("G:\\Program Files\\Mozilla Firefox\\firefox.exe"));
        FirefoxProfile prof = new FirefoxProfile();
        driver = new FirefoxDriver(bin, prof);
    }

    @BeforeMethod
    public void testMethodSetUp() {
        driver.get("http://startingwithseleniumwebdriver.blogspot.in/2013/12/frmset1.html");
    }

    @Test
    public void testSubmit() throws Exception {
        BlogPage blog = new BlogPage(driver);
        blog.submitForm("Test");
    }

    @Test
    public void testGoogleLink() throws Exception {
        BlogPage blog =new BlogPage(driver);
        blog.clickOnGoogleLink().searchTxt("Test");
    }

    @AfterTest
    public void tearDown() {
        driver.quit();
    }
}

Saturday, January 17, 2015

PageFactory In Selenium WebDriver

PageFactory is a way to implement Page Object Model in Selenium Webdriver.

In PageFactory mainly there are two things

1. PageFactory.initElements Method
2. @FindBy annotation

There are lots of other annotation(Like @FindAll,@FindBys,@Cache etc ) which we will learn later.


1. PageFactory.initElements Method

initElements are static methods of PageFactory class.

If we use this methods then we can assign value to the webelement at runtime when it is required. That means class loaded with WebElements having  some proxy(garbage or default) value and when actually it is required ,means call form method or accessing the WebElement in any way then it will find the WebElement into the page and assign the actual value to this WebElement. initelements method only assign value to the WebElement which is required currently it is not load the all webelement which is declared in page object class.

2. @FindBy annotation

Used to mark a field on a Page Object to indicate an alternative mechanism for locating the element or a list of elements. This allows users to quickly and easily create PageObjects.
You can either use this annotation by specifying both "how" and "using" or by specifying one of the location strategies (eg: "name") with an appropriate value to use.

e.g
 @FindBy(name = "q") 
  WebElement searchTxtBox;
 
 @FindBy(how = How.NAME, using = "q") 
  WebElement searchTxtBox;
 
Example Code is given below:
 
  //***************************************
  // BLOGPAGE Class
  //*************************************** 

package com.core.pageobject;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;

public class BlogPage {
 
  //***************************************
  // Use @FindBy Annotation To Locate Elements
  // Within Blog Page
  //***************************************  
    @FindBy(name = "txtbox1")
    private WebElement inputBox;
    @FindBy(name = "btnsub")
    private WebElement submitBtn;
    @FindBy(linkText = "Google")
    private WebElement googleLink;
 
    private final WebDriver driver;

    public BlogPage(WebDriver driver) {
        this.driver = driver;
    }
  //***************************************
  // BlogPage Have A Submit Button After
  // Click On That It Stay On Same Page So
  // Return Same Page Object
  //*************************************** 
 
    public BlogPage submitForm(String inputTxt) {
        inputBox.sendKeys(inputTxt);
        submitBtn.click();
        return PageFactory.initElements(driver, BlogPage.class);
    }
  //***************************************
  // BlogPage Have A Google Page Link After
  // Click On That It Redirect To Google Page
  // So Return Google Page Object
  //***************************************  
 
    public GooglePage clickonGoogleLink() {
        googleLink.click();
        return PageFactory.initElements(driver, GooglePage.class);
    }
}
 
  //***************************************
  // GOOGLEPAGE Class
  //***************************************
 
package com.core.pageobject;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;

public class GooglePage {
 
  //***************************************
  // Use @FindBy Annotation To Locate Elements
  // Within Google Page
  //***************************************  
    
    private final WebDriver driver;
    @FindBy(name = "q")
    WebElement searchTxtBox;

    public GooglePage(WebDriver driver) {
        this.driver = driver;
    }
 
  //***************************************
  // Searching Anything On Google Page remain
  // on Same Google Page So Return Type Is
  // Google Page Object.
  //*************************************** 
 
    public GooglePage searchTxt(String searchTxt) {
        searchTxtBox.sendKeys(searchTxt);
        return PageFactory.initElements(driver, GooglePage.class);
    }
} 
 
  //***************************************
  // Test Class
  //***************************************

package com.core.pageobject;

import java.io.File;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxBinary;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class PageObjectModelTest {

    WebDriver driver;

    @BeforeTest
    public void testSetUp() {
        FirefoxBinary bin = new FirefoxBinary(new File("G:\\Program Files\\Mozilla Firefox\\firefox.exe"));
        FirefoxProfile prof = new FirefoxProfile();
        driver = new FirefoxDriver(bin, prof);
    }

    @BeforeMethod
    public void testMethodSetUp() {
        driver.get("http://startingwithseleniumwebdriver.blogspot.in/2013/12/frmset1.html");
    }

    @Test
    public void testSubmit() throws Exception {
        BlogPage blog = PageFactory.initElements(driver, BlogPage.class);
        blog.submitForm("Test");
    }

    @Test
    public void testGoogleLink() throws Exception {
        BlogPage blog = PageFactory.initElements(driver, BlogPage.class);
        blog.clickonGoogleLink().searchTxt("Test");
    }

    @AfterTest
    public void tearDown() {
        driver.quit();
    }
}

 
 
We can create a another pageobject class for google search result here we make 
one pageobject class for google page and google search result.

Saturday, December 27, 2014

Page Object Model In Selenium WebDriver

What Is Page Object Model :

 Page Object Model is nothing but a code organization structure by which we can separated the web pages and Test classes.

Rule To Making This Structure :

 1. Separate the Test classes to WebPage classes.

 2. Create page related functionality on the same Page Class, from where we can perform functionality of this pages.

 3. If we perform any action on the page and redirect to the the another page, this method return type should be the another page object rather than void.If It stay on the same page then return the same page object or void.
               
     e.g : We can consider two page TestPage1 and TestPage2 for this example. 
TestPage1 and TestPage2 hold different component like button,image,checkbox,dropdown etc.Now we do some operational or structural work on this components like click,select etc to perform a logical or functional operation like login, sighout etc. After any individual logical or functional operation if we stay on the same page then this operation(method) return the same page object or void otherwise return the page object where it is redirected.

4. Isolate the Assertion(Pass,Fail) from the page classes and put them into test classes.

5. Page classes only hold the services that we can expect from this page.

6.Try to Exception handling into the test class.

Code Sample:

We have two page 

1. Blog Test Page
2. Google Search Page


We navigate Google search page from google link on Blog Test Page and give some text search on google page.So we must have 2 different class.BlogPage and GooglePage.

In BlogPage we have one operation click on google link which will navigate to the google page so this method return type should be google page object.But submit button on this page does not navigate to any other page it stay on this page so it's return type should be the blogpage object.

We follow the same structure in googlepage class also. 
  


Blog Test Page
---------------------------------
---------------------------------

package com.core.pageobject;


import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;

public class BlogPage {


    private final By inputBox=By.name("txtbox1");
    private final By submitBtn=By.name("btnsub");
    private final String googleLink="Google";
//    private final WebElement inputBox;
//    private final WebElement submitBtn;
//    private final WebElement googleLink;

    private final WebDriver driver;
   
    public BlogPage(WebDriver driver) {
        this.driver = driver; 

//      this.inputBox = driver.findElement(By.name("txtbox1"));
//      this.googleLink = driver.findElement(By.linkText("Google"));
//      this.submitBtn = driver.findElement(By.name("btnsub"));

    }
   

     
     /**********************************
     * This Method Return  BlogPage Object
     * Because After Submit It's Stay On The 

     * Same Page     
     **********************************/
    public BlogPage submitForm(String inputTxt){
        driver.findElement(inputBox).sendKeys(inputTxt);
        driver.findElement(submitBtn).click();
//        inputBox.sendKeys(inputTxt);
//        submitBtn.click();

    return new BlogPage(driver);
    }    


     /**********************************
     * This Method Return GoolePage Object
     * Because After Click On This Link

     * It's Redirect To The Google Page
     **********************************/

     public GooglePage clickonGoogleLink(){
        driver.findElement(By.linkText(googleLink)).click();
//         googleLink.click();
      return new GooglePage(driver);
    }
}

 

Google Test Page
-------------------------------
-------------------------------

package com.core.pageobject;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
 

public class GooglePage { 
    private final By searchBox=By.name("q");
//    private final WebElement searchBox;

    private final WebDriver driver;

    public GooglePage(WebDriver driver) {
        this.driver = driver; 

//      this.searchBox=driver.findElement(By.name("q"));
    }

     /**********************************
     * This Method Return Goole Page Object
     * Because After Click On Search Button

     * Redirect To The Google Page
     **********************************/

    public GooglePage searchTxt(String searchTxt){
      driver.findElement(searchBox).sendKeys(searchTxt); 
//      searchBox.sendKeys(searchTxt);
    return new GooglePage(driver);
    }
}

 


Page Object Model Test
--------------------------------------
--------------------------------------

package com.core.pageobject;

import java.io.File;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxBinary;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class PageObjectModelTest {
    WebDriver driver;


     /**********************************
     *Initialize Driver For All Test
     ***********************************/

    @BeforeTest
    public void testSetUp(){
        FirefoxBinary bin=new FirefoxBinary(new File("G:\\Program Files\\Mozilla Firefox\\firefox.exe"));
        FirefoxProfile prof=new FirefoxProfile();
        driver=new FirefoxDriver(bin, prof);
    }


     /**********************************
     * This Is Created To Go the Base Page 

     * Before Every Test
     **********************************/
    @BeforeMethod
    public void testMethodSetUp(){
    driver.get("http://startingwithseleniumwebdriver.blogspot.in/2013/12/frmset1.html");
    }



    @Test()
    public void testSubmit() throws Exception{
        BlogPage blog=new BlogPage(driver);
        blog.submitForm("Test");
    } 



    @Test
     public void testGoogleLink()throws Exception{
        BlogPage blog=new BlogPage(driver);
        blog.clickonGoogleLink().searchTxt("Test");
    } 


     /**********************************
     * This  Is Created To Close The Driver

     **********************************/
    @AfterTest
    public void tearDown(){
    driver.quit();
    }
}
 



Sunday, November 30, 2014

Custom CSS Locator Creation Technique

Previously we learn how to create or get the CSS Path from FirePath(Firefox browser Add-ons).

Here we try to learn the meaning of each and every element in CSS path.

Some Basic Of CSS-Path  
.
 It denote the class name
 e.g:- .editable

#
 It is used when we try to find element using id

 e.g:- #postingComposeBox

> or Space
 When we try to access the webelement which is direct child of the particular element then use >
 If we try to access the webelement which is maybe child or sub child then use Space

e.g:- div>a Here a is direct child of div element
         div a  Here a is sub-child and child also

tag[attributename="attributevalue"]
 We can directly access any webelement using the attributename and the corresponding value

 e.g:- div[class="field-item even"][name='test']>pre

tag[attributename~="attrivutevalue"]
 We can matching the exact word from attribute value string

 e.g:-iframe[title ~="utility"]

Sub String Matching


^= Match a prefix
$= Match a suffix
*= Match a substring

tag[attributename^="attrivutevalue"]
 Attribute value text starts with Addtext
e.g:-iframe[title^="Add"]

tag[attributename$="attrivutevalue"]
 Attribute value text ends with me text
e.g:-iframe[title$="me"]

tag[attributename*="attrivutevalue"] 
 Attribute value text contains lity text
 e.g:-iframe[title*="lity"]
 


Monday, October 27, 2014

Taking Screen Shot Of A Particular WebElement

Here we try to take a screen shot of an particular web element within a webpage.Normally when we take a screen shot using WebDriver we take the screen shot of a full page.We cannot take the screen shot of a particular web element or area.

Here we can do the following step to get the screen shot of an particular web element:

1.We take the screen shot of the full screen
2.Store The taken screen shot file into the buffer.
3.Then crop the picture from buffer image and store it into the buffer.
4.Write buffer to a File.
5.Then Copy the File to the particular destination.


Now, We try to implement this step

1. Taking the screen shot of whole page.   

File screenShot=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

2. Store the image into the buffer   

 BufferedImage buffImg=ImageIO.read(screenShot);

3. This is the step from where we can crop the picture.

For cropping a picture we need to know the X and Y coordinate of  the web element at any end point it maybe bottom left,bottom right,top right or top left corner of a web element .
We get the X and Y coordinate of an web element using element.getLocation().getX() and element.getLocation().getY(). It returns the top left corner x,y coordinate value.

Now we need to know the height and width of an web element. We can know this using  element.getSize().getWidth()  and element.getSize().getHeight() .

So this is the way we can crop the Image from buffer.
 
BufferedImage eleBuffImg=buffImg.getSubimage(element.getLocation().getX(), element.getLocation().getX()
                                ,element.getSize().getWidth() , element.getSize().getHeight());


4. We can write the buffer image to the file using this.

 ImageIO.write(eleBuffImg, "png",screenShot );

5. Now we can write this file to the particular location using this.

 FileUtils.copyFile(screenShot, new File("Your File Storing Location"));

Full Code is given below:





package WebElementScreenShot;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;

public class WebElementScreenShot {

    public static void main(String[] args) {

        //System.setProperty("webdriver.chrome.driver", "./chromedriver_win32_2.1/chromedriver.exe");
        ChromeDriverService service=new ChromeDriverService.Builder()
         .usingChromeDriverExecutable(new File("./chromedriver_win32_2.1/chromedriver.exe"))
         .usingAnyFreePort().build();
        WebDriver driver=new ChromeDriver(service);
       
        //Maximize Browser Window Because If It Is not Maximized
        //Then It May Take Screen Shot For Wrong Element.It may
        //Happen On Chrome Driver

       

         driver.manage().window().maximize();
       
        //Open The desired URL
        driver.get("http://www.google.com");

        try {
           
            //Call The Element Image Screen Shot Methiod
            elementScreenShot(driver, By.id("gbqfq"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally{
            driver.quit();
        }
    }
   
    public static void elementScreenShot(WebDriver driver,By byElement) throws IOException{
        WebElement element=driver.findElement(byElement);
       
        //This Is For To Surround The WebElement Before Taken The Screen Shot
        ((JavascriptExecutor)driver).executeScript("arguments[0].setAttribute('style', arguments[1]);",element, "color: Red; border: 2px solid red;");
       
        //Take The Full Page Screen Shot
        File screenShot=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
       
        //Transfer Full Image To Buffered Image
        BufferedImage buffImg=ImageIO.read(screenShot);
       
        //Crop The Picture According To the Element Size From Buffered Image 
        BufferedImage eleBuffImg=buffImg.getSubimage(

             element.getLocation().getX(), element.getLocation().getX(),
             element.getSize().getWidth() , element.getSize().getHeight());
       
        //Write The Buffered Image into Main Taken Screen Shot File
        ImageIO.write(eleBuffImg, "png",screenShot );
       
        //Copy The Crop Image Into The Machine Drive
        FileUtils.copyFile(screenShot, new File("D:/Test.jpeg"));
       
    }

}


  


Sunday, September 28, 2014

HighLight Web Element During Execution

During Execution we need to highlight the web element for debugging or to check, that we find the right element of the web page.In QTP we can do this using Active Window if the object is stored into the Object Repository.

So, now question is how to implement this in Selenium WebDriver?

We can achieve this using java script executor,

js.executeScript("arguments[0].style.border='3px solid red'", element);

                                                                  OR
 
js.executeScript("arguments[0].setAttribute('style', arguments[1]);",element, "color: Red; border: 2px solid red;");

We can use any of them to set set the red solid border around the element.


The Complete code is given below:

package highlight;

import java.io.File;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;

public class HighLight {

    /**
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {
     
      //#####################################################
      //Here We SetUp The Chrome Driver With Any Free Port
      //And We Also Set The Chrome Driver Path
      //#####################################################

  ChromeDriverService service=new ChromeDriverService.Builder()
            .usingChromeDriverExecutable(new File("./chromedriver_win32_2.1/chromedriver.exe"))
            .usingAnyFreePort().build();
        WebDriver driver=new ChromeDriver(service);
        driver.get("http://www.google.com");
        findElement(driver,By.name("q"));
       
    }



      //#####################################################
      //Below Two Methods Do The Same Thing But They Use 
      //Different Java Script.
      //#####################################################

      //#####################################################
      //Method 1
      //#####################################################  
     public static WebElement findElement(By by,WebDriver driver) throws InterruptedException {
        WebElement element = driver.findElement(by);
      
        // draw a border around the found element
        if (driver instanceof JavascriptExecutor) {
            JavascriptExecutor js = (JavascriptExecutor) driver;
            js.executeScript("arguments[0].style.border='3px solid red'", element);
            Thread.sleep(1000);
            js.executeScript("arguments[0].style.border=''",element, "");
            Thread.sleep(1000);
        }
        return element;
    }


      //#####################################################
      //Method 2
      //#####################################################  
    public static WebElement findElement(WebDriver driver, By by) throws InterruptedException {
        WebElement element = driver.findElement(by);
        

         // draw a border around the found element
           if (driver instanceof JavascriptExecutor) {
                JavascriptExecutor js = (JavascriptExecutor) driver;
                js.executeScript("arguments[0].setAttribute('style', arguments[1]);",element, "color: Red; border: 2px solid red;");
                Thread.sleep(1000);
                js.executeScript("arguments[0].setAttribute('style', arguments[1]);",element, "");
                Thread.sleep(1000);
            }
        return element;
    }
}

Sunday, August 3, 2014

Custom XPath Creation Technique

Mainly we use FirePath for getting XPath of an element but sometime we need to make XPath manually or need to customize the XPath.

Some Basic of XPath Notation

/                                                    
Select from the root node                   
ex: html/body/.......

//                                               
Select nodes form the current node     
ex: //table/tbody/tr/.............

@                                                  
Select attribute                                  
ex: //input[@id='abc']

//input[@id='Some Value']          
Select element with tag name and id        

//input[contains(text(),'TextValue')] 
Select element with text containing abc
ex: //input[contains(text(),'abc')]

//input[starts-with(text(),'TextValue')] 
Select element with text starting with abc
ex: //input[starts-with(text(),'abc')]

//input[contains(@id, 'TextValue')]    
identify element containing 'abc' in value attribute

//input[contains(@id, 'searchInput') and contains(@text,'google')]
look at two attributes in input node

//input[starts-with(@type, 'abc')]
find input node with attribute type and its value is starting with 'abc'

//*[@accesskey='abc'] 
Can use wild cards

//input[text()='abc']                      
Select element with tag input and text=abc

//td/a/strong[contains(text(),'abc')]
Find all elements containing 'abc'

.//input[position()=1]   
Select Input of First Position

//div[@class='cmnts']/descendant::div[position()=2]
Select 2nd div of the div node One thing keep in mind that descendant means child, child of child etc

//div[@class='cmnts']/ancestor::div[position()=2] 

//div[@class='GCUXF0KCICB']/ancestor-or-self::div[position()=2]
ancestor-or-self means traversing starts from current node.

//input[last()]

.//div[@class='GCUXF0KCO3B']/span[text()='Labels']
Select span text

.//div[count(*)=0]
Select div that does not contain any child node

Sunday, July 27, 2014

Log4J JDBC Configuration For DataBase Log

Some time we need to use DataBase for automation where we can try to validate UI(FrontEnd) with DataBase(BackEnd). So there are lots of database communication is needed and we need to track this what happened with the database.

Log4J JDBC is use for this reason by which we can track the all database communication.

Log4J JDBC use the SLF4J for logging but it does not have the capacity for writing the log into the file so we use Log4J with this.

Now we will go for the configuration for this.

Step 1:

a.Download Log4 JDBC form here
b.Download SLF4J from here
c.Download Log4j from here

Step 2:

Put this jars into the class path of our project.

slf4j-api-1.7.7.jar
slf4j-log4j12-1.7.7.jar
log4jdbc4-1.2.jar
log4j-1.2.17.jar

Step 3:

Put this Log4J configuration file into the project directory. The File looks like that


# Logging levels are:
# DEBUG < INFO < WARN < ERROR < FATAL


# turn on the internal log4j debugging flag so we can see what it is doing
log4j.debug=true

# JDBC API layer call logging :
# INFO shows logging, DEBUG also shows where in code the jdbc calls were made,
# setting DEBUG to true might cause minor slow-down in some environments.
# If you experience too much slowness, use INFO instead.


# Log all JDBC calls except for ResultSet calls
log4j.logger.jdbc.audit=INFO,jdbc
log4j.additivity.jdbc.audit=false

# Log only JDBC calls to ResultSet objects

log4j.logger.jdbc.resultset=INFO,jdbc
log4j.additivity.jdbc.resultset=false

# Log only the SQL that is executed.
log4j.logger.jdbc.sqlonly=DEBUG,sql
log4j.additivity.jdbc.sqlonly=false

# Log timing information about the SQL that is executed.
log4j.logger.jdbc.sqltiming=DEBUG,sqltiming
log4j.additivity.jdbc.sqltiming=false

# Log connection open/close events and connection number dump
log4j.logger.jdbc.connection=FATAL,connection
log4j.additivity.jdbc.connection=false


# the appender used for the JDBC API layer call logging above, sql only
log4j.appender.sql=org.apache.log4j.FileAppender
log4j.appender.sql.File=./logs/sql.log
log4j.appender.sql.Append=false
log4j.appender.sql.layout=org.apache.log4j.PatternLayout
log4j.appender.sql.layout.ConversionPattern=-----> %d{yyyy-MM-dd HH:mm:ss.SSS} %m%n%n

# the appender used for the JDBC API layer call logging above, sql timing
log4j.appender.sqltiming=org.apache.log4j.FileAppender
log4j.appender.sqltiming.File=./logs/sqltiming.log
log4j.appender.sqltiming.Append=false
log4j.appender.sqltiming.layout=org.apache.log4j.PatternLayout
log4j.appender.sqltiming.layout.ConversionPattern=-----> %d{yyyy-MM-dd HH:mm:ss.SSS} %m%n%n

# the appender used for the JDBC API layer call logging above
log4j.appender.jdbc=org.apache.log4j.FileAppender
log4j.appender.jdbc.File=./logs/jdbc.log
log4j.appender.jdbc.Append=false
log4j.appender.jdbc.layout=org.apache.log4j.PatternLayout
log4j.appender.jdbc.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSS} %m%n

# the appender used for the JDBC Connection open and close events
log4j.appender.connection=org.apache.log4j.FileAppender
log4j.appender.connection.File=./logs/connection.log
log4j.appender.connection.Append=false
log4j.appender.connection.layout=org.apache.log4j.PatternLayout
log4j.appender.connection.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSS} %m%n

# Log levels
log4j.rootLogger=DEBUG,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=%5p [%t] (%F:%L) - %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 - %c - %p - %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 4:

Now we write a database related code to test this, code looks like that

//STEP 1. Import required packages

import java.sql.*;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class DataBaseWork {
  
  private static final Logger logger = Logger.getLogger("Log4JSettings");
 
   // JDBC driver name and database URL
   // For Logging We need to change this as given below
  
   static final String DB_URL = "jdbc:log4jdbc:derby://localhost:1527/sample";

   //  Database credentials
   static final String USER = "app";
   static final String PASS = "app";
 
   public static void main(String[] args) {
     
   PropertyConfigurator.configure("log4j.properties");
   Connection conn = null;
   Statement stmt = null;
   try{
     
       //STEP 2: Register JDBC driver
      //For Logging we need to set the driver as below

      Class.forName("net.sf.log4jdbc.DriverSpy");
     
      //STEP 3: Open a connection
     
      System.out.println("Connecting to database...");
      conn = DriverManager.getConnection(DB_URL,USER,PASS);

      //STEP 4: Execute a query
     
      System.out.println("Creating statement...");
      stmt = conn.createStatement();
      String sql;
      sql = "select CUSTOMER_ID from APP.CUSTOMER";
      ResultSet rs = stmt.executeQuery(sql);

      //STEP 5: Extract data from result set
     
        while(rs.next()){
       
        //Retrieve by column name
        
         int id  = rs.getInt("CUSTOMER_ID");
        String first = rs.getString("CUSTOMER_ID");


         //Display values
        
          System.out.print("ID: " + id);
          System.out.print("\n");
      }
     
      //STEP 6: Clean-up environment
    
       rs.close();
      stmt.close();
      conn.close();
   }catch(SQLException se){      
    //Handle errors for JDBC
   
     se.printStackTrace();
   }catch(Exception e){
    //Handle errors for Class.forName
    
       e.printStackTrace();
   }finally{
      //finally block used to close resources
     
      try{
         if(stmt!=null)
            stmt.close();
         logger.debug("Test Debug");
      }catch(SQLException se2){
      }// nothing we can do
      try{
         if(conn!=null)
            conn.close();
      }catch(SQLException se){
         se.printStackTrace();
      }//end finally try
   }//end try
   System.out.println("Goodbye!");
}//end main
}//end FirstExample


Now we see the log about the database activity.

Saturday, July 12, 2014

Zip File Handling with Java And Selenium WebDriver

Some time we need to compress files for sending it.Here we learn how we can handle this programmatically.

We can handle this in two ways
1. Java SDK
2. Selenium WebDriver

1.Zip Using Java SDK:

public class Compress {

static List<String> fileList=new ArrayList<String>();

public static void main(String args[]) throws IOException {
        sendToZip(new File("Our Source To Zip"), new File("Our Destination To Zip\\ZipFile.ZIP"));
}

##########################################
#This Method is Created for List down Of All Files
# within the Source Path and put the Absolute Path 
#into the List
##########################################
    private static List<String> addFiletoList(File inputDir)
    {
        File[] listOfFile=inputDir.listFiles();
        for (File file : listOfFile) {
        if(file.isFile())
            fileList.add(file.getAbsolutePath());
        else
            addFiletoList(file);
        }
    return fileList;    
    }


##########################################
#This Method is Created to Zip the all File and 
#Save it to the Destination Path
###########################################
    private  static void sendToZip(File zipInput,File zipOutPut) throws FileNotFoundException, IOException
    {  
        List<String> fileList=new ArrayList<String>();
        fileList=addFiletoList(zipInput);
        FileOutputStream fos=new FileOutputStream(zipOutPut);
        ZipOutputStream zos=new ZipOutputStream(fos);
        for(String filePath:fileList){
            FileInputStream fis = new FileInputStream(filePath);

           
            //String name is required for showing the file name after zip same as before zip
 
            String name = filePath.substring(zipInput.getAbsolutePath().length()+1, filePath.length());
            ZipEntry entry = new ZipEntry(name);
            zos.putNextEntry(entry);

            int len;
            byte[] buffer = new byte[4096];
            while ((len = fis.read(buffer)) != -1) {
                zos.write(buffer, 0, len);
            }

            fis.close();
            zos.closeEntry();
        }
        zos.close();
        fos.close();
    }

} 

 1.Zip Using Selenium WebDriver:

Zip compress=new Zip();compress.zip(new File("Our Source To Zip"), new File("Our Destination To Zip"));





Now we can see that Zip using Selenium is more compact and easy coding but there is a problem if source and destination zip folder path is same then it creates a corrupted zip folder with in our zip folder.

So always keep in mind if we use selenium provided zip functionality then Zip folder Source and Zip folder Destination should be different. 

Sunday, June 22, 2014

Running Script on Selenium Grid

On previous post we learn how to configure Selenium grid and Node.Now we will try to learn how we can access Selenium Grid from our code.

Actually we do not need to change lots of things we just need to change the driver initialize part it should be looks like that
        
       DesiredCapabilities cap =new DesiredCapabilities();
       cap.setBrowserName("firefox");
       WebDriver driver = new RemoteWebDriver(new URL("http://Machine IP or localhost:PortNumber in which port hub is running/wd/hub"), cap); 
this is the main thing for the Selenium Grid script code rest of the part is same as the normal script.

If firefox is installed in other than default location then we need to specify the location of the firefox binary when we configure the node,node setup command should be looks like that

java -jar "path of selenium-server-standalone-2.41.0.jar" -role node -hub "http://Machine IP or localhost:PortNumber in which port hub is running/grid/register" -browser "firefox_binary=firefox binary path, browserName=firefox"

 If we need to run the script on IE then it is little bit tricky,we need to register the IE diver to the node, the command looks like that


java -jar "path of selenium-server-standalone-2.41.0.jar" -role node -hub "http://Machine IP or localhost:PortNumber in which port hub is running/grid/register" -Dwebdriver.ie.driver="path of 32 bit 64 bit IEDriverServer.exe"

 and need to set this into the code

cap.setBrowserName("internet explorer");




Thursday, June 5, 2014

Configuration of Selenium Grid And Node

Still now our main aim or goal to execute test script on the same machine where our script developed.But if we need to run the same test script on different environment(mainly the different version of browser we may also consider the different operating system) at the same time what we do? The answer is Selenium Grid.


Q1:Where we can find the Selenium Grid?
Ans: Selenium Grid is basically a jar file we can download this jar from here.

Q2:Which jar we need to run Selenium Grid?
Ans: After going to the above mentioned link we can find Download Version(Some version number) link under the Selenium Server(formerly the Selenium RC Server). After clicking to this link we can download the
selenium-server-standalone-2.41.0.jar file.The page looks like that

Q3:How many part we need to configure for Selenium Grid setup
Ans: Basically 2 part we need to configure for Selenium Grid set up
              A.Hub
                  Hub will receive all requests and distribute them to the right nodes.basically it play the Server role.
              B.Node
                  Node is playing as a client role

Q3:How to install or run this jar for hub role?
Ans: Just execute this command
                java -jar "our selenium Grid directory\selenium-server-standalone-2.41.0.jar" -role hub
After executing this command command screen shows the details it looks like below

Some common problems to start the Hub and solutions

Problem1: java -jar not executed
Solution: Go to the installed location of the java bin folder from the command prompt and then execute the above mentioned command.

 Problem2: Exception to bind the port


Solution:If we drill down the exception it clearly shows that Selenium Grid got this exception because default port (4444) is used by another process.To jump over this hurdle we just mention the free port with the command so it should be looks like that 
                   java -jar "our selenium Grid directory\selenium-server-standalone-2.41.0.jar" -role hub -port FreePortNumber 

How we know that which ports are using currently?
Ans: Execute the below command from the command prompt by which we can get the details of the all process and port
                   netstat -a -n -o
So we take any port except those ports are listed into the command prompt.

 Problem 3: FireWall block this port which we try to open?
Ans: Allow or unblock the port from FireWall ,if there is no security problem then off the FireWall.


After successfully start the hub we can find the webpage which looks like below if we hit the url:
http://localhost:portnumber(this is for local machine from where we execute the command to start the hub) or http://hubmachineIP:portnumber

In the below example we hit the url from the local machine

Q4:How to run or install the jar for the client role?
Ans:  Execute this command
                 java -jar "our selenium Grid directory\selenium-server-standalone-2.41.0.jar" -role node -hub http://our hub machine ip or localhost:portnumber/grid/register 

After successfully executing the command, command line screen should be looks like that 



Some common problems to start the Node and solutions

Problem1: Exception to bind the port means that it is already in use
Solution:If we drill down the exception it clearly shows that Selenium Grid got this exception because default port (5555) is used by another process.To avoid this problem we just mention the free port with the command so command should be looks like that 

  java -jar "our selenium Grid directory\selenium-server-standalone-2.41.0.jar" -role node -hub http://hub machine IP or localhost:portnumber/grid/register -port FreePortNumber

 There are lots of  optional parameter we can pass to the node when we required it like

borwsername:          -browser browserName=firefox
plantform:                 platform=WINDOWS
maxInstances:          maxInstances=5
version:                     version=29.0.1
firefox_binary           firefox_binary=our firefox binary path
port                           -port 4444

e.g:
  java -jar "our selenium Grid directory\selenium-server-standalone-2.41.0.jar" -role node -hub http://hub machine IP or localhost:portnumber/grid/register -port FreePortNumber -browser browserName=firefox platform=WINDOWS