Thursday 30 October 2014

How to Convert Tables 'MyISAM' to 'InnoDB' Engine in mysql database


-- QUERY TO CONVERT TABLES 'MyISAM' to 'InnoDB' Engine

SET @DATABASE_NAME = 'database';

SELECT  CONCAT('ALTER TABLE ', table_name, ' ENGINE=InnoDB;') AS sql_statements
FROM    information_schema.tables AS tb
WHERE   table_schema = @DATABASE_NAME
AND     `ENGINE` = 'MyISAM'
AND     `TABLE_TYPE` = 'BASE TABLE'
ORDER BY table_name DESC;


-- QUERY TO CONVERT TABLES 'InnoDB' TO 'MyISAM' ENGINE


SET @DATABASE_NAME = 'database';

SELECT  CONCAT('ALTER TABLE ', table_name, ' ENGINE=MyISAM;') AS sql_statements
FROM    information_schema.tables AS tb
WHERE   table_schema = @DATABASE_NAME
AND     `ENGINE` = 'InnoDB'
AND     `TABLE_TYPE` = 'BASE TABLE'
ORDER BY table_name DESC;



Monday 9 June 2014

Create a CRUD application using with DAO design pattern.


DAO or Data Access Object design pattern is good example of abstraction and encapsulation object oriented principles.
It separates persistence logic is a separate layer called Data access layer which enable application to react safely on change in Persistence mechanism.
In short Data Access Object or DAO design pattern is way to reduce coupling between Business logic and Persistence logic

DAO pattern allows you to encapsulate code for performing CRUD operation against persistence from rest of application.
Which means any change on persistence logic will not affect other layers of application which is already tested.

Here i am showing you how to make a CRUD application using with DAO design pattern.




create a table in Mysql database

CREATE TABLE student (
RollNo INT(10)  PRIMARY KEY NOT NULL,
NAME  VARCHAR(50) NOT NULL,
Course VARCHAR(25) NOT NULL,
Address VARCHAR(255)
);


----------------- ConnectionFactory.java -------------------


package com.ramsis.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectionFactory {
String driverClassName = "com.mysql.jdbc.Driver";
String connectionUrl = "jdbc:mysql://localhost:3306/test";
String dbUser = "root";
String dbPwd = "root";

private static ConnectionFactory connectionFactory = null;

private ConnectionFactory() {
try {
Class.forName(driverClassName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}

public Connection getConnection() throws SQLException {
Connection conn = null;
conn = DriverManager.getConnection(connectionUrl, dbUser, dbPwd);
return conn;
}

public static ConnectionFactory getInstance() {
if (connectionFactory == null) {
connectionFactory = new ConnectionFactory();
}
return connectionFactory;
}
}

------------------------ StudentBean.java --------------------------
package com.ramsis.dao;

import java.io.Serializable;

public class StudentBean implements Serializable {
int rollNo;
String name="";
String course="";
String address="";

public StudentBean() {

}

public StudentBean(int roll, String name, String course, String address) {
this.rollNo = roll;
this.name = name;
this.course = course;
this.address = address;
}

public int getRollNo() {
return rollNo;
}

public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getCourse() {
return course;
}

public void setCourse(String course) {
this.course = course;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

}


------------------------- StudentJDBCDAO.java ------------------------------
package com.ramsis.dao;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class StudentJDBCDAO {
Connection connection = null;
PreparedStatement ptmt = null;
ResultSet resultSet = null;

public StudentJDBCDAO() throws IOException{

}

private Connection getConnection() throws SQLException {
Connection conn;
conn = ConnectionFactory.getInstance().getConnection();
return conn;
}

public void add(StudentBean studentBean) {
try {
String queryString = "INSERT INTO student(RollNo, Name, Course, Address) VALUES(?,?,?,?)";
connection = getConnection();
ptmt = connection.prepareStatement(queryString);
ptmt.setInt(1, studentBean.getRollNo());
ptmt.setString(2, studentBean.getName());
ptmt.setString(3, studentBean.getCourse());
ptmt.setString(4, studentBean.getAddress());
ptmt.executeUpdate();
System.out.println("Data Added Successfully");
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (ptmt != null)
ptmt.close();
if (connection != null)
connection.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}

}

}

public void update(StudentBean studentBean) {

try {
String queryString = "UPDATE student SET Name=? WHERE RollNo=?";
connection = getConnection();
ptmt = connection.prepareStatement(queryString);
ptmt.setString(1, studentBean.getName());
ptmt.setInt(2, studentBean.getRollNo());
ptmt.executeUpdate();
System.out.println("Table Updated Successfully");
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (ptmt != null)
ptmt.close();
if (connection != null)
connection.close();
}

catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();

}
}
}

public void delete(int rollNo) {

try {
String querySelectId = "SELECT RollNo FROM student where RollNo=?";
String queryString = "DELETE FROM student WHERE RollNo=?";
connection = getConnection();
ptmt = connection.prepareStatement(queryString);
ptmt.setInt(1, rollNo); 
ptmt.executeUpdate();
System.out.println("Data deleted Successfully");
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (ptmt != null)
ptmt.close();
if (connection != null)
connection.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}

}

}

public void findAll() {
try {
String queryString = "SELECT * FROM student";
connection = getConnection();
ptmt = connection.prepareStatement(queryString);
resultSet = ptmt.executeQuery();
while (resultSet.next()) {
System.out.println("Roll No " + resultSet.getInt("RollNo")
+ ", Name " + resultSet.getString("Name") + ", Course "
+ resultSet.getString("Course") + ", Address "
+ resultSet.getString("Address"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (resultSet != null)
resultSet.close();
if (ptmt != null)
ptmt.close();
if (connection != null)
connection.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}

}
}
}


----------------------------- Main.java ------------------------------
package com.ramsis.dao;

import java.io.IOException;
import java.util.Scanner;

public class Main {
public static void main(String[] args) throws IOException{
Scanner scan  = new Scanner(System.in);
StudentJDBCDAO jdbc = new StudentJDBCDAO();
StudentBean bean = new StudentBean();

String ch="";
String num="";
String name="";
String course="";
String address="";
Integer rollNo;


do{        
System.out.println("please number what you want to do ? ");
System.out.println("1) Add data. ");
System.out.println("2) Update data. ");
System.out.println("3) delete data. ");
System.out.println("4) Show data. ");

num = scan.next();

if(num.equals("1")){

System.out.println("Enter the name : ");
name = scan.next();
bean.setName(name);

System.out.println("Enter Roll Number : ");
rollNo = scan.nextInt();
bean.setRollNo(rollNo);

System.out.println("Enter Course : ");
course = scan.next();
bean.setCourse(course);

System.out.println("Enter the Address : ");
address = scan.next();
bean.setAddress(address);
jdbc.add(bean);
}

else if(num.equals("2")){

System.out.println("Enter the name : ");
name = scan.next();
bean.setName(name);

System.out.println("Enter the roll Number : ");
rollNo = scan.nextInt();
bean.setRollNo(rollNo);
jdbc.update(bean);

}

else if(num.equals("3")){

System.out.println("Enter the roll Number for delete : ");
rollNo = scan.nextInt();
bean.setRollNo(rollNo);
jdbc.delete(rollNo);
}
else if(num.equals("4")){

jdbc.findAll();

}
else
{
System.out.println("Please enter 1 , 2 , 3 , 4 only.");
}


ch = scan.next();
}while(ch.equals("y") || ch.equals("Y"));
System.out.println("Successfully Exit.");
System.exit(0);


}
}



Monday 5 May 2014

File Upload Validation with JavaScript Extension

 User can not Upload .jsp , .php Extensions type file.




<html>
<head>    
<script type="text/javascript">

function ChkfileExt(){
var id = document.getElementById('FileUpload2');
var id1 = document.getElementById("FileUpload2").value;

var img = id.value;
var n = img.match('.jsp');
//alert(n);
if (n == '.jsp') 
{
alert("Not Authorised , Only pdf, txt, csv, doc, docx, xls, xlsx ,jpg files can be uploaded");
return false;
}

var n = img.match('.php');
//alert(n);
if (n == '.php') 
{
alert("Not Authorised , Only pdf ,csv, doc, docx, xlsx ,jpg files can be uploaded");
return false;
}


var fileName =id.value;

if( id1=== "" ) {
//alert("Please upload any file.");
}
else{
if( fileName.lastIndexOf(".jpg")==-1 && fileName.lastIndexOf(".JPG")==-1 && fileName.lastIndexOf(".pdf")==-1 && fileName.lastIndexOf(".txt")==-1 && fileName.lastIndexOf(".csv")==-1 && fileName.lastIndexOf(".doc")==-1 && fileName.lastIndexOf(".docx")==-1 && fileName.lastIndexOf(".xls")==-1 && fileName.lastIndexOf(".xlsx")==-1){
alert("Only pdf, txt, csv, doc, docx, xls, xlsx ,jpg files can be uploaded");
return false;
}
}

}
</script>
</head>
<form id="form1" name="AddBillStatus" action="act.html" METHOD="POST" ENCTYPE="multipart/form-data"  >
<table align="center" class="sample" width="50%">

<br/><br/><br/><br/>
<tr>
<td nowrap="nowrap"> <b>Upload File</b></td>
<td ><input type="file" name="FileUpload2" id="FileUpload2" onChange="javascript:return ChkfileExt();" /> </td>
</tr>             
<tr>
<td>&nbsp;</td>
<td >
<input type="submit" name="btnAdd" value="Save" id="btnAdd" onClick="javascript:return ChkfileExt();" />&nbsp;&nbsp;&nbsp; &nbsp;&nbsp; &nbsp;
<input id="Button2"  type="reset" value="reset"  />&nbsp; &nbsp;
</td>
</tr>
</table>
</form>
</html>

Wednesday 22 January 2014

Create Jesper Report in Jsp and download pdf report from the website



/* Save as : "jesper.jsp" */

<%@ page  import="java.io.*"%>
<%@ page  import="java.sql.Connection"%>
<%@ page  import="java.sql.DriverManager"%>
<%@ page  import="java.util.HashMap"%>
<%@ page  import="java.util.*"%>
<%@ page  import="net.sf.jasperreports.engine.*"%>
<%@ page  import="net.sf.jasperreports.engine.design.JasperDesign"%>
<%@ page  import="net.sf.jasperreports.engine.xml.JRXmlLoader"%>


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h2>Jesper Report</h2>

<form method="POST" action="jesper.jsp?rpt=1">
<input type="Submit" name="submit" value="Generate Report"/>
</form>
<%
String sign = request.getParameter("rpt");
if(sign==null)
{
sign="0";
}
if(sign.equals("0"))
{out.print("<b>Please click the button and download the report.</b>");
}else{
%>

<%
Calendar calendar = new GregorianCalendar();
String am_pm;
int datetoday = calendar.get(Calendar.DATE);
int month = calendar.get(Calendar.MONTH);
int year = calendar.get(Calendar.YEAR);
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);

%>
<%
Connection conn = null;
String s = String.valueOf(second);
String d =  String.valueOf(datetoday);
String m =  String.valueOf(month);
String y = String.valueOf(year);
String date_time =  String.valueOf(s+d+m+y);
//out.println(date_time);

try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/data", "root", "gftsd4");

InputStream input = new FileInputStream(new File("D:/MyInstall/Apache Software Foundation/Tomcat 7.0_JSP/webapps/Jesper_Report_Jsp/EmployeeReport.jrxml"));
JasperDesign jasperDesign = JRXmlLoader.load(input);

out.println("Compiling Report Designs<br/>");
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);

out.println("Creating JasperPrint Object<br/>");
Map parameters = new HashMap ();
parameters.put("Id", "select First_Name, Last_Name from employee where Id < 100");

JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport,parameters,conn);

//Exporting the report
OutputStream output = new FileOutputStream(new File("D://EmployeeReport-'"+date_time+"'.pdf"));

JasperExportManager.exportReportToPdfStream(jasperPrint, output);


out.println("Report Generation Complete");
out.print("<br/><br/>");
out.println("Generated Report name is:  "+"<b>EmployeeReport-"+date_time+".pdf</b>");

/* File download code start*/

response.setContentType("application/pdf");
response.setHeader("Content-Disposition","attachment;filename=EmployeeReport-'"+date_time+"'.pdf");
File file = new File("D://EmployeeReport-'"+date_time+"'.pdf");
FileInputStream fileIn = new FileInputStream(file);
ServletOutputStream out1 = response.getOutputStream();

byte[] outputByte = new byte[4096];
//copy binary contect to output stream
while(fileIn.read(outputByte, 0, 4096) != -1)
{
out1.write(outputByte, 0, 4096);
}
fileIn.close();
out1.flush();
out1.close();  

/* File download code close */

conn.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (JRException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
}

%>
</body>
</html>


//------------------------ EmployeeReport.jrxml ----------------------



















<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE jasperReport PUBLIC "//JasperReports//DTD Report Design//EN"
"http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">
<jasperReport name="EmployeeReport_aman.kumar">
<parameter name="Id" class="java.lang.String"/>
<queryString>
<![CDATA[$P!{Id}]]>
</queryString>
<field name="First_Name" />
<field name="Last_Name" />

<title>
<band height="50">
<staticText>
<reportElement x="0" y="0" width="180" height="15"/>
<textElement/>
<text><![CDATA[Jasper Report - By Java]]></text>
</staticText>
</band>
</title>

<pageHeader>
<band height="50">
<image>
<reportElement x="0" y="0" width="100" height="50"/>
<imageExpression><![CDATA["D://cooltext769884152.png"]]></imageExpression>
</image>
<staticText>
<reportElement x="0" y="0" width="69" height="24" />
<textElement verticalAlignment="Bottom" />
<text>
<![CDATA[First Name: ]]>
</text>
</staticText>
<staticText>
<reportElement x="100" y="0" width="79" height="24" />
<text>
<![CDATA[Last Name: ]]>
</text>
</staticText>
</band>
</pageHeader>

<detail>
<band height="30">
<textField>
<reportElement x="0" y="0" width="69" height="24" />
<textFieldExpression>
<![CDATA[$F{First_Name}]]>
</textFieldExpression>
</textField>
<textField>
<reportElement x="100" y="0" width="69" height="24" />
<textFieldExpression>
<![CDATA[$F{Last_Name}]]>
</textFieldExpression>
</textField>
</band>
</detail>
<summary>
<band height="50">
<textField>
<reportElement x="439" y="22" width="100" height="20" />
<textFieldExpression><![CDATA[$V{PAGE_NUMBER}]]></textFieldExpression>
</textField>
</band>
</summary>

</jasperReport> 

Wednesday 4 December 2013

How to Set Classpath of jar files and run JDBC code

Please follow the below Steps.


1) Create a 'contact' Table in Mysql 'Test' database

CREATE TABLE `contact` (
  `Id` bigint(20) NOT NULL,
  `Name` varchar(30) DEFAULT NULL,
  `Email` varchar(20) DEFAULT NULL,


2) create a folder/package and rename it as "JDBC" copy as below this java code and save it as "JDBC1.java".


package JDBCTest;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class JDBC1 {

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

Connection con= null;
ResultSet rs = null;
PreparedStatement psmt = null;

Integer Id=2005;
String Name ="Aman";
String Email ="aman@gmail.com";

try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Test","root","ABCD");

psmt = con.prepareStatement("select * from contact");
rs = psmt.executeQuery();

while(rs.next())
{
System.out.println("Id is: "+rs.getInt("Id")+" name is: "+ rs.getString("Name")+" Email is: "+rs.getString("Email"));    
}

psmt = con.prepareStatement("insert into contact (Id,Name,Email) values(?,?,?)");
psmt.setInt(1,Id);
psmt.setString(2,Name);
psmt.setString(3,Email);
int chk = psmt.executeUpdate();
if(chk>0){
System.out.println("\ndata has been inserted successgully auth table..");
}
else{System.out.println("Data Insertion error..");}


}
catch(Exception ex){

ex.printStackTrace();
}
finally{
rs.close();
psmt.close();
con.close();
}

}
}

 3) download this jar "mysql-connector-java-3.1.7-bin.jar"  in this url: http://www.java2s.com/Code/Jar/m/Downloadmysqlconnectorjava5114binjar.htm 
 4) create a folder/package and rename it "sqljar" and put the jar in it.

 5) copy the below code and save it as "Run.bat" 
  javac -cp "sqljar\*;." -d . JDBC1.java
  java -cp "sqljar\*;." JDBCTest.JDBC1
  pause;

Wednesday 13 November 2013

Sorting ArrayList with custom fields by Id, Name , City , Age using Comparator Interface in java


package TestCollection;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;

class SetData{
  public Integer id;
  private String name;
  private String city;
  private Integer age;
  
  public SetData (Integer id, String name, String city, Integer age) {
this.id = id;
this.name = name;
this.city = city;
this.age = age;
}
  
public Integer getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String nity) {
this.city = city;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}

public String toString(){

return "[" + " ID: " + this.getId() + " Name: "+ this.getName() + " City: " + this.getCity() + " Age: " + this.getAge() +"]";
}

}

class Sample2{
public static void main(String args[]){
   new Sample2();
Scanner scan  = new Scanner(System.in);
SetData setdata1 = new SetData(101,"Aman","Noida",28);
SetData setdata2 = new SetData(119,"Vijay","Delhi",25);
SetData setdata5 = new SetData(204,"chetan","Noida",28);
SetData setdata3 = new SetData(601,"Rajesh","Ghaziabad",27);
SetData setdata4 = new SetData(701,"Brijesh","Noida",26);
List <SetData> l1 = new ArrayList <SetData>();
List  l2 = new ArrayList();
l1.add(setdata1);
l1.add(setdata2);
l1.add(setdata3);
l1.add(setdata4);
l1.add(setdata5);
//l2.add(l1);
         
Iterator itr = l1.iterator();
while(itr.hasNext()){
Object o = itr.next();
//System.out.println(o);
}
Collections.sort(l1,new MyIdComparable1());
itr = l1.iterator();
System.out.println("------------------Sort By ID----------------------");
while(itr.hasNext()){
Object o = itr.next();
System.out.println(o);
}
Collections.sort(l1,new MyNameComparable2());
System.out.println("------------------Sort By Name----------------------");
for(Object name : l1){
System.out.println(name);
}
Collections.sort(l1,new MyCityComparable3());
System.out.println("------------------Sort By City----------------------");
for(Object city : l1){
System.out.println(city);
}
Collections.sort(l1,new MyAgeComparable4());
System.out.println("------------------Sort By Age----------------------");
for(Object age : l1){
System.out.println(age);
}
}
}

class MyIdComparable1 implements Comparator <SetData>{
public int compare(SetData s1, SetData s2){
return (s1.getId()<s2.getId() ? -1 : (s1.getId()==s2.getId() ? 0 : 1));
}

class MyNameComparable2 implements Comparator <SetData>{
public int compare(SetData s1, SetData s2){
return (s1.getName().compareToIgnoreCase(s2.getName()));
}

class MyCityComparable3 implements Comparator <SetData>{
public int compare(SetData s1, SetData s2){
return (s1.getCity().compareToIgnoreCase(s2.getCity()));
}

class MyAgeComparable4 implements Comparator <SetData>{
public int compare(SetData s1, SetData s2){
return (s1.getAge()<s2.getAge() ? -1 : (s1.getAge()==s2.getAge() ? 0 : 1));
}


// Out Put :

Thursday 7 November 2013

How to create a report using Jasper Report in java

Jasper Report is an open source java reporting engine. It is a Java class library, and is not meant for end users, but rather is targeted towards Java developers who need to add reporting capabilities to their applications.

Here i am showing you, how to create a reaport with Jasper Reporting engine in Eclipse.

Requirements 

jdk 1.6
Eclipse IDE

commons-beanutils-1.8.0.jar
commons-collections-2.1.1.jar
commons-digester-2.1.jar
commons-javaflow-20060411.jar
commons-lang-2.1.jar
commons-logging-1.1.1.jar
iText-2.1.7.js2.jar
jasperreports-5.5.0.jar
mysql-connector-java-3.1.7-bin.jar
servlet-api.jar



//-------------------- Save as ReportGenerator.java ----------------------------

package com.ramsis;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRResultSetDataSource;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;

public class ReportGenerator {

Connection conn;

public void generateReport() {

try {
//Class.forName("oracle.jdbc.driver.OracleDriver");
//conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","ABCD");
Class.forName("com.mysql.jdbc.Driver");
//con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","public");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/gts","root","public");
System.out.println("Loading Report Designs");
InputStream input = new FileInputStream(new File("jrxml/EmployeeReport.jrxml"));
JasperDesign jasperDesign = JRXmlLoader.load(input);

System.out.println("Compiling Report Designs");
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);

System.out.println("Creating JasperPrint Object");
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("ReportTitle", "PDF JasperReport");

JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport,null,conn);

//Exporting the report
OutputStream output = new FileOutputStream(new File("Report/EmployeeReport4.pdf"));

JasperExportManager.exportReportToPdfStream(jasperPrint, output);

System.out.println("Report Generation Complete");
conn.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (JRException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new ReportGenerator().generateReport();
}

}


//----------------------- Save as EmployeeReport.jrxml ------------------------

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE jasperReport PUBLIC "//JasperReports//DTD Report Design//EN"
"http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">
<jasperReport name="EmployeeReport_aman.kumar">
<queryString>
<![CDATA[select First_Name, Last_Name from employee e]]>
</queryString>
<field name="First_Name" />
<field name="Last_Name" />
<title>
<band height="50">
<staticText>
<reportElement x="0" y="0" width="180" height="15"/>
<textElement/>
<text><![CDATA[Jasper Report - By Java]]></text>
</staticText>
</band>
</title>
<pageHeader>
<band height="30">
<staticText>
<reportElement x="0" y="0" width="69" height="24" />
<textElement verticalAlignment="Bottom" />
<text>
<![CDATA[First Name: ]]>
</text>
</staticText>
<staticText>
<reportElement x="100" y="0" width="79" height="24" />
<text>
<![CDATA[Last Name: ]]>
</text>
</staticText>
</band>
</pageHeader>
<detail>
<band height="30">
<textField>
<reportElement x="0" y="0" width="69" height="24" />
<textFieldExpression>
<![CDATA[$F{First_Name}]]>
</textFieldExpression>
</textField>
<textField>
<reportElement x="100" y="0" width="69" height="24" />
<textFieldExpression>
<![CDATA[$F{Last_Name}]]>
</textFieldExpression>
</textField>
</band>
</detail>
</jasperReport>


Out Put:




//------------------------- Save as HelloJasper.java ---------------------

package com.ramsis;

import java.util.HashMap;
import java.util.Map;

import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRResultSetDataSource;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;
import net.sf.jasperreports.view.JasperViewer;

public class HelloJasper {

public static void main(String args[]){

String reportSource = "jrxml/HelloReportWorld.jrxml";
String reportDest = "jrxml/HelloReportWorld.html";



Map <String, Object> params = new HashMap <String, Object>();

//params.put("reportTitle", "Hello Report World");
//params.put("author", "Craig Conover");
//params.put("startDate", (new java.util.Date()).toString());


try
{
JasperReport jasperReport =
JasperCompileManager.compileReport(reportSource);

JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, new JREmptyDataSource());

JasperExportManager.exportReportToHtmlFile(
jasperPrint, reportDest);
JasperViewer.viewReport(jasperPrint);
}

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

}

//-------------------------- Save as HelloReportWorld.jrxml ------------------



<jasperReport name="HelloReportWorld">

<detail>
<band height="200">
<staticText>
<reportElement mode="Opaque" x="50" y="10" width="500" height="30" />
<text><![CDATA[ ID Name Phone City ]]></text>
</staticText>

<staticText>
<reportElement x="50" y="20" width="500" height="30" />
<text><![CDATA[101 Aman Kumar 997152663 Noida ]]></text>
</staticText>

<staticText>
<reportElement x="50" y="30" width="500" height="30" />
<text><![CDATA[102 Suraj Kumar 929300440 New Delhi ]]></text>
</staticText>

<staticText>
<reportElement x="50" y="40" width="500" height="30" />
<text><![CDATA[102 Pavan Yadav 9293344550 Noida ]]></text>
</staticText>
</band>
</detail>
</jasperReport>


Out Put: