refermycode.com

Develop your world..

Chapter 5: Generating Report With Java POJO Classes.

In our previous chapter we have created a simple report with “Hello World !!!”, In this chapter we will create a report which will print the values using Java POJO classes. POJO means nothing but Plain Old Java Object. It has properties, getters and setters for respective properties.

So let us start with the Design part first,

Step 1:
Create a new report by following the steps in our previous chapter, here I will directly jump to the design part for adding the fields in our report. We are going to design report in Java language hence change the language of report to Java. To change the language click on report in Report Inspector Window and find the language property in Properties window of IReport, by default it is set to Groovy language, click on combo box and change it to Java, as show in following screenshot.

chapter5_0

Step 2:

Fields are the placeholder which will stored the values which we want to display in our report. These value will be set with the help of Java POJO classes which we will see in the later part in this chapter.
For adding the field go into the Report Inspector Window of IReport and click Right Button of mouse on Field and select the “Add Field” option to add the field in report as shown following screenshot.

chapter5_1

Step 3:

After that select added field and rename it by selecting rename option. Jasper provide multiple datatypes for field, parameters and variables. You can change the datatype of Field from property window of IReport. In this chapter we are going to use string datatype to generate the report and String is Default datatype for any field, variable or parameter, hence I am not going to change the datatype. If you want different datatype then you can select the field and change the datatype which you want in your report as shown in following screenshot.

chapter5_2

Step 4:

In this chapter we are just putting the values which is set from Java side so we will remove the other band except Detail and Column Header Band. So drag and drop the required fields in Detail Band. When you add the fields in the Detail Band, we get an option to which value should be display in the field section, mean value which is stored by field or you can show count of the selected field as shown in following screenshot.

chapter5_3

Step 5:

When you used drag and drop method for adding the field in Detail Band of report then Static Text is automatically gets added in the Column Header of report with the label name as Default text in it.

chapter5_4

Step 6:

We can change it by double click in the static text. so we will change the Header labels to standardise our report with proper Header names, After changing the the labels our report design will looks as shown in following screenshot.

chapter5_5

We can see the generated sample XML code (.jrxml) in XML view of IReport. Our jrxml file is

<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="report2" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
<property name="ireport.zoom" value="1.4641000000000006"/>
<property name="ireport.x" value="0"/>
<property name="ireport.y" value="0"/>
<subDataset name="New Dataset 1"/>
<field name="employeeNumber" class="java.lang.String"/>
<field name="employeeName" class="java.lang.String"/>
<field name="employeeAddress" class="java.lang.String"/>
<field name="employeeSalary" class="java.lang.String"/>
<columnHeader>
<band height="33">
    <staticText>
            <reportElement x="15" y="4" width="100" height="20"/>
            <textElement>
                    <font size="10" isBold="true"/>
            </textElement>
            <text><![CDATA[Employee Number]]></text>
    </staticText>
    <staticText>
            <reportElement x="143" y="5" width="100" height="20"/>
            <textElement>
                    <font isBold="true"/>
            </textElement>
            <text><![CDATA[Employee Name]]></text>
    </staticText>
    <staticText>
            <reportElement x="274" y="5" width="100" height="20"/>
            <textElement>
                    <font isBold="true"/>
            </textElement>
            <text><![CDATA[Employee Address]]></text>
    </staticText>
    <staticText>
            <reportElement x="426" y="5" width="100" height="20"/>
            <textElement>
                    <font isBold="true"/>
            </textElement>
            <text><![CDATA[Employee Salary]]></text>
    </staticText>
</band>
</columnHeader>
<detail>
<band height="36">
    <textField>
            <reportElement x="15" y="7" width="100" height="20"/>
            <textElement>
                    <font size="10"/>
            </textElement>
            <textFieldExpression><![CDATA[$F{employeeNumber}]]></textFieldExpression>
    </textField>
    <textField>
            <reportElement x="143" y="7" width="100" height="20"/>
            <textElement/>
            <textFieldExpression><![CDATA[$F{employeeName}]]></textFieldExpression>
    </textField>
    <textField>
            <reportElement x="274" y="7" width="100" height="20"/>
            <textElement/>
            <textFieldExpression><![CDATA[$F{employeeAddress}]]></textFieldExpression>
    </textField>
    <textField>
            <reportElement x="426" y="7" width="100" height="20"/>
            <textElement/>
            <textFieldExpression><![CDATA[$F{employeeSalary}]]></textFieldExpression>
    </textField>
</band>
</detail>
</jasperReport>

We have finished the design phase of report, now let us move on to the Java side.
Step 1:
Create new project by selecting the simple Java Application Setting and add all the necessary libraries which is described in earlier chapter.

Step 2:
We have to display the multiple records by using Java POJO classes, so create a new class with name Employee and create the variables with the same name and datatype which was we used in .jrxml file. Create getter and setter method for each variable.

package com.refermycode.mypackage;
/*
* @author Mayur
*/

public class Employee {
String employeeNumber = "";
String employeeName = "";
String employeeAddress = "";
String employeeSalary = "";
public String getEmployeeAddress() {
return employeeAddress;
}
public void setEmployeeAddress(String employeeAddress) {
this.employeeAddress = employeeAddress;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public String getEmployeeNumber() {
return employeeNumber;
}
public void setEmployeeNumber(String employeeNumber) {
this.employeeNumber = employeeNumber;
}
public String getEmployeeSalary() {
return employeeSalary;
}
public void setEmployeeSalary(String employeeSalary) {
this.employeeSalary = employeeSalary;
}
}

Step 3:
In main class add the following code to generate the PFD.

package com.refermycode.mypackage;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;

/*
* @author Mayur
*/

public class JasperTutorial2 {

public static List addEmployeeInfo() {
List employeeList = new ArrayList();

Employee employee = new Employee();
employee.setEmployeeNumber("1001");
employee.setEmployeeName("Ajit");
employee.setEmployeeAddress("Latur");
employee.setEmployeeSalary("40,000");
employeeList.add(employee);

employee = new Employee();
employee.setEmployeeNumber("1002");
employee.setEmployeeName("Amit");
employee.setEmployeeAddress("Aurangabad");
employee.setEmployeeSalary("50,000");
employeeList.add(employee);

employee = new Employee();
employee.setEmployeeNumber("1004");
employee.setEmployeeName("Aniket");
employee.setEmployeeAddress("Nashik");
employee.setEmployeeSalary("50,000");
employeeList.add(employee);

employee = new Employee();
employee.setEmployeeNumber("1004");
employee.setEmployeeName("Anup");
employee.setEmployeeAddress("Pune");
employee.setEmployeeSalary("60,000");
employeeList.add(employee);

employee = new Employee();
employee.setEmployeeNumber("1005");
employee.setEmployeeName("Kuldeep");
employee.setEmployeeAddress("Hyderabad");
employee.setEmployeeSalary("60,000");
employeeList.add(employee);

employee = new Employee();
employee.setEmployeeNumber("1006");
employee.setEmployeeName("Tushar");
employee.setEmployeeAddress("Shirdi");
employee.setEmployeeSalary("50,000");
employeeList.add(employee);

return employeeList;
}

public static void main(String[] args) throws FileNotFoundException {
try {
InputStream inputStream = new FileInputStream("C:/JasperTutorial2/src/com/refermycode/mypackage/Report2.jrxml");
JasperDesign jasperDesign = JRXmlLoader.load(inputStream);
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);

HashMap parameters = new HashMap();
List employeeList = addEmployeeInfo();
JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(employeeList);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, beanColDataSource);
JasperExportManager.exportReportToPdfFile(jasperPrint, "C:/test_jasper.pdf");
} catch (JRException ex) {
Logger.getLogger(JasperTutorial2.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

let us understand, what actually happened in execution of above code.

  1. We have created POJO class to stored the record of employee with the help of getter and setter methods.
  2. In our main class we have read the .jrxml file with the help of InputStream class and stored the definition of design in stream.
  3. After that we have passed this inputstream to the Jasper Report XML Loader (JRXmlLoader) which helps to creates an object of Jasper Design.
  4. Then Jasper Compile Manager take these Jasper Design as input and compile it. It will returns the object of Jasper Report after successful compilation of Jasper Design. In this phase it will generate an intermediate file with .jrfill extension which help us to fill the data in the report design.
  5. Now next phase is to fill the data in report design. We can supply dynamic data with the help of fields and parameters. Parameters holds only value while Field have to stored multiple values, hence we are used collection to stored the data for fields. We use map to store the parameters with their value.
    hence, in short we need following stuff to fill the data into report,
    1. Object of Jasper Report.
    we have create this in steps 1-4.
    2. Parameter map.
    we can use simple map of collection framework.
    3. List of POJO object to store the data for fields.
    here we have to pass this list to the Jasper Report Bean Collection Data Source(JRBeanCollectionDataSource) to create data source for the report.
    Jasper fill manager takes above three things as parameter and generate Jasper Print which we will use to export the report in next step.
  6. After successful generation of jasper print we can export our report into different types of files like pdf,xls,doc,html etc. Jasper Export Manager help to generate the report and write into the desired file.
    In this way the jasper will generate the desire output with help of Java POJO classes and collection framework.

Following is the generated sample pdf of our above code.

chapter5_6