Saturday, 28 February 2015

CREATE PDF FILES USING iTextPdf Jar LIBRARY - BASIC EXAMPLE

iText is an API for creating and manipulating PDF files in java.

Note: you must add itextpdf jar file to your build path in order to use itext pdf API.

Download Link:

itextpdf-5.5.5.jar

(or)

Using Maven:

If you are interested to use a maven dependency - add the following to your dependencies list:

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.5</version>
</dependency>

Note: you can continue reading this post even if you don't no maven.

If you are new to maven - click here ---> What is Maven & how to use it?

This post explains the creation of PDF with a specifed format like this:

Example PDF :  CWCReport.pdf

Important Classes:

Mostly all the classes I am using here are from same package:
com.itextpdf.text package


>>Document - Objects of this classes resembles the real world PDF document.

//creating an instance of Document
Document document = new Document();

Document class has different overloaded constructors. I am using one which specifies the page size of A4.

//creating an instance of Document
Document document = new Document(PageSize.A4.rotate());

Here,
>>PageSize  - class having all standard page formats like A1-A10 , B1-B10

rotate() method - creates a landscape PDF.

>>PdfWriter

* After defining a Document object - define PdfWriter object

//creating PdfWriter instance using a static method getInstance

//You can specify the path for PDF file creating using FileOutputStream
 OutputStream file=new FileOutputStream(new File("/home/dinesh/CWCReport.pdf"));

For File pass you pdf path where you want to create on your file system.

Note: On windows, you may have you give \\ (double slashes) for file's path.
Like: c:\\home\\pdfs\\create.pdf

//Parameters document & FileOutStream file
PdfWriter.getInstance(document, file);

Defining Document Information using document object:

using document object - we can define the pdf author, subject, title, & creation date.

                 //defining an author
                document.addAuthor("Dinesh Dontha");

                 //defining a subject
                document.addSubject("CWC Matches List");
   
                // title on the document-window
                document.addTitle("CWC - Schedule");

                // creation date
                document.addCreationDate();

Opening a Document:

Note: Inorder to write content into the pdf document - you must open it first

//open a document
document.open();

Adding a Paragraph:

>> Paragraph

Objects of this classes resembles real-object Paragraphs - so to create a paragraph use an object of it.

Paragraph class extends a Phrase class.

Phrase is like a sentence.

Defining Paragraphs :

//create a paragraph - using a String argument
Paragraph para2 = new Paragraph("para1....");

//create a paragraph -using a Phrase

>>Phrase
 
Phrase is a series of chunks

Here, we also have Chunk class

Chunk is the smallest significant part of the text that can be added to
document.

//creating a phrase with no parameters
Phrase phrase = new Phrase();

//Phrase with a specified font
Phrase title =new Phrase("phrase1",new Font(FontFamily.HELVETICA, 32));

Note:

>>Font  class 

 FontFamily  is an ENUM defined inside Font class

//creating Paragraph by passing Phrase instance
Paragraph para2 = new Paragraph(phrase);

//creating Paragraph with specified Font
Paragraph para2 = new Paragraph("Paragraph Text", new Font(FontFamily.HELVETICA, 16));

 Adding New Blank Lines between Paragraphs:

Using Chunk class

>>Chunk

//adds a blank line
document.add(Chunk.NEWLINE);

Creating a table:

Use  PdfPTable class instance

>>PdfPTable

While creating the instance of PdfPTable - we can define the number of columns in that table

//create a table with 2 columns
PdfPTable table = new PdfPTable(2);

Using this instance, you can set some global properties for this table elements

//setting the table width in the document
table.setWidthPercentage(100);

Here, table extends complete width of page.

 //setting a padding for all cells
table.getDefaultCell().setPadding(10);

//setting an align of cell data      
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);

Defining Table Cells:

we can add table cells using  addCell() method of PdfPTable class

//adding a basic cell using addCell() method

table.addCell("Match Date");
table.addCell("Between");

(or)

you can define table cells using PdfPCell class

>>PdfPCell
PdfPCell class has many overloaded constructors

//with no parameters
PdfPCell cell1 = new PdfPCell();

//with a Phrase paramter -defines the cell content with Phrase
Phrase p1 =new Phrase("Cell Content");

//defining cell with phrase as content
PdfPCell cell = new PdfPCell(p1);

Once defined a cell instance - we can override the properties that are
globally defined- defined on table i.e, PdfPTable object.

//overrides padding defined on table object
cellHeader2.setPadding(20);

**Note:
 //setting properties on PdfPTable object-"table" are not applicable for this particular cell defined using PdfPCell class

i.e,       table.getDefaultCell().setPadding(10);

Here, padding for all cells is 10. But, for this cell - it is 20.

//similarly this overrides - alignment property set on table(PdfPTable) object
cellHeader2.setHorizontalAlignment(Element.ALIGN_CENTER);

Example:

All the data in this example are stored in a Map object.

Note: finally close the document object and file stream object.

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Font.FontFamily;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

/* GeneratePdf.java
 * Created on 26-Sep-2014
 */

public class CreatePdf {

 public static void main(String[] args) {

try {

 // creating a file stream object
 OutputStream file = new FileOutputStream(new File(
   "/home/dinesh/CWCReport.pdf"));

 // creating a document object - with A4 size
 // please see the effect of rotate() method -with and without it

 // rotate() method -creates a pdf in landscape format
 Document document = new Document(PageSize.A4.rotate());

 // must create a PdfWriter object -pass document and file output
 // stream
 PdfWriter.getInstance(document, file);

 // creating document info
 document.addAuthor("Dinesh Dontha");
 document.addSubject("CWC Matches List");
 document.addTitle("CWC - Schedule");
 document.addCreationDate();

 // must open a document -to put content
 document.open();

 // creating a Phrase
 Phrase title = new Phrase("Cricket World Cup-2015- Schedule",
   new Font(FontFamily.HELVETICA, 32));

 // creating a Paragrapgh with Phrase as parameter
 Paragraph para1 = new Paragraph(title);
 para1.setAlignment(Element.ALIGN_CENTER);

 // adding paragraph to document -this main heading for document.
 document.add(para1);

 // adding a blank line after - heading/title
 document.add(Chunk.NEWLINE);

 // creating a paragraph
 Paragraph para2 = new Paragraph(
   "Next upcoming league matches of Team India in the "
     + "giagantic Cricket World Cup-2015", new Font(
     FontFamily.HELVETICA, 16));
 para2.setAlignment(Element.ALIGN_LEFT);

 // adding a paragraph - this is infact the first paragraph in this
 // exxample
 document.add(para2);

 // adding a blank line after - first paragraph
 document.add(Chunk.NEWLINE);

 // adding all cell data to a Map object
 Map indiaMatches = new HashMap<>();

 indiaMatches.put("Sunday, March 6th 2015", "INDIA VS WEST INDIES");
 indiaMatches.put("Sunday, March 10th 2015", "INDIA VS IRELAND");
 indiaMatches.put("Sunday, March 14th 2015", "INDIA Vs ZIMBABWE");

 // Define a PDF table with 2 columns - Match Date & Between column
 // Names
 PdfPTable table = new PdfPTable(2);

 // Setting global table cell properties
 table.setWidthPercentage(100);
 table.getDefaultCell().setPadding(10);
 table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);

 // table header creation -using PdfPCell class

 // creating table header -cell -first column - Match Date
 Phrase matchDate = new Phrase("Match Date", new Font(
   FontFamily.HELVETICA, 14, Font.BOLD));
 // using PdfPCell class
 PdfPCell cellHeader1 = new PdfPCell(matchDate);
 cellHeader1.setBackgroundColor(BaseColor.ORANGE);
 cellHeader1.setPadding(10);
 cellHeader1.setHorizontalAlignment(Element.ALIGN_CENTER);
 table.addCell(cellHeader1);

 // creating table header -cell -second column - Between
 Phrase matchBetween = new Phrase("Match Between", new Font(
   FontFamily.HELVETICA, 14, Font.BOLD));
 // using PdfPCell class
 PdfPCell cellHeader2 = new PdfPCell(matchBetween);
 cellHeader2.setBackgroundColor(BaseColor.ORANGE);
 cellHeader2.setPadding(10);
 cellHeader2.setHorizontalAlignment(Element.ALIGN_CENTER);
 table.addCell(cellHeader2);

 // creating cell data -other than table column headers- using
 // addCell()
 // method of PdfPTable object
 for (Map.Entry entry : indiaMatches.entrySet()) {
  table.addCell(entry.getKey());
  table.addCell(entry.getValue());
 }

 // adding table to Pdf document
 document.add(table);

 // finally close - document & file stream
 document.close();
 file.close();

} catch (DocumentException | IOException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
}
}

}

Source Code: Download
Note: To run it successfully change the file path.

Saturday, 14 February 2015

PROGRAM FOR PRINTING ALL PERMUTATIONS OF A STRING - JAVA

Let us say -

String str = "abc"

As the length of the str is 3,  it should have 3! (factorial - 3*2*1) permutations - 6

[abc acb bca bac cab cba]


Example:

It builds all permutations recursively looping through all the characters - char by char

Here I have defined 3 custom methods - All 3 methods are looped after every character.

appendBefore -
appendAfter
appendMiddle

Go Over the code - it is commented properly

If not understood - just try to execute it once
package testing;

import java.util.ArrayList;
import java.util.List;

public class Permutations {

 /*
  * You will get n! (factorial) - permutations from this
  * 
  * Just like this Example: abc (3! = 6 permutations) 
  * [abc acb bac bca cab cbc]
  * 
  */
 static String str = "abcd";
 static char[] ch = str.toCharArray();
 static List s1 = new ArrayList<>();
 static List s2 = new ArrayList<>();

 public static void main(String[] args) {

  // s1 - list stores initial character from the string
  s1.add(String.valueOf(ch[0]));

  // recursive loop - char by char
  for (int k = 1; k < ch.length; k++) {

   // adds char at index 0 for all elements of previous iteration
   appendBefore(s1, ch[k]);
   
   // adds char at last index for all elements of previous iteration
   appendAfter(s1, ch[k]);
   
   /*adds char middle positions like a^b^C - if prev list stores
    * elements whose size() is 3 - then it would have 2 positions fill
    * say d is next char - d should be filled in _^_^_ _ positions are
    * previous permutations for 3 chars a,b,c(i.e 6 permutations
    */
   appendMiddle(s1, ch[k], k);
   
   /*for every iteration first clear s1 - to copy s2, which contains
   previous permutations*/
   s1.clear();
   
   /* now copy s2 to s1- then clear s2
   - this way finally s2 contains all the permutations*/
   for (int x = 0; x < s2.size(); x++) {
    s1.add(s2.get(x));
   }
   //shows how it is building - all iterations
   System.out.println(s1);
   s2.clear();
  }
  System.out.println("Total Permutations for given string "+str+" are "+s1.size());
 }

 private static void appendMiddle(List str, char ch, int positions) {
  for (int pos = 1; pos <= positions - 1; pos++) {
   for (int i = 0; i < str.size(); i++) {
    s2.add(str.get(i).toString().substring(0, pos) 
    + String.valueOf(ch)
    + str.get(i).toString().substring(pos, str.get(i).toString().length()));

   }
  }
 }

 private static void appendBefore(List str, char ch) {
  for (int i = 0; i < str.size(); i++) {
   s2.add(String.valueOf(ch) + str.get(i));
  }
 }

 private static void appendAfter(List str, char ch) {
  for (int i = 0; i < str.size(); i++) {
   s2.add(str.get(i) + String.valueOf(ch));
  }
 }

} 

Wednesday, 11 February 2015

READING EXCEL FILES USNG APACHE POI API

With Apache POI API, you can access various Microsoft Documents like MS Excel, MS Powerpoint,  and MS Word.

In this post, I am going to discuss - How to access Excel File using Apache POI API?

To Access excel files with different versions like 2003(xls) and 2007(xlsx) - we use POI-HSSF and POI-XSSF APIs respectively. HSSF is the POI Project's pure Java implementation of the Excel '97(-2007) file format. XSSF is the POI Project's pure Java implementation of the Excel 2007 (.xlsx) file format.

Note: You must include APACHE POI jar in you build path to access and manipulate excel files.This jar file contains all the required classes for various versions of excel files.

Download Link:  Apache POI jar


Important Classes(For Excel- 2007 & above):

XSSFWorkbook

XSSFSheet

XSSFRow

XSSFCell

 All these classes are in same package : org.apache.poi.xssf.usermodel


Important Classes(For Excel- 97-2003):

HSSFWorkbook

HSSFSheet

HSSFRow

HSSFCell

 All these classes are in same package : org.apache.poi.hssf.usermodel

Examples:

In examples, reading excel file -Sheet1 - row wise and printing on console

Sample Data- In Sheet1

Test Case Name Username Password Results IsExecute
APACHE_POI_TC testuser_1 Test@123 Pass Yes
APACHE_POI_TC testuser_2 Test@124 Pass No
APACHE_POI_TC testuser_3 Test@125 Pass Yes
APACHE_POI_TC testuser_4 Test@126 Pass Yes
APACHE_POI_TC testuser_5 Test@127 Pass No
APACHE_POI_TC testuser_6 Test@128 Pass Yes

Example : with Excel file (2007) - .xlsx

Use  org.apache.poi.xssf.usermodel package - all class names starts with XSSF

 Here,   

XSSFWorkbook represents the whole excel file

XSSFSheet represents the instance of a single sheet

XSSFRow represents a single row of  the current sheet you are working on

XSSFCell represents a tiny element cell in the sheet

 
package com.sample;

import java.io.FileInputStream;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/*
 * For Excel - From 2007 version
 * File Extension - .xlsx
 * All class from Apache POI API -should start with XSSF
 * 
 */

public class ReadWriteWorkbook {
 private static XSSFWorkbook xlWBook;
 private static XSSFSheet xlSheet;
 private static XSSFRow xlRow; 
 private static String filePath = "/home/dinesh/";
 private static String fileName = "xtest.xlsx";

 public static void main(String[] args) {

  try {

   FileInputStream xlFile = new FileInputStream(filePath + fileName);

   // Access the required test data sheet
   xlWBook = new XSSFWorkbook(xlFile);

   // Assuming your data is in Sheet1
   xlSheet = xlWBook.getSheet("Sheet1");

   // gives row count in sheet
   int noOfRows = xlSheet.getPhysicalNumberOfRows();

   // gives number of rows
   xlRow = xlSheet.getRow(0);
   
   int noOfColumns = xlRow.getLastCellNum();
   
   // Storing all the excel data into an array excelData (Sheet1 only)
   String[][] excelData = new String[noOfRows][noOfColumns];

   // r - row c- column
   for (int r = 1; r < noOfRows; r++) {
    for (int c = 0; c < noOfColumns; c++) {
     xlRow = xlSheet.getRow(r);
     
     // Here we have complete excel data excelData
     // if there are any cells with no data - as treated as blanks
     Cell cell = xlRow.getCell(c, Row.CREATE_NULL_AS_BLANK);

     excelData[r][c] = cell.toString();

     System.out.println("row: " + r + " column: " + c
       + " cell data: " + excelData[r][c]);
    }
    System.out.println("*****************************************");
   }
  } catch (Exception e) {
   e.printStackTrace();

  }
 }
}
Example : with Excel file (2003) - .xls Use  org.apache.poi.hssf.usermodel package - all class names starts with HSSF
package com.sample;

import java.io.FileInputStream;

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.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;


/*
 * For Excel - Upto 2003 version
 * File Extension - .xls
 * All class from Apache POI -should start with HSSF
 */

public class ReadWriteExcelUpto2003 {
 
 private static HSSFWorkbook xlWBook;
 private static HSSFSheet xlSheet;
 private static HSSFRow xlRow;
 private static String filePath = "/home/dinesh/";
 // file extension - .xls
 private static String fileName = "xtest.xls";

 public static void main(String[] args) throws InterruptedException {

  try {

   FileInputStream xlFile 
   = new FileInputStream(filePath + fileName);

   // Access the required test data sheet
   xlWBook = new HSSFWorkbook(xlFile);

   // Assuming your data is in Sheet1
   xlSheet = xlWBook.getSheet("Sheet1");

   // gives row count in sheet
   int noOfRows = xlSheet.getPhysicalNumberOfRows();
   
   //gives number of rows 
   xlRow = xlSheet.getRow(0);
   int noOfColumns = xlRow.getLastCellNum();

   //Storing all the excel data into an array excelData (Sheet1 only)
   String[][] excelData = new String[noOfRows][noOfColumns];

   // r - row c- column
   for (int r = 1; r < noOfRows; r++) {
    for (int c = 0; c < noOfColumns; c++) {
  xlRow = xlSheet.getRow(r);
  
  // Here we have complete excel data excelData
  // if there are any cells with no data - as treated as blanks
  Cell cell = xlRow.getCell(c, Row.CREATE_NULL_AS_BLANK);

  excelData[r][c] = cell.toString();

     System.out.println("row: " + r + " column: " + c 
       + " cell data: "+excelData[r][c]);     
    }
    System.out.println("*****************************************");
   }
  } catch(Exception e){
   e.printStackTrace();
   
  }
 }
} 
Output:
row: 1 column: 0 cell data: APACHE_POI_TC
row: 1 column: 1 cell data: testuser_1
row: 1 column: 2 cell data: Test@123
row: 1 column: 3 cell data: Pass
row: 1 column: 4 cell data: Yes
*****************************************
row: 2 column: 0 cell data: APACHE_POI_TC
row: 2 column: 1 cell data: testuser_2
row: 2 column: 2 cell data: Test@124
row: 2 column: 3 cell data: Pass
row: 2 column: 4 cell data: No
*****************************************
row: 3 column: 0 cell data: APACHE_POI_TC
row: 3 column: 1 cell data: testuser_3
row: 3 column: 2 cell data: Test@125
row: 3 column: 3 cell data: Pass
row: 3 column: 4 cell data: Yes
*****************************************
row: 4 column: 0 cell data: APACHE_POI_TC
row: 4 column: 1 cell data: testuser_4
row: 4 column: 2 cell data: Test@126
row: 4 column: 3 cell data: Pass
row: 4 column: 4 cell data: Yes
*****************************************
row: 5 column: 0 cell data: APACHE_POI_TC
row: 5 column: 1 cell data: testuser_5
row: 5 column: 2 cell data: Test@127
row: 5 column: 3 cell data: Pass
row: 5 column: 4 cell data: No
*****************************************
row: 6 column: 0 cell data: APACHE_POI_TC
row: 6 column: 1 cell data: testuser_6
row: 6 column: 2 cell data: Test@128
row: 6 column: 3 cell data: Pass
row: 6 column: 4 cell data: Yes
*****************************************
Note: All examples are properly commented - please feel free to post your doubts/comments - Hope you like the content  please share this - thank u

Monday, 2 February 2015

FORMATING NUMBERS USING DecimalFormat

 DecimalFormat


Using java.text.DecimalFormat class  you can control the display of leading and trailing zeros, prefixes and suffixes, thousand separators, and the decimal   separator.


Example:
package com.selenium;

import java.text.DecimalFormat;

public class DecimalFormatEx {

 public static void main(String[] args) {
  
  /* first parameter - pattern  second parameter - value
   * According to the given pattern 
   */
  
  //acts as a thousand separator - 12,345.343
  formatByPattern("###,###.###",12345.34343);
  
  //here the decimal value is rounding - 123456.79
  formatByPattern("###.##",123456.789);
  
  //adding trailing and leading zeros - 000898.780
  formatByPattern("000000.000",898.78);
  
  //adding prefix $  - $12,345.34
  formatByPattern("$###,###.###",12345.34);  
  
 }

 //a custom method - you can name this method as you wish
 
 private static void formatByPattern(String pattern,double value){
  
  DecimalFormat formater = new DecimalFormat(pattern);
  
  String output = formater.format(value);
  
  System.out.println(output);
 }

}


Sunday, 1 February 2015

HOW TO USE TESTNG FRAMEWORK - SAMPLES-I

Just like Junit, TestNG provides very good testing strategies.

This post gives an overview of TestNG - a sample test case.

To you TestNG framework in your project you must use TestNG.jar

Ways To Download:

Official Download Link:  TestNG.jar

or

use git clone
git clone git://github.com/cbeust/testng.git  
or

If your using eclipse IDE, you can install TestNG as an eclipse plugin:
Read More...

After downloading TestNG jar file - add that jar to the project build path:

Now you are ready to use TestNG framework.

TestNG test cases  uses some important annotations:


All annotations are placed in the package:

org.testng.annotations.*;

@Test 

To write a test case - use @Test annotation.

Example:

package examples.testng;

import org.testng.annotations.Test;

public class MyFirstTest {

//First Test Case
@Test
public void validUser() {
// write your validation logic
System.out.println("Checking authorization");
}

//Second Test Case
@Test
public void checkBalance() {
// write a business logic to check the balance
System.out.println("Must check balance - before transactions");
}
} 


 How to run it?

It is very easy to run a test case in TestNG if your are using an IDE like eclipse

Right Click on Test Case Class->select "Run as"  -> TestNG test


More Concepts on TestNG ..coming soon

HOW TO INSTALL TESTNG FRAMEWORK AS A PLUGIN IN ECLIPSE

Testng framework is available on Eclipse IDE as a plugin.

Steps to Install:

Step1:

go to "Help" Menu -> click on "install new software"



Step2:

Click Add.... button 

This opens a pop up - Add Repository

For Name Field - enter any name for the installation location

Location Filed:

In location field enter url as per eclipse IDE version


Step3:

After adding respository location

select the checkbox "TestNG"



Step4:

Click next -  be patient it takes some time - then


click - "I accept the terms ...."



Step5:

Click install- you can also choose to run in background

- now this starts installation



NOTE:

To install any new plugin you follow this way of adding the respective software location as a repository.

Thank You
Hope you like it...