My Thoughts: Java
Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Thursday, March 6

On test case failure take a screenshot with Selenium WebDriver


Don't you think "A picture is worth a thousand words.." :)

It is always(at least in most of the cases :P) better to take screenshot of webpage when the test run fails.

Because with one look at the screenshot we can get an idea of where exactly the script got failed. Moreover reading screenshot is easier compare to reading 100's of console errors :P

Here is the sample code to take screenshot of webpage
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

FileUtils.copyFile(scrFile, new File("PathOnLocalDrive")

To get screenshot on test failure , we should put the entire code in try-catch block . In the catch block make sure to copy the above screenshot code.

In my example I am trying to register as a new user. For both first and last name fields I have used correct locator element whereas for emailaddress field I have used wrong locator element i.e name("GmailAddress1").

So when I run the script , test failed and I got the screenshot with pre filled first and last names but not email address.

Here is the sample code :
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.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class TakeScreenshot {
 
   WebDriver driver;
 
 @BeforeTest
 public void start(){
  driver = new FirefoxDriver();
 }
 
 @Test
 public void Test() throws IOException{
 try{
  driver.get("https://mail.google.com/");
  driver.findElement(By.id("link-signup")).click();
  driver.findElement(By.name("FirstName")).sendKeys("First Name");
  driver.findElement(By.name("LastName")).sendKeys("Last Name");
  driver.findElement(By.name("GmailAddress1")).sendKeys("GmailAddress@gmail.com");
  
 }catch(Exception e){
  //Takes the screenshot  when test fails
     File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
     FileUtils.copyFile(scrFile, new File("C:\\Users\\Public\\Pictures\\failure.png"));
   
  }
 }
}
And here is the screenshot of webpage on test failure


Reference  :
http://docs.seleniumhq.org/docs/04_webdriver_advanced.jsp#taking-a-screenshot
http://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/TakesScreenshot.html

Between have a great day ...!!! :)


Saturday, October 5

Extract and Verify the text from image using Selenium WebDriver


Firstly WebDriver does not support the functionality of extracting text from an image , at least as of now  :) .
So if we would like to extract and verify text from an image then we should use OCR (Optical Character Recognition) technology.

Coming to OCR , here is one of the nice article , and it says :

OCR software extracts all the information from the image into easily editable text format.Optical character recognition (OCR) is a system of converting scanned printed/handwritten image files into its machine readable text format. OCR software works by analyzing a document and comparing it with fonts stored in its database and/or by noting features typical to characters. 

There are good no.of free OCR software tools . If your preferred program is Java then you can use one of the Java OCR libraries to extract text from an image. I used ASPRISE OCR java library in this article. To work with  ASPRISE OCR library , follow the below simple two steps.

  1. Download "Asprise OCR" libraries , depending on the operating system you are using .
  2. Unzip the downloaded  folder and add the aspriseOCR jar file to your working directory . If you want you can download the single jar file from here .
  3. Also Copy the "AspriseOCR.dll" file from unzipped downloaded folder and save it  under "C:\Windows\System32" .
Now you are ready to go  :P .

Look at the below sample image .



And here is the sample code to read the text from above image :

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.asprise.util.ocr.OCR;

public class ExtractImage {
 
 WebDriver driver;
 
 @BeforeTest
  public void setUpDriver() {
   driver = new FirefoxDriver();
  }
 
 @Test
 public void start() throws IOException{
   
 /*Navigate to http://www.mythoughts.co.in/2013/10/extract-and-verify-text-from-image.html page
  * and get the image source attribute
  *  
  */  
 driver.get("http://www.mythoughts.co.in/2013/10/extract-and-verify-text-from-image.html");
 String imageUrl=driver.findElement(By.xpath("//*[@id='post-body-5614451749129773593']/div[1]/div[1]/div/a/img")).getAttribute("src");
 System.out.println("Image source path : \n"+ imageUrl);

 URL url = new URL(imageUrl);
 Image image = ImageIO.read(url);
 String s = new OCR().recognizeCharacters((RenderedImage) image);
 System.out.println("Text From Image : \n"+ s);
 System.out.println("Length of total text : \n"+ s.length());
 driver.quit();
    
 /* Use below code If you want to read image location from your hard disk   
  *   
   BufferedImage image = ImageIO.read(new File("Image location"));   
   String imageText = new OCR().recognizeCharacters((RenderedImage) image);  
   System.out.println("Text From Image : \n"+ imageText);  
   System.out.println("Length of total text : \n"+ imageText.length());   
      
   */ 
}

}

Here is the output of the above program:

Image source path :
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgB6j3Yn6-LlRNqfQp1QvtINI0H9YbPfzY228Qmt72DdJhfy3h9ort0tySJcwdX9KVZGOzR8XHHrIIRo18_VpmMsn8LtZuYAn1ulTP48R2qZKtDIp3JNX5LlR8IAE0a2CC0GN4ZWXOy3qnV/s1600/love.jpg

Never M2suse the O, ne
Who Likes You
Never Say Busy To Th,e One
Who Needs You
Never cheat The One
Who ReaZZy Trust You,
Never foJnget The One
Who Zways Remember You.

Length of total text :
175



Thats for now. Have a great weekend ..!! :)

Reference :
http://asprise.com/product/ocr/javadoc/index.html




Thursday, May 31

WebDriver(Selenium2) : Extract text from PDF file using java


Verifying PDF content is also part of testing.But in WebDriver (Selenium2) we don't have any direct methods to achieve this.

If you would like to extract pdf content then we can use Apache PDFBox  API.

Download the Jar files and add them to your Eclipse Class path.Then you are ready to extract text from PDF file .. :)

Here is the sample script which will extract text from the below PDF file.
http://www.votigo.com/pdf/corp/CASE_STUDY_EarthBox.pdf
import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.util.PDFTextStripper;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Reporter;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class ReadPdfFile {
 
 WebDriver driver;
 
  @BeforeTest
  public void setUpDriver() {
   driver = new FirefoxDriver();
   Reporter.log("I am done");
     }
  
  @Test
  public void start() throws IOException{
  driver.get("http://votigo.com/overview_collateral.pdf");
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  URL url = new URL(driver.getCurrentUrl()); 
  BufferedInputStream fileToParse=new BufferedInputStream(url.openStream());

  //parse()  --  This will parse the stream and populate the COSDocument object. 
  //COSDocument object --  This is the in-memory representation of the PDF document

  PDFParser parser = new PDFParser(fileToParse);
  parser.parse();

  //getPDDocument() -- This will get the PD document that was parsed. When you are done with this document you must call    close() on it to release resources
  //PDFTextStripper() -- This class will take a pdf document and strip out all of the text and ignore the formatting and           such.

  String output=new PDFTextStripper().getText(parser.getPDDocument());
  System.out.println(output);
  parser.getPDDocument().close(); 
  driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);
  }

}
Here is the output of above program :
EarthBox a Day Giveaway 
Objectives 
EarthBox wanted to engage their Facebook 
audience with an Earth Day promotion that would 
also increase their Facebook likes. They needed a 
simple solution that would allow them to create a 
sweepstakes application themselves. 
 
 
Solution 
EarthBox utilized the Votigo 
platform to create a like-
gated sweepstakes. Utilizing a 
theme and uploading a custom graphic they 
were able to create a branded promotion. 
 
 
Details 
• 1 prize awarded each day for the entire Month of April  
• A grand prize given away on Earth Day  
• Daily winner announcements on Facebook 
• Promoted through email newsletter blast  
 
Results (4 weeks) 
• 6,550 entries 
 
Facebook  

Tuesday, March 20

Dangling meta character '?' near index 0 ? ^

Hey ,

After a long long time writing my post again.:)

Did you ever see the error message like this when you run your script

"Dangling meta character '?' near index 0 ? ^"

I happened to see this when I have below piece of code :
String str[]=page.split("?");


And the solution is very simple
String str[]=page.split("\\?");

Have a Good Day ..!!

Thursday, January 5

Connecting to DataBase using WebDriver


Our scripts are not just clicking on links we will do more.Yes , of course more :) and one of that "more" is "checking DB".
But Web Driver cannot directly connect to Database. You can only interact with your Browser using Web Driver.SO if you want to connect to Database then you need to write piece of code which will let you to connect to Database to perform further actions(insertion, deletion, updation).

For this we use JDBC("Java Database Connectivity").The JDBC API is a Java API for accessing virtually any kind of tabular data.The value of the JDBC API is that an application can access virtually any data source and run on any platform with a Java Virtual Machine.

In simplest terms, a JDBC technology-based driver ("JDBC driver") makes it possible to do three things:

1.Establish a connection with a data source
2.Send queries and update statements to the data source
3.Process the results

1.Establish a connection with a data source
The traditional way to establish a connection with a database is to call the method
DriverManager.getConnection(URL,  "myLogin", "myPassword" )
URL :   jdbc:<subprotocol>:<subname>
<subprotocol>-the name of the driver or the name of a database connectivity mechanism
<subname> - The point of a subname is to give enough information to locate the data source .(Includes IP address , Port number and exact name of DataSource)

For connecting to MYSQL URL will be
jdbc:mysql:<<subname>>

2.Send queries and update statements to the data source
A Statement object is used to send SQL statements to a database over the created connection in Step 1.
Statement-created by the Connection.createStatement methods. A Statement object is used for sending SQL statements with no parameters.
PreparedStatement-created by the Connection.prepareStatement methods. A PreparedStatement object is used for precompiled SQL statements. These can take one or more parameters as input arguments (IN parameters).
CallableStatement-created by the Connection.prepareCall methods. CallableStatement objects are used to execute SQL stored procedures
In Short
createStatement methods-for a simple SQL statement (no parameters)
prepareStatement methods-for an SQL statement that is executed frequently
prepareCall methods-for a call to a stored procedure

3.Process the results
A ResultSet is a Java object that contains the results of executing an SQL query.We will have separate post on it.The JDBC API provides three interfaces for sending SQL statements to the database

Here is the code for it.

//Load the mysql driver dynamically
Class.forName("com.mysql.jdbc.Driver");
//Establish connection
Connection con = DriverManager.getConnection("jdbc:mysql:wombat", "myLogin", "myPassword");
//Create statement Object
Statement stmt = con.createStatement();
//Execute the query and store the results in the ResultSet object
ResultSet rs = stmt.executeQuery("SELECT id, name, salary FROM employee");
//Printing the column values of ResultSet
while (rs.next()) {
 int x = rs.getInt("id");
 String s = rs.getString("name");
 float f = rs.getFloat("salary");
}

Tuesday, October 11

Running JavaScript in the Java platform


Java is one of the powerful language.And we can do so mang things with it .

If you want to integrate javascript code with your javacode then it is very simple.
the steps are
1. Create ScriptEngineManager object
2.Get the ScriptEngine object from scriptEngineManager
3.Evaluate a script using the ScriptEngine object.

Here is the sample code :
You need to include "javax.script" package.

The scripting API consists of interfaces and classes that define Java Scripting Engines and provides a

framework for their use in Java applications.


import javax.script.*;

public class Javascript {


public static void main(String[] args) {
// Creating ScriptEngineManager
ScriptEngineManager mgr = new ScriptEngineManager();
//getting the ScriptEngine object
 ScriptEngine jsEngine = mgr.getEngineByName("JavaScript");
 try {
//Evaluate the script.For this we are using eval method
   jsEngine.eval("print('Hello, world!')");
 

 } catch (ScriptException ex) {
     ex.printStackTrace();
 }  

 try {
//We can import even java pacjages from script
   jsEngine.eval("importPackage(javax.swing);" +
       "var optionPane = " +
       "  JOptionPane.showMessageDialog(null, 'Hello, world!');");
 } catch (ScriptException ex) {
   ex.printStackTrace();
 }

}

}