Sunday 29 September 2013

Reading an element contnet without using XPath by WebDriver

Purpose: Reading an element contnet without using XPath by WebDriver

Some times we can access an element with class only but the class contans compound values but className will not accept compound values.

In order to handle these situatuions we need to write differently. Following code will help you to handle it.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class Webelements {
 static WebDriver driver;
 // Browser startup
 @BeforeClass
 public void setup() {
 
  driver = new FirefoxDriver();
 }
 // Functionality of Test Case
 @Test
 public void testGoogle() throws InterruptedException, IOException {
 
  driver.get("http://quirksmode.org/css/selectors/multipleclasses.html");
//  System.out.println(driver.findElement(By.className("underline small")).getText());
  System.out.println(driver.findElement(By.cssSelector("p[class='underline small']")).getText());
 
  Thread.sleep(3000);
 }
 @AfterClass
 public void tear() {
  driver.close();
 }

Wednesday 25 September 2013

Expanding Tree Structure using Selenium Web Driver

Purpose: Expanding Tree Structure using Selenium Web Driver

Following code will help how to expand tree structure with the help of Selenium WebDriver. Every Tree Structure have its own levels. Following code will help to go 2 level expansion.

import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class TreeStructure {
 public String baseURL = "http://www.javascripttoolbox.com/lib/mktree/";

 public WebDriver driver = new FirefoxDriver();
 @BeforeMethod
 public void setup()
 {
  driver.get(baseURL);
 }

 @AfterMethod
 public void tear()
 {
  driver.quit();
 }

 @Test
 public void testTreeStructure() throws InterruptedException
 {
  driver.findElement(By.xpath("html/body/table/tbody/tr[2]/td[1]/div[2]/div[2]/p[6]/a[2]")).click();
  Thread.sleep(3000);
  List<WebElement> roots = driver.findElements(By.xpath(".//*[@id='tree1']/li"));
  int rootSize = 1;
  for(WebElement root: roots)
  {
   String openRoot = root.getAttribute("class");
   if(openRoot.equalsIgnoreCase("liClosed"))
   {
    String xpath = ".//*[@id='tree1']/li["+rootSize+"]/span";
    openTree(xpath);
    List<WebElement> childRoots = driver.findElements(By.xpath(".//*[@id='tree1']/li["+rootSize+"]/ul/li"));
    int subRootSize = 1;
    for(WebElement childRoot: childRoots)
    {
     String openSubRoot = childRoot.getAttribute("class");
     if(openSubRoot.equalsIgnoreCase("liClosed"))
     {
      String path = ".//*[@id='tree1']/li["+rootSize+"]/ul/li["+subRootSize+"]/span";
      openTree(path);
     }
     subRootSize = subRootSize+1;
    }
   }
   rootSize = rootSize+1;
  }
 }

 public void openTree(String xpath) throws InterruptedException
 {
  driver.findElement(By.xpath(xpath)).click();
  Thread.sleep(3000);
 }
}

Tuesday 24 September 2013

Handling different Javascript prompts using Selenium WebDriver

Purpose: Handling different Javascript prompts using Selenium WebDriver

We always come across different javascript prompts while accessing different websites. Follwoing code will help to handle while automating those functionalities.

This requires one web page which contains different ways to generate Javascript prompts. Following code for Web page

jscriptpopup.html

<html>
<head>
<script type="text/javascript">
function show_alert()
{
alert("This is a JavaScript Alert Box!")
document.getElementById("result").innerHTML="Alert Prompted";
}
function show_confirm()
{
 var r=confirm("Press a button");
 if (r==true)
   {
   x="Pressed OK Button!";
   document.getElementById("result").innerHTML=x;
   }
 else
   {
   x="Pressed Cancel Button!";
   document.getElementById("result").innerHTML=x;
   }
}
function show_prompt()
{
 var v = prompt("Enter Value");
 if(v!=null)
  document.getElementById("result").innerHTML="Entered Value is "+v;
  else
 document.getElementById("result").innerHTML="Pressed Cancel button";
}
</script>
</head>
<body>
<input type="button" onclick="show_alert()" value="Show Alert Box" />
<input type="button" onclick="show_confirm()" value="Show Confrim Box" />
<input type="button" onclick="show_prompt()" value="Show Prompt Box" />
<div id="result"></div>
</body>
</html>

Please save the above code and provide the location of the file in WebDriver code

Webdriver Code:

 import org.openqa.selenium.By;
import org.openqa.selenium.Alert;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class JscriptPop {

 public String baseURL = "file:///D:/Raju/Projects/Automation/Sample/jscriptpopup.html"; // Location of the source file
 public Alert alert;
 public static WebDriver driver=new FirefoxDriver();

 @BeforeMethod
 public void setup()
 {
  driver.get(baseURL);
 }

 @AfterMethod
 public void tear()
 {
  driver.quit();
 }

 @Test
 public void testJscriptPop() throws InterruptedException
 {
  // Clicking Alert Box
  driver.findElement(By.xpath("//input[@value='Show Alert Box']")).click();
  Thread.sleep(3000);
  alert = driver.switchTo().alert();
  Thread.sleep(3000);
  // To click ok
  alert.accept();
  Thread.sleep(3000);

  // Clicking Confirm Box
  driver.findElement(By.xpath("//input[@value='Show Confrim Box']")).click();
  Thread.sleep(3000);
  alert = driver.switchTo().alert();
  Thread.sleep(3000);
  // To click OK
  alert.accept();
  Thread.sleep(3000);

  // Clicking Confirm Box
  driver.findElement(By.xpath("//input[@value='Show Confrim Box']")).click();
  Thread.sleep(3000);
  alert = driver.switchTo().alert();
  Thread.sleep(3000);
  // To click Cancel
  alert.dismiss();
  Thread.sleep(3000);

  // Clicking Confirm Box Prompt Button
  driver.findElement(By.xpath("//input[@value='Show Prompt Box']")).click();
  Thread.sleep(3000);
  alert = driver.switchTo().alert();
  alert.sendKeys("Test value");
  Thread.sleep(3000);
  // To click OK
  alert.accept();
  Thread.sleep(3000);

  // Clicking Confirm Box Prompt Button
  driver.findElement(By.xpath("//input[@value='Show Prompt Box']")).click();
  Thread.sleep(3000);
  alert = driver.switchTo().alert();
  Thread.sleep(3000);
  // To click Cancel
  alert.dismiss();
  Thread.sleep(3000);
 }
}

Sunday 22 September 2013

Capturing contents of a Table using Selenium Web Driver

Purpose: Capturing contents of a Table using Selenium Web Driver

Some times we may need to capture each and every value from a table while automating. Following example will help to implement the requirement.

This example also will help us to capture nth Row & Column value.

import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class TableExample {
  public String baseURL = "http://accessibility.psu.edu/tablecomplexhtml";
  public WebDriver driver = new FirefoxDriver();
 
  @BeforeMethod
  public void setup()
  {
   driver.get(baseURL);
  }
 
  @AfterMethod
  public void tear()
  {
   driver.quit();
  }
 
  @Test
  public void testTableExample()
  {
   List<WebElement> rows = driver.findElements(By.xpath(".//*[@id='node-281']/div/div[1]/div[2]/table/tbody/tr")); // Returns the number of Rows
   List<WebElement> cols = driver.findElements(By.xpath(".//*[@id='node-281']/div/div[1]/div[2]/table/tbody/tr[1]/td")); // Returns the number of Columns
  
   // Static XPath of a single TR and TD is ".//*[@id='node-281']/div/div[1]/div[2]/table/tbody/tr[1]/td[1]"
  
   // code to fetch each and every value of a Table
  
   for(int rowNumber = 1; rowNumber <= rows.size(); rowNumber++)
   {
    for(int colNumber = 1; colNumber <= cols.size(); colNumber++)
    {
     System.out.print(driver.findElement(By.xpath(".//*[@id='node-281']/div/div[1]/div[2]/table/tbody/tr["+rowNumber+"]/td["+colNumber+"]")).getText()+"  ");
    }
    System.out.println("\n");
   }
  
   System.out.println("###############################################################################\n");

  // nth element value of a table
  
   System.out.println(driver.findElement(By.xpath(".//*[@id='node-281']/div/div[1]/div[2]/table/tbody/tr["+rows.size()+"]/td["+cols.size()+"]")).getText());
  
  }
}

Wednesday 18 September 2013

Performing Mouse Double Click using Selenium Web Driver

Perpose: Performing Mouse Double Click using Selenium Web Driver

Some web applications may need to perform double click to fire the action. Following code will help how to implement Mouse Double Click using Selenium.

In the following example, page contans a div and if we perform single click noting is going to happen but when we perform double click Map will be zoomed.


import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class DoubleClick {
 public String baseURL = "http://openlayers.org/dev/examples/click.html";
 public WebDriver driver = new FirefoxDriver();
 public WebElement element;
 public String title;
 public Actions action = new Actions(driver);
 @BeforeTest
 public void launchBrowser()
 {
  driver.get(baseURL);
 }

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

 @Test
 public void doubleClick() throws InterruptedException
 {
  element = driver.findElement(By.xpath(".//*[@id='OpenLayers_Map_2_OpenLayers_ViewPort']"));
  element.click();// For single click Map will not load
  System.out.println("Single Click performed");
  Thread.sleep(3000);
  Action doubleClick = action.doubleClick(element).build();
  doubleClick.perform();// After performing double click Map will load
  System.out.println("Double Click performed");
  Thread.sleep(10000);
  doubleClick.perform();// After performing double click Map will load
  System.out.println("Double Click performed");
  Thread.sleep(10000);
 }
}

Capturing the Sub Menu values using Selenium Web Driver

Purpose: Capturing the Sub Menu values using Selenium Web Driver

Some times we may need to validate the valus of Sub-menus. If static it is easy to implement but some times we may need to validate the dynamic data.

Following code will help to accomplish this:

import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class DropDownCSSMenu {
 public String baseURL = "http://demo.lateralcode.com/css-drop-down-menus/";
 public WebDriver driver = new FirefoxDriver();
 public Actions action = new Actions(driver);
 public List<WebElement> elements;
 public int size;

 @BeforeTest
 public void launchBrowser()
 {
  driver.get(baseURL);
 }

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

 @Test
 public void test() throws InterruptedException
 {
  WebElement home = driver.findElement(By.linkText("Home"));
  WebElement about = driver.findElement(By.linkText("About"));
  WebElement contact = driver.findElement(By.linkText("Contact"));
 
  action.moveToElement(home).build().perform();//MouseOver of Menu
  driver.findElement(By.xpath("//*[@id='menu']/ul/li[1]/ul/li[1]/a")).click(); //Clicking Sub Menu
  Thread.sleep(3000);
  elements = driver.findElements(By.xpath(".//*[@id='menu']/ul/li[1]/ul/li/a"));
  for (WebElement element : elements) {
   System.out.println(element.getText());
  }
 
  action.moveToElement(about).build().perform();//MouseOver of Menu
  driver.findElement(By.xpath("//*[@id='menu']/ul/li[2]/ul/li[1]/a")).click(); //Clicking Sub Menu
  Thread.sleep(3000);
  elements = driver.findElements(By.xpath(".//*[@id='menu']/ul/li[2]/ul/li/a"));
  for (WebElement element : elements) {
   System.out.println(element.getText());
  }
 
  action.moveToElement(contact).build().perform();//MouseOver of Menu
  driver.findElement(By.xpath("//*[@id='menu']/ul/li[3]/ul/li[1]/a")).click(); //Clicking Sub Menu
  Thread.sleep(3000);
  elements = driver.findElements(By.xpath(".//*[@id='menu']/ul/li[3]/ul/li/a"));
  for (WebElement element : elements) {
   System.out.println(element.getText());
  }
 }
}

Clicking on CSS Drop Down sub Menu using Selenium WebDriver

Purpose: Clicking on CSS Drop Down sub Menu using Selenium WebDriver

Some times we encounter to test different types of Web Sites which have some dynamic features and automating such features are little bit difficult. One of such example is CSS Drop Down Menus & Sub-menus.

Following code will help to handle CSS Drop Down Menus & Sub-menus:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class DropDownCSSMenu {
 public String baseURL = "http://demo.lateralcode.com/css-drop-down-menus/";
 public WebDriver driver = new FirefoxDriver();
 public Actions action = new Actions(driver);

 @BeforeTest
 public void launchBrowser()
 {
  driver.get(baseURL);
 }

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

 @Test
 public void test() throws InterruptedException
 {
  WebElement home = driver.findElement(By.linkText("Home"));
  WebElement about = driver.findElement(By.linkText("About"));
  WebElement contact = driver.findElement(By.linkText("Contact"));
 
  action.moveToElement(home).build().perform();//MouseOver of Menu
  driver.findElement(By.xpath("//*[@id='menu']/ul/li[1]/ul/li[1]/a")).click(); //Clicking Sub Menu
  Thread.sleep(3000);
 
  action.moveToElement(about).build().perform();//MouseOver of Menu
  driver.findElement(By.xpath("//*[@id='menu']/ul/li[2]/ul/li[1]/a")).click(); //Clicking Sub Menu
  Thread.sleep(3000);
 
  action.moveToElement(contact).build().perform();//MouseOver of Menu
  driver.findElement(By.xpath("//*[@id='menu']/ul/li[3]/ul/li[1]/a")).click(); //Clicking Sub Menu
  Thread.sleep(3000);
 }
}

Tuesday 17 September 2013

Executing Sequence of Selenium Test Cases in a Cusomized Sequence

Purpose: Executing Sequence of Selenium WebDriver Test Cases in a Cusomized Sequence

While automating any application we come across a situation where we need to execute multiple test cases in a particular sequence. But when it comes to execute the test cases they will execute randomly. In order to execute the test cases in our pre requisite order we need to pass a parameter to @Test method priority and a value(Lower priorities will be scheduled first).

Following code will be useful to accomplish the requirement:
 
 import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class OrderOfTestCase {

 public String baseURL = "http://www.google.com";
 public WebDriver driver = new FirefoxDriver();

 @BeforeTest
 public void launchBrowser()
 {
  driver.get(baseURL);
 }

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

 @BeforeMethod
 public void getTitle()
 {
  System.out.println(driver.getTitle());
 }
 @AfterMethod
 public void goToPreviousPage()
 {
  driver.navigate().back();
 }

 @Test(priority = 0)
 public void images() throws InterruptedException
 {
  driver.findElement(By.linkText("Images")).click();
  Thread.sleep(3000);
  System.out.println(driver.getTitle());
 }

 @Test(priority = 1)
 public void maps() throws InterruptedException
 {
  driver.findElement(By.linkText("Maps")).click();
  Thread.sleep(3000);
  System.out.println(driver.getTitle());
 }

 @Test(priority = 2)
 public void mail() throws InterruptedException
 {
  driver.findElement(By.linkText("Gmail")).click();
  Thread.sleep(3000);
  System.out.println(driver.getTitle());
 }
}

Monday 16 September 2013

Extracting ZIP file programatically with the help of Java

Purpose: Extracting ZIP file programatically with the help of Java

Some time we may need to extract zip file and read the contents. Following code will help how to extract .zip files. I collected this program form some blog while searching and I want to share this to all through my blog.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class FileUnZip {
 public static void main(String[] args)
 {
  unzip("D://LatestSample.zip", "D://tmp");
  System.out.println("Unzip Completed");
 }

 public static void unzip(String zipFile,String outputPath){
  
        if(outputPath == null)
            outputPath = "";
        else
            outputPath+=File.separator;
        System.out.println(outputPath+=File.separator);
        // 1.0 Create output directory
        File outputDirectory = new File(outputPath);
        if(outputDirectory.exists())
            outputDirectory.delete();
        outputDirectory.mkdir();
        // 2.0 Unzip (create folders & copy files)
        try {
            // 2.1 Get zip input stream
            ZipInputStream zip = new ZipInputStream(new FileInputStream(zipFile));
            ZipEntry entry = null;
            int len;
            byte[] buffer = new byte[1024];
            // 2.2 Go over each entry "file/folder" in zip file
            while((entry = zip.getNextEntry()) != null){
                if(!entry.isDirectory()){
                    System.out.println("-"+entry.getName());                       
                    // create a new file
                    File file = new File(outputPath +entry.getName());
                    // create file parent directory if does not exist
                    if(!new File(file.getParent()).exists())
                        new File(file.getParent()).mkdirs();
                    // get new file output stream
                    FileOutputStream fos = new FileOutputStream(file);
                    // copy bytes
                    while ((len = zip.read(buffer)) > 0) {
                        fos.write(buffer, 0, len);
                    }
                    fos.close();
                }
                zip.close();
            }
        }catch (FileNotFoundException e) {
                e.printStackTrace();
        } catch (IOException e) {
                e.printStackTrace();
        }
 }
}

Wednesday 11 September 2013

Adding An Image to Word programatically using Java

Purpose: Adding An Image to Word programatically using Java

Following Code will allow to add an Image to a Word file using Java from local or web based source.


import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import word.api.interfaces.IDocument;
import word.w2004.Document2004;
import word.w2004.elements.BreakLine;
import word.w2004.elements.Image;
import word.w2004.elements.Paragraph;
public class AddImageToWord
{
    public static void main(String[] args) throws Exception
    {
     String img = "";
      IDocument doc = new Document2004();
      doc.addEle(Paragraph.with("Image from Web URL:").create());
      doc.addEle(new BreakLine(2)); //Add two break lines
      img = Image.from_WEB_URL("http://www.google.com/images/logos/ps_logo2.png").setHeight("100").setWidth("300").create().getContent();
      doc.addEle(img);
      doc.addEle(new BreakLine(2)); //Add two break lines
      doc.addEle(Paragraph.with("Image from Hard Disk:").create());
      doc.addEle(new BreakLine(2)); //Add two break lines
      String wh = Image.from_FULL_LOCAL_PATHL("D://Screen.png").getOriginalWidthHeight();
      String[] temp = wh.split("#");
      System.out.println(temp[0]);
      System.out.println(temp[1]);
      img = Image.from_FULL_LOCAL_PATHL("D://Screen.png").setHeight("300").setWidth("500").create().getContent();
      doc.addEle(img);
     
      File fileObj = new File("D://Java2word_allInOne.doc");
      PrintWriter writer = null;
      try {
          writer = new PrintWriter(fileObj);
      } catch (FileNotFoundException e) {
          e.printStackTrace();
      }
      String myWord = doc.getContent();
      writer.println(myWord);
      writer.close();
    }
}


 

Tuesday 10 September 2013

How to add text to a word file using Java

Purpose: How to add text to a word file using Java


Following code will help you to Add text to a Word file programatically.

import java.io.*;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import java.io.FileOutputStream;
public class AddToWord
{
    public static void main(String[] args) throws IOException, InvalidFormatException
    {
        XWPFDocument document = new XWPFDocument();
        XWPFParagraph paragraph = document.createParagraph();
        XWPFRun run = paragraph.createRun();
        run.setText("Sample Text to add a word file programatically");
        run.setFontSize(33);
        FileOutputStream out = new FileOutputStream("Success.doc");
        document.write(out);
        out.close();
    }
}

Generating previous day's Date using Java

Purpose: Generating previous day's Date using Java


Some times we may need to use date in different situations in different applications dynamically. That is very simple and we can use the methods of Date/Calender class. But some times we may need to capture previous day's date.

Following code will be useful to capture previous day's date.

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class PreviousDate {
 public static void main(String[] args)
 {
//     Selecting Previous Date --- Start
    
     DateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy");
     Date date = new Date();
     Calendar cal = new GregorianCalendar();
     cal.setTime(date);
     cal.add(Calendar.DAY_OF_YEAR,-1);
     Date oneDayBefore= cal.getTime();
     System.out.println();
     System.out.println("Previous Day's Date in dd/mm/yyyy format: "+dateFormat.format(oneDayBefore).toString());
//     Selecting Previous Date --- End
 }
}
 

Monday 9 September 2013

Capturing an Element Screenshot using Selenium Webdriver

Purpose: Capturing an Element Screenshot using Selenium Webdriver

Following Code will help to capture a particular element form a Webpage.

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.OutputType;
import org.openqa.selenium.Point;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class CaptureElement {
 static WebDriver driver;
 // Browser startup
 @BeforeClass
 public void setup() {
  driver = new FirefoxDriver();
 }

 @Test
 public void gomezTest() throws InterruptedException, IOException {
  // Capturing Required Element Screen shot
  driver.get("http://www.google.com");
  WebElement ele = driver.findElement(By.id("hplogo"));  
  try
  {
  File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
  BufferedImage  fullImg = ImageIO.read(screenshot);
  //Get the location of element on the page
  Point point = ele.getLocation();
  //Get width and height of the element
  int eleWidth = ele.getSize().getWidth();
  int eleHeight = ele.getSize().getHeight();
  //Crop the entire page screenshot to get only element screenshot
  BufferedImage eleScreenshot= fullImg.getSubimage(point.getX(), point.getY(), eleWidth, eleHeight);
  ImageIO.write(eleScreenshot, "png", screenshot);
  //Copy the element screenshot to disk
  FileUtils.copyFile(screenshot, new File("GoogleLogo_screenshot.png"));
  }
  catch(Exception e)
  {
   e.printStackTrace();
  }
 }
 @AfterClass
 public void tear() {
  driver.close();
 }

Capturing Entire Page Screenshot using Selenium Webdriver

Purpose: Capturing Entire Page Screenshot using Selenium Webdriver

Following code will help to take the screenshot entire page of any webpage.

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TakeScreenshot {
 static WebDriver driver;
 // Browser startup
 @BeforeClass
 public void setup() {
  driver = new FirefoxDriver();
 }
 @Test
 public void gomezTest() throws InterruptedException, IOException {
  // Capturing Screen shot
  driver.get("http://www.google.com");
  //Get entire page screenshot
  try
  {
   File screenshotFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

  //Copy the element screenshot to disk
  FileUtils.copyFile(screenshotFile, new File("\\GoogleLogo_screenshot.png"));
  }
  catch(Exception e)
  {
   e.printStackTrace();
  }
 }
 @AfterClass
 public void tear() {
  driver.close();
 }
}