CD Burner Free tool ( Good one)


Hello Friends,

You can use CDBurnerXP Tool for burning CD's , its cool one

http://cdburnerxp.se/en/home

One of my friend asked me about CD Burning tool , and thought to put it on blog .

Best Regards

Vodafone had launched Webbox – an innovative plug and play keyboard, bringing internet to your television

 


Hello everyone Vodafone has launched Webbox - an innovative plug and play keyboard, bringing internet to your television. It is basically key board with lots of features inbuilt. The features include Internet, applications, photos, music, FM Radio, Documents to go, SMS, EMail, Contacts, Games, USB and Micro SD. Now i show you some images here after that you will understand more about this new technology.

Top Features

 

 

 



 Tech Specifications

 

Setup User Guide (Easy Installation)





How to Clean your Computer RAM and make your PC perform Faster ?

You may recognize that your system gets slower and slower when playing games and working a lot on your PC. That`s cause your RAM is full of remaining progress pieces you do not need any more.





















Do not take any tension now you can make your PC faster by cleaning the RAM by yourself you do not need any hardware person. Kindly Follow this steps

1) Click on start on your windows and go into Run application

2) Kindly type in that NOTEPAD.

3) Kindly Type following string in single line in Notepad     FreeMem=Space(512000000)

4) Kindly press ALT+F+A
                                       
5)  Kindly Give following string as file name :"RAMcleaner.vbs"
                                       
6) Select All File & Save file on the desktop

7) Run the file whenever you wish to clean your RAM

Introduction to Struts2

Introduction to Struts2

Author: Ashish Garg

OGNL(Object-Graph Navigation language) is an expression language inherited by Struts from WebWork. It is used in struts to access model objects from a jsp page. OGNL can be used to bing GUI elements to model objects in struts framework. It can be used to invoke methods of the model.

It can create lists,maps to be used with GUI,bind generic tags with model objects,convert one type to another.

Value Stack is an object created prior to any action method is executed and is used to store actions and other objects.

The struts framework stores the value stack in request attribute struts.valueStack and is used by jsp to display action and other info. Value Stack contains Object Stack and the Context Map.

Action and other objects are pushed ito the Object Stack where as maps(parameters,request,session,application,attr) are stored in Context Map To access Context Map properties we use a # in front of the OGNL expression, if not used search will take place from Object Stack.

eg #session.code returns the value of the session attribute code. Accessing Object Stack object properties [0].message, returns the message property valueof the object on top. [1]duration returns the duration property of the second object.

The automation of data transfer and type conversion is one of the most powerful features of Struts 2. With the help of OGNL, the Struts 2 framework allows transfer of data onto more complex Java-side types like List, Map, etc.

Custom converters can also be developed to extend the type conversion mechanism and it can handle any data type, including user-defined types.



OGNL is the interface between the Struts 2 framework string-based HTTP Input and Output and the Java-based internal processing. For developers who are conversant with OGNL, it will substantially improve efficiency and reduce maintenance headaches.

The framework sets the OGNL context to be our ActionContext, and the value stack to be the OGNL root object. (The value stack is a set of several objects, but to OGNL it appears to be a single object.) Along with the value stack, the framework places other objects in the ActionContext, including Maps representing the application, session, and request contexts. These objects coexist in the ActionContext, alongside the value stack (our OGNL root).


Utilizing Singleton Database controller class for interaction with database

Utilizing Singleton Database controller class for interaction with database

Author: Shruti Upadhyaya

This is a singleton class whose object is created once in entire application. Its object is shared in entire application. Using this class, database interaction code is minimized and confined to a few couple of lines only.


DatabaseViewController.h class includes:

#import
#import "sqlite3.h"
@interface DatabaseViewController : NSObject{
sqlite3 *database;
sqlite3_stmt *statement;
NSString *dbName;
}
@property(nonatomic ,assign) sqlite3 *database;
@property(nonatomic ,assign) sqlite3_stmt *statement;
@property(nonatomic ,retain) NSString *dbName;
+(DatabaseViewController *)sharedInstance;
-(id)initWithDB:(NSString *)db_Name;
-(NSString *)getDBFilePath;
-(BOOL)checkNCreateDB;
-(BOOL)getConnection:(const char*)dbPath;
-(BOOL)createStatement:(NSString *)querySQL;
-(BOOL)closeConnection;
-(BOOL)createTable:(NSString *)sqlQuery;
-(BOOL)updateQuery:(NSString *)sqlQuery;
-(NSMutableArray *)executeQuery:(NSString *)query;
-(void)ProcessData;
@end

DatabaseViewController.m class includes:

#import "DatabaseViewController.h"
static DatabaseViewController *_instance;
@implementation DatabaseViewController

@synthesize database;
@synthesize statement;
@synthesize dbName;
+(DatabaseViewController *)sharedInstance{
if (_instance == nil) {
_instance = [[self alloc]init];
}
return _instance;
}
-(BOOL)createTable:(NSString *)sqlQuery{
const char *sql_Query = [sqlQuery UTF8String];
BOOL returnFlag;
NSString *dbFilePath = [self getDBFilePath];
BOOL connectionFlag = [self getConnection:[dbFilePath UTF8String]];
if (connectionFlag) {
if (sqlite3_exec(database,sql_Query,NULL,NULL,NULL) == SQLITE_OK) {
NSLog(@"table is created successfully");
returnFlag =YES;
}else{
NSLog(@"table is not created ");
returnFlag =NO;
}
[self closeConnection];
}else{
NSLog(@"Connection is not opened");
returnFlag = NO;
}
return returnFlag;
}
// this method is used to insert/ update record in database
-(BOOL)updateQuery:(NSString *)sqlQuery{
BOOL returnFlag= NO;
NSString *dbFilePath = [self getDBFilePath];
BOOL connectionFlag = [self getConnection:[dbFilePath UTF8String]];
if (connectionFlag) {
BOOL statementFlag = [self createStatement:sqlQuery];
if (statementFlag==YES && sqlite3_step(statement) == SQLITE_DONE) {
NSLog(@"row is insertedne");
sqlite3_finalize(statement);
returnFlag = YES;
}else{
NSLog(@"Row can not be inserteded");
returnFlag = NO;
}
[self closeConnection];
}else{
returnFlag = NO;
}
return returnFlag;
}
// calling this method to close the opened db connection
-(BOOL)closeConnection{
if (sqlite3_close(database) == SQLITE_OK) {
return YES;
}else{
return NO;
}
}
-(BOOL)getConnection:(const char*)dbPath{
if (sqlite3_open(dbPath,&database)== SQLITE_OK) {
NSLog(@"Connection is openend successfully");
//NSLog(@"databadfsad %@",database);
return YES;
}else{
NSLog(@"Connection is not openend");
return NO;
}
}
-(BOOL)createStatement:(NSString *)querySQL{
const char *dbquery = [querySQL UTF8String];
NSLog(@"going texecutere quernt%@",querySQL);
if (sqlite3_prepare_v2(database,dbquery,-1,&statement,NULL)== SQLITE_OK) {
NSLog(@"query is executed successfully");
return YES;
}else{
NSLog(@"query is not executed successfully");
return NO;
}
}
// below mehod is used to check and create database in App document directory
-(BOOL)checkNCreateDB{
//Getting App Path Array
NSArray *DocsArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
//Getting App Document Directory path
NSString *docsPath = [DocsArray objectAtIndex:0];
//Now we are adding DB File Name in Document Directory path
NSString *dbPath = [docsPath stringByAppendingPathComponent:self.dbName];
//Now we are getting File Manager Object to determine Sqlite file existing in Document Directory
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:dbPath]) {
//Control comes inside if DBFile is not existing and we are are copying that file in Document Directory
NSString *dbPathInApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:self.dbName];
[fileManager copyItemAtPath:dbPathInApp toPath:dbPath error:nil];
return YES;
}else{
//Control comes inside if DB File is already existing
NSLog(@"Database is already existing");
return NO;
}
[fileManager release];
}

//Below method is used to select record from Database
-(NSMutableArray *)executeQuery:(NSString *)query{
[self checkNCreateDB];
NSMutableArray *dataArray = [[NSMutableArray alloc]init];
//getting DBPath
NSString *dbFilePath = [self getDBFilePath];
//getting Connection
BOOL connectionCreationFlag = [self getConnection:[dbFilePath UTF8String]];
if (connectionCreationFlag) {
NSLog(@"connection is established");
BOOL statementCreationFlag = [self createStatement:query];
if (statementCreationFlag) {
NSLog(@"statement is created in executequery");
while (sqlite3_step(statement)== SQLITE_ROW) {
int noOfColumns = sqlite3_data_count(statement);
NSLog(@"no of rows in database is %d",sqlite3_data_count(statement));
NSMutableDictionary *dictRow = [[[NSMutableDictionary alloc]init]autorelease];
for (int i = 0; i< noOfColumns;i++) {
NSString *columnValue = [[NSString alloc] initWithUTF8String:(const char*) sqlite3_column_text(statement,i)];
[dictRow setObject:columnValue forKey:[NSString stringWithFormat:@"COL%d",i]];
}
[dataArray addObject:dictRow];
}
sqlite3_finalize(statement);
}else{
NSLog(@"statement is not created");
}
NSLog(@"connection is closed");
sqlite3_close(database);
}else{
NSLog(@"connection can not be established");
}
NSLog(@"dataarray is %@",dataArray);
return [dataArray autorelease];
}

//below method return dbfilepath , which is residing in App Document Directory
-(NSString*) getDBFilePath{
//getting Docs Array
NSArray *docsDir = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
//getting Documents Directory path
NSString *docsPath = [docsDir objectAtIndex:0];
//getting Database file path
NSString *DBFilePath = [docsPath stringByAppendingPathComponent:self.dbName];
NSLog(@"Dbpath is %@",DBFilePath);
return DBFilePath;
}

- (oneway void)release
{
}

- (id)retain
{
return _instance;
}

- (id)autorelease
{
return _instance;
}

-(void)dealloc{
[dbName release];
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end

Note:

1) get shared DatabaseViewController object where ever you want to have Database Interaction
2) In AppDelegate didFinishLaunchingWithOptions, get Shared Instance and assign dbname property with appropriate
sqlite filename that is put into your App Bundle. and call method checkNCreateDB, it will check and Create sqlite
file in App Document Directory
NSString *db_Name = @"empContact.sqlite";
DatabaseViewController * _dbController = [DatabaseViewController sharedInstance];
_dbController.dbName = db_Name;
[_dbController checkNCreateDB];

3)Where ever you get DatabaseViewController shared object then you can interact with database.

Seclet Query

DatabaseViewController * _dbController = [DatabaseViewController sharedInstance];

NSString *sqlQuery = @"SELECT * from emp";
empData = [dbController executeQuery:sqlQuery];
[empData retain];
NSLog(@"dataArr is in Emp %@",empData);

Update or Insert Query

DatabaseViewController *_dbController = [DatabaseViewController sharedInstance];
NSString *sqlQuery = @"INSERT INTO EMP VALUES('Nitesh','Team Lead','944593434','09-08-1986')";
BOOL insertFlag = [dbController updateQuery:sqlQuery];
if (insertFlag) {
NSLog(@"Record is inserted");
}else{
NSLog(@"Record is not inserted");
}

Get Signature in iPad App

Get Signature in iPad App

Author: Ghanshyam Maliwal

One of the basic requirement for filling any Technical forms needs attached signature. Following code describes how to add Signature functionality in your project.


SignatureViewController:

This ViewController opens in UIPopOverViewController and holds user Signature. User sketches here on UIView using CALayer ,
CGContext classes ( Core-Data framework API) . While making Signature, if any Correction is required, than tap three times
continuously enables incorrect signature disappear and can make new one signature . After so, tap outside UIPopOverViewController
that displays Signature in UIImageView that appears on MainViewController.

SignatureViewController.h file includes :

@interface SignatureViewController : UIViewController{
CALayer *canvasLayer;
CALayer *backgroundLayer;
UIImage *cacheImage;
CGMutablePathRef path;
CGPoint pathPoint;
BOOL touching;
}

SignatureViewController.m file includes :


1) put this below code in viewDidLoad

//Set Up drawing Layer
canvasLayer = [[CALayer layer] retain];
canvasLayer.bounds = CGRectMake(0,0,768, 600);
canvasLayer.position = CGPointMake(canvasLayer.bounds.size.width/2, canvasLayer.bounds.size.height/2);
[canvasLayer setDelegate:self];
[self.view.layer addSublayer:canvasLayer];
//Set up storage Layer
backgroundLayer = [[CALayer layer] retain];
backgroundLayer.bounds = CGRectMake(0,0,768, 600);
backgroundLayer.position = CGPointMake(backgroundLayer.bounds.size.width/2, backgroundLayer.bounds.size.height/2);
[backgroundLayer setDelegate:self];
[self.view.layer addSublayer:backgroundLayer];
//Initialize some other Variable
cacheImage = nil;
touching = NO;
NOTE: we are taking two Layer
a) Canvaslayer is used to hold signature temporarily
b) background layer is used to hold signature permanently.


2) Implement Touches Delegate in your ViewController

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
NSLog(@"touch moving is calling");
if(touching){
//get the Current location of touch event
UITouch *touch = [touches anyObject];
pathPoint = [touch locationInView:self.view];
CGPathAddLineToPoint(path, NULL, pathPoint.x, pathPoint.y);
[canvasLayer setNeedsDisplay];
}
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
if ([touch tapCount]==3) {
NSLog(@"calling to hide ");
[self resetSignature];
}else{
NSLog(@"touch begin is calling");
if (touching) return;
//Start a new Path
path = CGPathCreateMutable();
//set the path's starting point
UITouch *touch = [touches anyObject];
CGPathMoveToPoint(path, NULL, [touch locationInView:self.view].x, [touch locationInView:self.view].y);
touching = YES;
}
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
NSLog(@"touch end is calling");
UITouch *touch = [touches anyObject];
if ([touch tapCount]==3) {
NSLog(@"calling to hide in end ");
[self resetSignature];
}else{
if (!touching) return;
//create a new image context (Bitmap based graphic context and make it current context)
UIGraphicsBeginImageContext(CGSizeMake(backgroundLayer.bounds.size.width, backgroundLayer.bounds.size.height));
//grab a reference to the new image context
CGContextRef ctx = UIGraphicsGetCurrentContext();
//push the image context to the top of the drawing stack
UIGraphicsPushContext(ctx);
//set the blend mode to prevent white pixels from
//covering up the lines that have already been drawn
CGContextSetBlendMode(ctx, kCGBlendModeDarken);
if (cacheImage != nil) {
//draw the cached state of the image to the image context and release it
[cacheImage drawInRect:CGRectMake(0,0,backgroundLayer.bounds.size.width,backgroundLayer.bounds.size.height)];
[cacheImage release];
}
//blend the drawing layer into the image context
[canvasLayer drawInContext:ctx];

//we're done drawing to the image context
UIGraphicsPopContext();
//store the image context so we can add to it again later (this is refresh Image)
cacheImage = UIGraphicsGetImageFromCurrentImageContext();
[cacheImage retain];
//we're finished with the image context altogether
UIGraphicsEndImageContext();
touching = NO;
//release the path
CGPathRelease(path);
//update the background layer (we'll need to draw the cached image to the background)
[backgroundLayer setNeedsDisplay];
}
}


3) This drawLayer is called when either canvas layer or background layer is going to send setNeedsDisplay message

- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx {

NSLog(@"calling drawing line ");
//this method is handling multiple layers, so first
//determine which layer we're drawing to
if (layer == canvasLayer) {
//we don't want this to fire after the background layer update
//and after the path has been released
if (!touching) return;
//add the path to the context
CGContextAddPath(ctx, path);
//set a line width and draw the path
CGContextSetLineWidth(ctx, 2.0f);
//CGContextSetStrokeColorWithColor(ctx, [[UIColor greenColor] CGColor]);
CGContextStrokePath(ctx);
//CGContextRelease(ctx);
}
else if (layer == backgroundLayer) {
//remember the current state of the context
CGContextSaveGState(ctx);
//the cached image coordinate system is upside down, so do a backflip
CGContextTranslateCTM(ctx, 0, backgroundLayer.bounds.size.height);
CGContextScaleCTM(ctx, 1.0, -1.0);
//draw the image
CGImageRef ref = cacheImage.CGImage;
CGContextDrawImage(ctx, backgroundLayer.bounds, ref);
//restore the context to its pre-flipped state
CGContextRestoreGState(ctx);
}
}


4) We use below resetSingnature function to remover signature and create platform to get new Signature

-(void)resetSignature{
path =nil;
cacheImage = nil;
canvasLayer.contents = nil;
backgroundLayer.contents = nil;
}


Compare Excel in Java

Compare Excel sheets in Java

To compare two excel files we created a struts project in which two excel files can be uploaded and after comparing them result on a pdf file is generated which is available for download.

To read the excel files Apache POI is used and for pdf generation iText library is used.

Following is the process:

Upload File:





Download Result.pdf:


Open Result.pdf:

Following are java files that are used in project:

1. FileUploadForm.java: Contains getter and setter methods for FormFile to provide functionality of uploading of file through browser. Also validates excel files for their format and size(File Size should be less then 512MB).

2. compareSheetAction.java: Contains action which is called on "Submit" Action. Captures files from FileUploadForm.java through getter method and calculates real path of file to compare them. Then calls method "readExcelFile" of CompareExcelDAO.java to read file, one by one. Method returns LinkedHashMap for respective excel files. Then "compareCellData" of CompareExcelDAO.java is called which takes as input two LinkedHashMap.

3. CompareExcelDAO.java: Contains "readExcelFile" and "compareCellData" methods for reading excel file and comparing them. Method "createFirstTable" creates the table to be displayed on pdf file. Pdf file is returned by "compareCellData" method in ByteArrayOutputStream that is directly passed to browser to made it downloadable.


FileUploadForm.java:


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

import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.upload.FormFile;

/**
*
* @author Mighty Heart
*/
public class FileUploadForm extends ActionForm {

private FormFile file1;
private FormFile file2;
private String message;

public FileUploadForm() {
super();
}

public FormFile getFile1() {
return file1;
}

public void setFile1(FormFile file1) {
this.file1 = file1;
}

public FormFile getFile2() {
return file2;
}

public void setFile2(FormFile file2) {
this.file2 = file2;
}

/**
* @return the message
*/
public String getMessage() {
return message;
}

/**
* @param message the message to set
*/
public void setMessage(String message) {
this.message = message;
}

@Override
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
boolean isFileSize1 = false;
boolean isFileSize2 = false;
isFileSize1 = file1.getFileSize() > 0;
isFileSize2 = file2.getFileSize() > 0;

System.out.println("File Size is : " + isFileSize1);
System.out.println("File Size is : " + isFileSize2);
if (!isFileSize1) {
errors.add("file1", new ActionMessage("error.file.required"));
} else if (!file1.getContentType().equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) {
errors.add("file1", new ActionMessage("error.file.type"));
}
if (!isFileSize2) {
errors.add("file2", new ActionMessage("error.file.required"));
} else if (!file1.getContentType().equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) {
errors.add("file2", new ActionMessage("error.file.type"));
}
/**
* If the file size is greater than 512MB, show error.
*/
if (file1.getFileSize() > 524288000 || file2.getFileSize() > 524288000) {
errors.add("file", new ActionMessage("error.file.size"));
}
return errors;
}
}

compareSheetAction.java



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

import com.yusata.dao.CompareExcelDAO;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedHashMap;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.upload.FormFile;

/**
*
* @author Mighty Heart
*/
public class compareSheetAction extends DispatchAction {

HttpSession session = null;

public ActionForward uploadFileAction(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws FileNotFoundException, IOException, Exception {
session = request.getSession();
FileUploadForm uploadForm = (FileUploadForm) form;
FileOutputStream outputStream1 = null;
FileOutputStream outputStream2 = null;
FormFile formFile1 = null;
FormFile formFile2 = null;
InputStream in1 = null;
InputStream in2 = null;
String path = null;
String path1 = null;
String path2 = null;
try {
formFile1 = uploadForm.getFile1();
formFile2 = uploadForm.getFile2();
path = getServlet().getServletContext().getRealPath("uploadedFile") + "\\";
path1 = path + formFile1.getFileName();
path2 = path + formFile2.getFileName();

File f1 = new File(path1);
File f2 = new File(path2);
if (f1.exists()) {
f1.delete();
} else {
f1.createNewFile();
}
if (f2.exists()) {
f2.delete();
} else {
f2.createNewFile();
}
System.out.println("Path Is: " + path1);
System.out.println("Path Is: " + path2);
outputStream1 = new FileOutputStream(f1);
outputStream2 = new FileOutputStream(f2);
in1 = formFile1.getInputStream();
int charInInt1;
while ((charInInt1 = in1.read()) != -1) {
outputStream1.write((char) charInInt1);
}
in2 = formFile2.getInputStream();
int charInInt2;
while ((charInInt2 = in2.read()) != -1) {
outputStream2.write((char) charInInt2);
}
} catch (Exception e) {
System.out.println("Exception Occured :-" + e.getMessage());
} finally {
outputStream1.close();
outputStream1.flush();
outputStream2.close();
outputStream2.flush();
in1.close();
in2.close();

}
uploadForm.setMessage("The file " + formFile1.getFileName() + " & " + formFile2.getFileName() + " is uploaded successfully.");
CompareExcelDAO mapDao = new CompareExcelDAO();
LinkedHashMap dataHolder_sheet1 = mapDao.readExcelFile(session, path1, 1);
LinkedHashMap dataHolder_sheet2 = mapDao.readExcelFile(session, path2, 2);
ServletOutputStream op = response.getOutputStream();
response.setContentType("APPLICATION/pdf");
response.setHeader("Content-Disposition", "attachment; filename=Result.pdf");
op.write(mapDao.compareCellData(path, formFile1.getFileName().toString(), formFile2.getFileName().toString(),
dataHolder_sheet1, dataHolder_sheet2).toByteArray());
return null;
}
}

CompareExcelDAO.java:



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

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.FontFactory;
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;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Iterator;
import java.util.LinkedHashMap;
import javax.servlet.http.HttpSession;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
*
* @author yusata26
*/
public class CompareExcelDAO {

Connection con = null;
Statement stmt = null;
boolean addPDFTable = false;
String[] SheetNames1;
String[] SheetNames2;
public static final String[] TYPES = {"Number Type", "String Type", "Formula Type", "Blank Type", "Boolean Type", "Error type"};
/**
* To get column names, from column indexes, as per standard excel
* notations.
*/
public static final String[] ExcelColumns = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O",
"P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "AA", "AB", "AC", "AD", "AE", "AF", "AG", "AH", "AI",
"AJ", "AK", "AL", "AM", "AN", "AO", "AP", "AQ", "AR", "AS", "AT", "AU", "AV", "AW", "AX", "AY", "AZ", "BA",
"BB", "BC", "BD", "BE", "BF", "BG", "BH", "BI", "BJ", "BK", "BL", "BM", "BN", "BO", "BP", "BQ", "BR", "BS",
"BT", "BU", "BV", "BW", "BX", "BY", "BZ", "CA", "CB", "CC", "CD", "CE", "CF", "CG", "CH", "CI", "CJ", "CK", "CL", "CM",
"CN", "CO", "CP", "CQ", "CR", "CS", "CT", "CU", "CV", "CW", "CX", "CY", "CZ", "DA", "DB", "DC", "DD", "DE", "DF", "DG",
"DH", "DI", "DJ", "DK", "DL", "DM", "DN", "DO", "DP", "DQ", "DR", "DS", "DT", "DU", "DV", "DW", "DX", "DY", "DZ"};

public LinkedHashMap readExcelFile(HttpSession session, String fileName, int file) {
LinkedHashMap multipleSheetData = new LinkedHashMap();
LinkedHashMap cellData;
int NumberOfSheets;
try {
FileInputStream myInput = new FileInputStream(fileName);
XSSFWorkbook myWorkBook = new XSSFWorkbook(myInput);
NumberOfSheets = myWorkBook.getNumberOfSheets();
if (file == 1) {
SheetNames1 = new String[NumberOfSheets];
} else {
SheetNames2 = new String[NumberOfSheets];
}
for (int i = 0; i < NumberOfSheets; i++) {
if (file == 1) {
SheetNames1[i] = myWorkBook.getSheetName(i);
} else {
SheetNames2[i] = myWorkBook.getSheetName(i);
}
cellData = new LinkedHashMap();
XSSFSheet mySheet = myWorkBook.getSheetAt(i);
Iterator rowIter = mySheet.rowIterator();
while (rowIter.hasNext()) {
XSSFRow myRow = (XSSFRow) rowIter.next();
Iterator cellIter = myRow.cellIterator();
while (cellIter.hasNext()) {
XSSFCell myCell = (XSSFCell) cellIter.next();
cellData.put(ExcelColumns[myCell.getColumnIndex()] + (myRow.getRowNum() + 1), myCell);
}
}
multipleSheetData.put(i + "", cellData);
}
} catch (Exception e) {
System.out.println("Exception. " + e.getMessage());
}
return multipleSheetData;
}

public PdfPTable createFirstTable(String[][] statusSheet) throws DocumentException {
PdfPTable table;
table = new PdfPTable(5);
table.setWidths(new int[]{1, 2, 2, 3, 3});
table.setWidthPercentage(100);
System.out.println("About to create pdf. ");
PdfPCell cell;
cell = new PdfPCell(new Phrase(statusSheet[0][0], FontFactory.getFont(FontFactory.TIMES_BOLD, 11)));
table.addCell(cell);
cell = new PdfPCell(new Phrase(statusSheet[0][1], FontFactory.getFont(FontFactory.TIMES_BOLD, 11)));
table.addCell(cell);
cell = new PdfPCell(new Phrase(statusSheet[0][2], FontFactory.getFont(FontFactory.TIMES_BOLD, 11)));
table.addCell(cell);
cell = new PdfPCell(new Phrase(statusSheet[0][3], FontFactory.getFont(FontFactory.TIMES_BOLD, 11)));
table.addCell(cell);
cell = new PdfPCell(new Phrase(statusSheet[0][4], FontFactory.getFont(FontFactory.TIMES_BOLD, 11)));
table.addCell(cell);
for (int itr = 1; itr < statusSheet.length; itr++) {
if (statusSheet[itr][0] != null) {
addPDFTable = true;
cell = new PdfPCell(new Phrase(statusSheet[itr][0], FontFactory.getFont(FontFactory.TIMES_ROMAN, 10)));
// System.out.println(statusSheet[itr][0]);
// System.out.println(statusSheet[itr][1]);
// System.out.println(statusSheet[itr][2]);
// System.out.println(statusSheet[itr][3]);
// System.out.println(statusSheet[itr][4]);
table.addCell(cell);
cell = new PdfPCell(new Phrase(statusSheet[itr][1], FontFactory.getFont(FontFactory.TIMES_ROMAN, 10)));
table.addCell(cell);
cell = new PdfPCell(new Phrase(statusSheet[itr][2], FontFactory.getFont(FontFactory.TIMES_ROMAN, 10)));
table.addCell(cell);
cell = new PdfPCell(new Phrase("\"" + statusSheet[itr][3] + "\"", FontFactory.getFont(FontFactory.TIMES_ROMAN, 10)));
table.addCell(cell);
cell = new PdfPCell(new Phrase("\"" + statusSheet[itr][4] + "\"", FontFactory.getFont(FontFactory.TIMES_ROMAN, 10)));
table.addCell(cell);
}
}
return table;
}

public ByteArrayOutputStream compareCellData(String path, String file1, String file2, LinkedHashMap dataHolder_sheet1,
LinkedHashMap dataHolder_sheet2) throws Exception {
ByteArrayOutputStream BA = new ByteArrayOutputStream();
String statusSheet[][];
LinkedHashMap cellDataLHM1;
LinkedHashMap cellDataLHM2;
SimpleDateFormat formatter = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a");
boolean matchFlag = true;

PdfPTable tbl;
System.out.println("******* In Write PDF *******");
Document document = new Document(PageSize.A4);
PdfWriter.getInstance(document, BA);
document.open();
// Image image = Image.getInstance(path + "\\pru.PNG");
// image.setAlignment(Element.ALIGN_LEFT);
// document.add(image);
Paragraph p1 = new Paragraph();
Paragraph p4 = new Paragraph();
Paragraph p2;
Paragraph p3;
p4.add(new Phrase("Comparison Report", FontFactory.getFont(FontFactory.TIMES_BOLD, 20)));
p4.setAlignment(Element.ALIGN_CENTER);
document.add(p4);
p4 = new Paragraph();
p4.add("\n");
p4.add("File1: " + file1);
p4.add("\n");
p4.add("File2: " + file2);
p4.add("\n");
p4.add("Generated On: " + formatter.format(Calendar.getInstance().getTime()));
p4.add("\n");

int pdfSrNum = 1;
try {

for (Object keyForSheets : dataHolder_sheet1.keySet()) {
cellDataLHM1 = (LinkedHashMap) dataHolder_sheet1.get(keyForSheets.toString());
cellDataLHM2 = (LinkedHashMap) dataHolder_sheet2.get(keyForSheets.toString());
statusSheet = new String[cellDataLHM1.size()][5];
statusSheet[0][0] = "Sr.No.";
statusSheet[0][1] = "Status";
statusSheet[0][2] = "Location";
statusSheet[0][3] = "Value1";
statusSheet[0][4] = "Value2";
pdfSrNum = 1;

for (Object key : cellDataLHM1.keySet().toArray()) {
switch (((XSSFCell) cellDataLHM1.get(key.toString())).getCellType()) {
case Cell.CELL_TYPE_STRING:
try {
// if (!((((XSSFCell) cellDataLHM1.get(key.toString())).getStringCellValue()).toString().trim()).equals((((XSSFCell)
cellDataLHM2.get(key.toString())).getStringCellValue()).toString().trim())) {
if (!((((XSSFCell) cellDataLHM1.get(key.toString())).getStringCellValue()).toString()).equals((((XSSFCell)
cellDataLHM2.get(key.toString())).getStringCellValue()).toString())) {
if (!((((XSSFCell) cellDataLHM1.get(key.toString())).getStringCellValue()).toString()).contains("Run Date:")) {
statusSheet[pdfSrNum][0] = Integer.toString(pdfSrNum);
statusSheet[pdfSrNum][1] = "Mismatch";
// statusSheet[pdfSrNum][2] = "[" + key.toString().replace("####", ",") + "]";
statusSheet[pdfSrNum][2] = key.toString();
statusSheet[pdfSrNum][3] = cellDataLHM1.get(key.toString()).toString();
statusSheet[pdfSrNum][4] = cellDataLHM2.get(key.toString()).toString();
pdfSrNum++;
}
}
} catch (Exception e) {
System.out.println("Exception Found. *********" + e.getMessage());
}

break;
case Cell.CELL_TYPE_NUMERIC:
try {
if (DateUtil.isCellDateFormatted(((XSSFCell) cellDataLHM1.get(key.toString())))) {
if (!(((XSSFCell) cellDataLHM1.get(key.toString())).getDateCellValue()).equals(((XSSFCell) cellDataLHM2.get(key.toString())).getDateCellValue())) {
// System.out.println("not match");
statusSheet[pdfSrNum][0] = Integer.toString(pdfSrNum);
statusSheet[pdfSrNum][1] = "Mismatch";
// statusSheet[pdfSrNum][2] = "[" + key.toString().replace("####", ",") + "]";
statusSheet[pdfSrNum][2] = key.toString();
statusSheet[pdfSrNum][3] = cellDataLHM1.get(key.toString()).toString();
statusSheet[pdfSrNum][4] = cellDataLHM2.get(key.toString()).toString();
pdfSrNum++;
// System.out.println("mismatch at " + key.toString());
}
//CellArray.add(myCell.getDateCellValue());
} else {
if (((XSSFCell) cellDataLHM1.get(key.toString())).getNumericCellValue() != ((XSSFCell) cellDataLHM2.get(key.toString())).getNumericCellValue()) {
// System.out.println("not match");
statusSheet[pdfSrNum][0] = Integer.toString(pdfSrNum);
statusSheet[pdfSrNum][1] = "Mismatch";
// statusSheet[pdfSrNum][2] = "[" + key.toString().replace("####", ",") + "]";
statusSheet[pdfSrNum][2] = key.toString();
statusSheet[pdfSrNum][3] = cellDataLHM1.get(key.toString()).toString();
statusSheet[pdfSrNum][4] = cellDataLHM2.get(key.toString()).toString();
pdfSrNum++;
// System.out.println("mismatch at " + key.toString());
}

}

} catch (Exception e) {
System.out.println("Exception Found. *********" + e.getMessage());
}
break;


case Cell.CELL_TYPE_BOOLEAN:
try {
if (((XSSFCell) cellDataLHM1.get(key.toString())).getNumericCellValue() != ((XSSFCell) cellDataLHM2.get(key.toString())).getNumericCellValue()) {
// System.out.println("not match");
statusSheet[pdfSrNum][0] = Integer.toString(pdfSrNum);
statusSheet[pdfSrNum][1] = "Mismatch";
// statusSheet[pdfSrNum][2] = "[" + key.toString().replace("####", ",") + "]";
statusSheet[pdfSrNum][2] = key.toString();
statusSheet[pdfSrNum][3] = cellDataLHM1.get(key.toString()).toString();
statusSheet[pdfSrNum][4] = cellDataLHM2.get(key.toString()).toString();
pdfSrNum++;
// System.out.println("mismatch at " + key.toString());
}
} catch (Exception e) {
System.out.println("Exception Found. *********" + e.getMessage());
}
break;
default:
//cellData.put(myRow.getRowNum() + "####" + myCell.getColumnIndex(), myCell.getRichStringCellValue());
//cellStoreVector.addElement(myCell.getRichStringCellValue());
}
}
p1.add("\n");
p1.add("Sheet" + (Integer.parseInt(keyForSheets.toString()) + 1) + ": " + SheetNames1[Integer.parseInt(keyForSheets.toString())]);
p1.add("\n");
p1.add("Sheet" + (Integer.parseInt(keyForSheets.toString()) + 1) + ": " + SheetNames2[Integer.parseInt(keyForSheets.toString())]);
tbl = createFirstTable(statusSheet);
if (addPDFTable) {
matchFlag = false;
p1.add("\n");
p2 = new Paragraph();
p2.add(tbl);
p2.setAlignment(Element.ALIGN_CENTER);
p1.add(p2);

} else {
p2 = new Paragraph();
p2.add("\nData is same in both Sheets.\n\n");
p1.add(p2);
}
addPDFTable = false;
}

// }
// }

} catch (Exception E) {
E.printStackTrace();
}
p3 = new Paragraph();
if (matchFlag) {
p3.add("Status: Match");
} else {
p3.add("Status: Mismatch");
}
p3.add("\n");
p3.setAlignment(Element.ALIGN_LEFT);
document.add(p4);
document.add(p3);
document.add(p1);
document.close();
return BA;
}
}

Features:
1. Works for multiple sheets on Excel files.
2. Matches data cell by cell.
3. In Result pdf shows mismatch with locations so easy to identify.

Google Analytics

Use Google Analytics

Author: Neha Vyas

Google analytics helps you to track everything going on your website, where people going, what they are liking and why they are drop-off from page, so you can go and improve that page. You can access google anayltics by going to its website http://www.google.com/analytics To use Google Analytics either signing up for a new account or signing in to your Google account.

Set up a profile for the site you'd like to track and the step-by-step process will generate a unique script that you can add. Copy the JavaScript code from Analytics and paste it just above the tag in your page or template.

By following this you can add google analytics to your website and after that easily access website visits information.

Gogole analytics provides several functionalities for enhancement such as:

1. Setup Goals: The goals you setup for your website are the foundation of your website analysis because everything gravitates around your goals and conversion rates, the goals that are ultimately your business goals. These goals will help you track conversion rates and get insights about what are the main traffic sources that send you visitors which convert, what are the keywords who send you customers, which page your visitor use most to signup for your newsletter, where your customers from.



2. Track Event: Event tracking is a powerful feature in Google Analytics that can help you track among others: How many people download your eBook,What ads are performing better and who clicks on your ads,Which signup form converts better (sidebar, below the post, about page),Who pauses, fast forward or stops a video,What errors a visitor encounters during the checkout.
3. Real-time Reporting: Google has taken analytics one step further recently and introduced Real-Time Reporting, which displays information about visitors that are on your website in a specific moment. Your are able to see how many visitors are on your website in that moment, where they are on your website, from where they come (keywords and referrals) and where they live.



4. Dash Board: Gogole analytics dashboard provides teh facility to view all data in summarized form for analysis. We can customized dashboard, to create a custom dashboard, go to the [Home] menu > [Dashboards] and select [+New Dashboard].



5. Visitors Flow: The Visitors Flow will display the path that your visitors have taken to navigate through your website.You will be able to see, based on a selected dimension, such as country source or keyword, the exact path of your visitors and where they stopped to read your content.

On hover, the report displays for each page additional details, like the total number of visits, how many visitors moved to a different page and how many of them dropped the funnel and left.If you click on a page, you will be able to highlight the traffic that went through that page, explore traffic through that page or display in a popup even more details.

Handle a Web Service Which is Returning a JSON as Response in Android

Handle a Web Service Which is Returning a JSON as Response in Android

Author: Surender Kumar

Step 1 : Create an Interface


import org.json.JSONObject;

public interface HandleWebServiceResponse {
public void getWebServiceResponse(JSONObject json, int callingId);

}
HandleWebServiceResponse is the interface containing a method getWebServiceResponse.
It contains two parameters:

1. JSON Object i.e Response of web service.
2. Unique Calling ID to identify the response uniquely.

» This interface is to be implemented to the activity that is initializing a web service and is willing to handle
the JSON Response received from the web Service.

Step 2: Calling the web service in the background and sending the response back to the class that have initialized the web service call.


/**
* @author :Surender Kumar
*/


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.util.Log;

import com.investment.inteface.HandleWebServiceResponse;

/*
This class will call a webservice which is returning a json and will parse it to create a JSON object and the JSON object is
send back to the class which requires this json string.
The web service is called in a separate thread so it doesn't hang your UI while the code is busy in fetching the json result.

*/
public class WebServiceMaster extends AsyncTask {

private Object activity = null;
private int callingId;
private Map parameters = null;
private static String URL = "YOUR_WEBSERVICE_URL";

/*This method will initialize the calling of web service

@param fromActivity
object of the activity that has initialized the webservice i.e the class object which needs the JSON response

@param parameters
the Map object containing the parameters to be send along with the webservice. It contains the key value pair
in the Map object

@param callingId
the unique calling ID of the webservice. This is to identify the webservice response uniquely.
*/



public initWebService(Object fromActivity,Map parameters, int callingId) {
// TODO Auto-generated constructor stub
this.activity = fromActivity;
this.parameters = parameters;
this.callingId = callingId;
this.execute();
}

/*
This is the method of class AsyncTask which is executed in the separated thread. This method is overridden here to execute the particular code in the background so that the main UI does not hangs.
*/

@Override
protected JSONObject doInBackground(Void... arg0) {
// TODO Auto-generated method stub

StringBuilder param = new StringBuilder();
if (parameters != null) {
param.append("?");
for (Object key : parameters.keySet()) {
param.append(key.toString() + "="+ parameters.get(key).toString() + "&");
}
}
String url = URL + param.toString();
Log.i("info", "url :: "+url);
JSONObject json = null;
try {
json = getJSONfromURL(url);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json;
}



/*

This is the method of class AsyncTask which is executed when the background execution is finished.This method is overriden
here to perform the functionallity when the background thread has finished its work.

HandleWebServiceResponse is the inteface containg a method getWebServiceResponse.

From here we have called the getWebServiceResponse method of the activity that have initialized the call to web service and have implemented the inteface HandleWebServiceResponse.

As a response a JSON Object along with the unique calling id is send back.

*/




@Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Log.i("log_cat", "calling getWebServiceResponse method");
HandleWebServiceResponse response = (HandleWebServiceResponse) activity;
response.getWebServiceResponse(result, callingId);
super.onPostExecute(result);
}

/*

This is the method to make a http request to the url of web service and parse the json response to
create a json object.

@param url
URL of the webservice to be called.


*/

public static JSONObject getJSONfromURL(String url) throws IOException {

// initialize
InputStream in = null;
String result = "";
JSONObject json = null;

// http get
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
in = response.getEntity().getContent();

} catch (Exception e) {
Log.e("log_cat", "Error in http connection " + e.toString());
}

// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
in, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line);
}
result = sb.toString();
in.close();
} catch (Exception e) {
Log.e("log_cat", "Error converting result " + e.toString());
}

// try parse the string to a JSON object
try {
json = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_cat", "Error parsing data " + e.toString());
}
return json;
}

}

Step 3: Initializing the webservice from an activity


public class MainActivity extends Activity implements HandleWebServiceResponse{

private static final int WEB_SERVICE_ID_1 = 759176;


public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);


//Some of your code goes here
}

private void callWebService() {
// TODO Auto-generated method stub

HashMap parameters = new HashMap();
parameters.put("PARAMETER_1_NAME", PARAMETER_1_VALUE);
parameters.put("PARAMETER_1_NAME ", PARAMETER_1_VALUE);
parameters.put("PARAMETER_1_NAME ", PARAMETER_1_VALUE);

WebServiceMaster web_service = new WebServiceMaster(this, parameters,
WEB_SERVICE_ID_1);
}

@Override
public void getWebServiceResponse(JSONObject json, int callingId) {
// TODO Auto-generated method stub

/*
Handle your webservice response here.
You will receive a JSONObject as a response from webservice.

You can easily identify the response uniquely by the unique
Calling ID

*/
}

}

Barcode in Vaadin

Barcode in Vaadin

Author: Akshay Mathur

In one of our projects for one of our clients, we have used the Vaadin framework to develop the application. One of the requirements of this application was to Generate Barcode.

For that we created a PDF with the barcode .One way to display this PDF to the end-user is to open a new browser window. Unfortunately this was hindered by popup blockers which are not acceptable to end-users of the application. So we used Embedded and Window components to display the PDF.

Using an embedded component to display the PDF inside a native Vaadin popup window. This way, the popup with the PDF contents is not hindered by browser popup blockers because the popup is just a regular div. By using this method, the PDF window also integrated nicely with the rest of the application. The following code demonstrates how to implement this functionality:


/**
* This class creates a PDF with the iText library. This class implements
* the StreamSource interface which defines the getStream method.
*/
public class Pdf implements StreamSource {
private final ByteArrayOutputStream os = new ByteArrayOutputStream();

public Pdf() {
Document document = null;
PdfWriter writer;

try {
document = new Document (PageSize.A4);
PdfWriter.getInstance(document, os);
document.open();
document.add(new Paragraph("This is BARCODE PDF!"));
PdfContentByte cb = writer.getDirectContent();
Barcode128 barcd = new Barcode128();
barcd.setCode("10031");
Image barcode1 = barcd.createImageWithBarcode(cb, null, null);
document.add(barcode1);
}
catch (Exception e) {
e.printStackTrace();
} finally {
if (document != null) {
document.close ();
}
}
}

@Override
public InputStream getStream() {
// Here we return the pdf contents as a byte-array
return new ByteArrayInputStream(os.toByteArray());
}
}

And the code for displaying a popup with the actual PDF viewer:


Window window = new Window();
window.setWidth("900px");
window.setHeight("600px");
window.setModal(true);
String Title = "Barcode PDF";
e = new Embedded();
e.setWidth("850px");
e.setHeight("550px");
e.window.center();
e.setType(Embedded.TYPE_BROWSER);
StreamResource resource = new StreamResource(new Pdf(), Title+".pdf?", this);
resource.setMIMEType("application/pdf");
e.setSource(resource);
window.addComponent(e);
getMainWindow().addWindow(window);

Note: For proper display of Barcode PDF the filename of PDF must be Different.

We can also use PDF in the application to print content. The following code demonstrates how to implement this functionality:


/**
* This class creates a PDF with the iText library. This class implements
* the StreamSource interface which defines the getStream method.
*/
public class Pdf implements StreamSource {
private final ByteArrayOutputStream os = new ByteArrayOutputStream();
PdfWriter writer ;
public Pdf() {
Document document = null;
PdfPTable table = null;

try {
document = new Document(PageSize.A4);
writer = PdfWriter.getInstance(document, os);
document.open();
Paragraph preface = new Paragraph("Loyalty Information",
FontFactory.getFont(FontFactory.TIMES_ROMAN , 20,Font.BOLD));
preface.setAlignment(Element.ALIGN_CENTER);
document.add(preface);

Paragraph p1 = new Paragraph("Loyalty Number : 10031",
FontFactory.getFont(FontFactory.TIMES_ROMAN, 15));
p1.setAlignment(Element.ALIGN_LEFT);
p1.setSpacingBefore(30);
p1.setSpacingAfter(20);
document.add(p1);

Paragraph p2 = new Paragraph("Barcode : ",FontFactory.getFont(FontFactory.TIMES_ROMAN, 15));
p2.setAlignment(Element.ALIGN_LEFT);
p2.setSpacingAfter(60);
document.add(p2);

PdfContentByte cb = writer.getDirectContent();
Barcode128 barcd = new Barcode128();
barcd.setCode("10031");
Image barcode = barcd.createImageWithBarcode(cb, null, null);
barcode.scaleToFit(80,40);
barcode.setAbsolutePosition(100, 658);
document.add(barcode);

table = new PdfPTable(3);// number of columns in table
table.setWidthPercentage(95);
table.setSpacingAfter(7);

// the cell object

table.addCell(new Phrase("Serial Number",FontFactory.getFont(FontFactory.TIMES_ROMAN, 13,Font.BOLD)));
table.addCell(new Phrase("Name",FontFactory.getFont(FontFactory.TIMES_ROMAN, 13,Font.BOLD)));
table.addCell(new Phrase("Date of Birth",FontFactory.getFont(FontFactory.TIMES_ROMAN, 13,Font.BOLD)));
table.addCell(new Phrase("1",FontFactory.getFont(FontFactory.TIMES_ROMAN,12)));
table.addCell(new Phrase("TEST",FontFactory.getFont(FontFactory.TIMES_ROMAN,12)));
table.addCell(new Phrase("12/11/1976",FontFactory.getFont(FontFactory.TIMES_ROMAN,12)));
table.addCell(new Phrase("2",FontFactory.getFont(FontFactory.TIMES_ROMAN,12)));
table.addCell(new Phrase("TEST",FontFactory.getFont(FontFactory.TIMES_ROMAN,12)));
table.addCell(new Phrase("09/20/1992",FontFactory.getFont(FontFactory.TIMES_ROMAN,12)));
table.addCell(new Phrase("3",FontFactory.getFont(FontFactory.TIMES_ROMAN,12)));
table.addCell(new Phrase("TEST",FontFactory.getFont(FontFactory.TIMES_ROMAN,12)));
table.addCell(new Phrase("07/02/1995",FontFactory.getFont(FontFactory.TIMES_ROMAN,12)));
table.addCell(new Phrase("4",FontFactory.getFont(FontFactory.TIMES_ROMAN,12)));
table.addCell(new Phrase("TEST",FontFactory.getFont(FontFactory.TIMES_ROMAN,12)));
table.addCell(new Phrase("20/09/1998",FontFactory.getFont(FontFactory.TIMES_ROMAN,12)));
document.add(table);

} catch (Exception e) {
e.printStackTrace();
} finally {
if (document != null) {
document.close();
}
}
}

@Override
public InputStream getStream() {
// Here we return the pdf contents as a byte-array
return new ByteArrayInputStream(os.toByteArray());
}
}

Screenshots

Number Entered



Popup PDF Window