iReport Pie Chart Report

March 17, 2009

This blog i will show how to make a pie chart report. here i used very simple report. I have one table called category it has different categoryno with categroy name. Each category has subcategory. I want to show how many categories are there by pie chart.  Category table struc and data link will give you the table structure and some sample data. I used MySql database for this report.

  • Create New document from iReport. use this band value title = 30, columnHeader = 15, detail = 15 and summary = 300 and others = 0.
  • Add Query:     select category “Cat No”, subcat_name “category Name”, count(category) total from category
    group by category order by 1
  • Add 3 fields – Cat No, Category Name, Total to Detail band.    detail-band
  • Click the char button and select the Pie 3D. I put its width is 268 and height is 203.   ui2
  • right click on chart and select cart properties. select cart data tab, select the Details tab. and put the value as follows -  for Key Expression = $F{category Name} ,  Value Expression = $F{total},  Label Expression = $F{category Name}
  • click close.
  • b4 execute you must select your database connection. now click Execute with data connection. the output file will looks like as follows

output-pie-report


Fast file copy and move by java

January 11, 2009

The following method does very fast file copy from one location to another location.

public boolean copyTo(File source, File destination) {
try {
FileInputStream fis = new FileInputStream(source);
FileOutputStream fos = new FileOutputStream(destination);

byte []buf = new byte[4096];
int loaded = 0;
while ((loaded = fis.read(buf)) > 0 ) {
fos.write(buf, 0, loaded);
}
fis.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}

Here i used 4096 byte buffer thats the key for fast copy.this value is optimize value from from different tested values.

The following method does very fast file move from one location to another location.

public boolean moveTo(File source, File destination) {
boolean isRenamed;
if(isPathExists(destination.getAbsolutePath())){
destination.delete();
}

isRenamed = source.renameTo(destination);
if(!isRenamed){
copyTo(source,destination);
source.delete();
}
return isRenamed;

}

public boolean isPathExists(String path){
File location = new File(path);
return location.exists();
}

The key of fast moving is the rename function.


A quick tour to iReport (using Route US I95)

January 10, 2009

Here i am describing some important features of iReport. My another blog has described how to create a report using iReport and how to execute that report by eclipse java project.

# set ClassPath: put your desire database driver jar file into the lib folder of iReport. you can do that Options->class path-> add jar

# Element:

-Static text is used Label and Text field is used for Value.

-Bar Code tools is used for print bar code. barcode make sure the font has to select that you are going to use for printing the barcode. to set font for bar code right click on bar code element and select properties and select BarCode tab and set the appropiate type that is font.

-SubReport: this is very important element. master-details it is mostly used. when you need a master details report that time it is required. For example,  an itemlist according to category. a report that header portion shows the category details and also show all the item of that category. you can show all the categroy group by one paritcular field among category’s details. that time you have to select that field as group by. like ‘Category A’ shows the details of category at the header and body show all the item of ‘Category A’. so this item list of ‘Category A’ is the sub report. for grouping of any category description fileds you have to select that filed group by. to do you have to select that field on right boutton click and select Group selected items.

- Field, Variable & Parameter: we can create variable which will only used as variable, denoted as $V{name}, that scope is the whole report. Field,denoted as $F{name}, that is used for showing a field in the report.Parameter ,denoted as $P{name}, that takes data from java class or master report to subreport.

-Connections/Data Sources: this is the way from where you feed the data to your report. Most common Connection is JDBC connection you can used this connection for connecting your RDMS Database like Oracle, MySql, MsSql, PostGresql, MSAccess… etc. You can also used XML data source that time you have to select the xml file as a data source. JavaBeans source is suppose your program class file List contains some data, such case report grabbed data from that list. Hibernate Connection is HQL database connection. lets say how you do that, here i described how make your data source as XML datasource, click Data->Connections/DataSources->New->XML file data source -> Next ->Select the xml file. and choose Use the report Xpath, click the test button for confirmation of your datasource connection. if your xml file has master details data like

<Category name=”A” noOfItem=2>

<Item sku=”2322″ productName=”Poland Spring Water”/>

….

</Category>

lets set the datasource in the Report Query.

For masters, Category details, click Data->Report Query select Report Query tab, Query Language: XPath, Query: //Category click the Read Fields button then all the fields of Category will shows.

For sub-report, Item list,  open subreport & click Data->Report Query select Report Query reportquery1tab, Query Language: XPath, Query: /Category/Item click the Read Fields button then all the fields of Category will shows.

# Some common error:

1.if iReport shows casting error so it means it cant convert to desire type to actual type. for example – the text field type is Double and xml data is String such this case we can set the expression as: new Double($F{price}).

2.Boolean converting error. suppose reprot has Sex field and textfiled type is boolean but xml data is like that – sex=”0″ so it will generate error. if we want to show Male/Female or conditionally show a value, do follows this step. change the text file type is java.lang.String and edit Expression as

( $F{sex}.equals(“0″) ? “Male” : “Female”)

# Band: iReport breaks the report by several bands. we define the band as section or portion of whole report. this is as a good features. you can design as you want. if you want to show the title just set the title band hight value or not set the hieght value is zero, event we can show it conditionally if i used Print when expresstion value. if we used group by for a particular filed then we will get that Column Header and footer so that we can show the some summary information of the group. If there is no data so we can show this information using noData Band.

o another topic, if you want move more element, shift+click for selection and slow move use arrow , fast move use shift+arrow.


A simple iReport (using iReport and eclipse)

January 10, 2009

this time i described how make one very simple report. lets download iReport. here i download iReport-3.0.0 zip file. This version i found mysql driver jar found in the lib folder but i did not see the oracle(ojdbc14.jar) driver jar file. if you would like to use oracle please put this jar file into the lib folder.

# Create Connection:  Click Data-> Connections/Datasources. Click New button. select Database JDBC Connection -> Next Button ->now put your database information. i gave here one screen shot dbconnection window

Pressing test button iReport shows the connection status. if you get any error like oracle/mysql class not found, make sure the lib folder contain your database driver jar file. if you get same excepton so go Options -> ClassPath -> Click add jar. now select the related database jar file.

# create a report using iReport:  File -> Report Wizard ->

template : none, connection: mysql, SQL Query : Select *from Person.

Next-> select all columns.  Next -> (do not select any group 1 value, if you want to show the report by any group you can select any column.)  Next -> Tabular Layout (ClassicT) Finish.

now you get one report. now you can change the report title. it looks

mainscreen1Now you can test this report by clicking  Build->Complie or Build->Execute (empty connection) or Build-> Execute (active connection). after compile the jaspar file will generate where the iReport.exe file is located. empty connection will show only report without data but active connection will show the data.

Since we want to show only first 30 id records, so we have create a parameter variable. this parameter determine how many record we want to show. to create a parameter click View -> Parameter then a window will come, here we can create variable which will only used as variable that scope is the whole report, field that is used for showing a field in the report and finally parameter that takes data from java class.  Click New button ->parameter name: p_id, class type: java.lang.Integer, use as Prompt uncheckd, default Value expression : new Integer(0) that means we assing a default value for this parameter. iReport always consider all the value as Object not primitive thats why i set write as new Integer(0) Paramete Description: paraeter ID . now click OK.

Now lets set the condition in the query. Click Data-> Report Query now put the following line – select *from person where id < $P{p_id}  here $P{p_id} is the parameter. reportquery in iReport $F { name } is means field and $V{ name } is indicate variable. now click OK.

Now save the report as person.jrxml. if you complie this report you will get person.jasper file. let see the description of person table.

create table person ( id number(6), name varchar(20));

# Execute iReport From Java: I used eclipse to create one java program that execute the iReport.  Open eclipse, click New -> New Java Project  Project Name: SimpleiReprot , select Create new project in workspace, select default JRE, select Create separate folders now click Next -> FInish. now create 3 folders ( lib, report-out, report-src) under this project. The project folder structure looks this folder_arch3

now put the person.jrxml and person.jaspar file into report-src folder. report-out folder will use for the pdf report file. now copy all the jar files from ireport’s lib folder into your project lib folder.  now refresh the eclipse project.now set the build path for this project. click the right button on the project and select properties and select the Java Build Path from the left side menu and click the Libraries Tab. it looks as

eclipse project buildpath

eclipse project buildpath

Now Add Jar button from the right side. Now select SimpleiReprot project and explore the lib folder and select all the jar files of lib folder. now click OK. Select Order and Exprot tab and Select All button from right side. Click OK.

I used 2 java files. DBConnector.java used for creating the database connection and SimpleiReport.java used for execute the jasper report.

—————-DBConnector.java

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

/*
* Database connection class.
* it return single instance of connection
* author: rajib_info@yahoo.com
*/

public class DBConnector {

public static Connection getConnection() {
Connection connection = null;

if (connection != null) {
return connection;
}

try {
Class.forName(“org.gjt.mm.mysql.Driver”).newInstance();
connection = DriverManager.getConnection(
“jdbc:mysql://localhost/development”, “root”, “”);
} catch (Exception e) {
e.printStackTrace();
}
return connection;

}
}

————————- SimpleiReport.java

import java.sql.Connection;
import java.util.HashMap;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporter;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;

/*
* this class generates one pdf file from jaspar file. here i used one condition that filter
* only first 30 records.
* author: rajib_info@yahoo.com
*/

public class SimpleiReport {

public static void main(String[] args) {
// database connection
Connection connection = null;

String jasperFile = “./report-src/person.jasper”;
String pdfFile = “./report-out/personList.pdf”;

// params used for passing the parameter.
HashMap<String,Integer> params = new HashMap<String,Integer>();
params.put(“p_id”, 30);
try {
// get database connection.
connection = DBConnector.getConnection();

JasperPrint print = JasperFillManager.fillReport(jasperFile, params,
connection);
JRExporter exporter = new net.sf.jasperreports.engine.export.JRPdfExporter();
exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME,
pdfFile);
exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
exporter.exportReport();
System.out.println(“Created file: ” + pdfFile);

} catch (JRException e) {
e.printStackTrace();
System.exit(1);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}

If you want to use other database change the DBConnector class.eclipse-mainClick the right button on the SimpleiReport file and select Run As -> 3 Java Application. Or you can set Run configaration from the Run->Run Configuration. this run configuration window you have to select the main class. the output console looks

——- output console

Created file: ./report-out/personList.pdf

and personList.pdf file will generate under the report-out folder. the pdf looks as

Jasper report output as pdf

Jasper report output as pdf

Please ask me if you have any problem or can give me any suggestion.

Thanks

Rajib.


Filter data when insert into List

January 4, 2009

We use list for storing data but there is no way to insertation filter. I mean when i want to insert a specific type of data like a list that always store which string has this value. here i gave one example list that  always filterine during the insertation period. lets consider we have one collection that contain all the car make names. now we need one list that will store only Honda make name.

I used here two class HondaList and ToyotaList that act as list.

———————-HondaList.java

import java.util.LinkedList;
class HondaList extends LinkedList<String> {

public HondaList() {
super();
}

public boolean add(String make) {
if (make.indexOf(“Honda”) == -1) {
return false;
} else {
super.add(make);
return true;
}
}
}
—————- ToyotaList.java

import java.util.LinkedList;
class ToyotaList extends LinkedList<String> {

public ToyotaList() {
super();
}

public boolean add(String make) {
if (make.indexOf(“Toyota”) == -1) {
return false;
} else {
super.add(make);
return true;
}
}
}

—————— Main Class

public class ListDataFilterDemo {
private HondaList hondaList;
private ToyotaList toyotaList;

public ListDataFilterDemo() {
this.hondaList = new HondaList();
this.toyotaList = new ToyotaList();
}

public void addData(){
hondaList.add(“Honda Civic 2002″);
hondaList.add(“Honda Accord 2002″);
hondaList.add(“Toyota Corolla 2002″);

toyotaList.add(“Honda Civic 2002″);
toyotaList.add(“Honda Accord 2002″);
toyotaList.add(“Toyota Corolla 2002″);

for (String make : hondaList) {
System.out.println(make);
}

for (String make : toyotaList) {
System.out.println(make);
}
}

public static void main(String[] args) {
try {
ListDataFilterDemo demo = new ListDataFilterDemo();
demo.addData();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

————- Output

Honda Civic 2002
Honda Accord 2002
Toyota Corolla 2002

HondaList adds all data except Honda data same ToyotaList does.


Follow

Get every new post delivered to your Inbox.