Listing 1
<?xml version="1.0" encoding="UTF-8" ?>
<!-- Created with iReport - A designer for JasperReports -->
<!DOCTYPE jasperReport PUBLIC "//JasperReports//DTD Report Design//EN"
"http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">
<jasperReport
name="sampleReport"
columnCount="1"
printOrder="Vertical"
orientation="Portrait"
pageWidth="595"
pageHeight="842"
columnWidth="555"
columnSpacing="0"
leftMargin="20"
rightMargin="20"
topMargin="30"
bottomMargin="30"
whenNoDataType="NoPages"
isTitleNewPage="false"
isSummaryNewPage="false">
<property name="ireport.scriptlethandling" value="0" />
<import value="java.util.*" />
<import value="net.sf.jasperreports.engine.*" />
<import value="net.sf.jasperreports.engine.data.*" />
<reportFont name="Arial_Normal" isDefault="true" fontName="Arial" size="8" isBold="false"
isItalic="false" isUnderline="false" isStrikeThrough="false" pdfFontName="Helvetica"
pdfEncoding="Cp1252" isPdfEmbedded="false"/>
<reportFont name="Arial_Bold" isDefault="false" fontName="Arial" size="8" isBold="true"
isItalic="false" isUnderline="false" isStrikeThrough="false" pdfFontName="Helvetica-Bold"
pdfEncoding="Cp1252" isPdfEmbedded="false"/>
<parameter name="ReportTitle" isForPrompting="true" class="java.lang.String"/>
<parameter name="NoOfGames" isForPrompting="true" class="java.lang.Integer"/>
<field name="bowlerName" class="java.lang.String"/>
<field name="game1" class="java.lang.Integer"/>
<field name="game2" class="java.lang.Integer"/>
<field name="game3" class="java.lang.Integer"/>
<variable name="noOfGames" class="java.lang.Integer" resetType="Report"
calculation="System">
<initialValueExpression><![CDATA[$P{NoOfGames}]]></initialValueExpression>
</variable>
<background>
<band height="0" isSplitAllowed="true" >
</band>
</background>
<title>
<band height="30" isSplitAllowed="true" >
<textField isStretchWithOverflow="false" pattern="" isBlankWhenNull="false"
evaluationTime="Now" hyperlinkType="None" hyperlinkTarget="Self" >
<reportElement
mode="Transparent"
x="0"
y="0"
width="261"
height="30"
forecolor="#000000"
backcolor="#FFFFFF"
key="textField-1"
stretchType="NoStretch"
positionType="FixRelativeToTop"
isPrintRepeatedValues="true"
isRemoveLineWhenBlank="false"
isPrintInFirstWholeBand="false"
isPrintWhenDetailOverflows="false"/>
<box topBorder="None" topBorderColor="#000000" leftBorder="None"
leftBorderColor="#000000" rightBorder="None" rightBorderColor="#000000"
bottomBorder="None" bottomBorderColor="#000000"/>
<textElement textAlignment="Left" verticalAlignment="Top" rotation="None"
lineSpacing="Single">
<font fontName="Arial" pdfFontName="Helvetica" size="24"
isBold="true" isItalic="false" isUnderline="false" isPdfEmbedded
="false" pdfEncoding ="Cp1252" isStrikeThrough="false" />
</textElement>
<textFieldExpression
class="java.lang.String"><![CDATA[$P{ReportTitle}]]></textFieldExpression>
</textField>
</band>
</title>
<pageHeader>
<band height="20" isSplitAllowed="true" >
<staticText>
<reportElement
mode="Transparent"
x="0"
y="4"
width="50"
height="15"
forecolor="#000000"
backcolor="#FFFFFF"
key="staticText"
stretchType="NoStretch"
positionType="FixRelativeToTop"
isPrintRepeatedValues="true"
isRemoveLineWhenBlank="false"
isPrintInFirstWholeBand="false"
isPrintWhenDetailOverflows="false"/>
<box topBorder="None" topBorderColor="#000000" leftBorder="None"
leftBorderColor="#000000" rightBorder="None" rightBorderColor="#000000"
bottomBorder="None" bottomBorderColor="#000000"/>
<textElement textAlignment="Left" verticalAlignment="Top" rotation="None"
lineSpacing="Single">
<font reportFont="Arial_Bold"/>
</textElement>
<text><![CDATA[Bowler Name]]></text>
</staticText>
<staticText>
<reportElement
mode="Transparent"
x="60"
y="4"
width="30"
height="15"
forecolor="#000000"
backcolor="#FFFFFF"
key="staticText"
stretchType="NoStretch"
positionType="FixRelativeToTop"
isPrintRepeatedValues="true"
isRemoveLineWhenBlank="false"
isPrintInFirstWholeBand="false"
isPrintWhenDetailOverflows="false"/>
<box topBorder="None" topBorderColor="#000000" leftBorder="None"
leftBorderColor="#000000" rightBorder="None" rightBorderColor="#000000"
bottomBorder="None" bottomBorderColor="#000000"/>
<textElement textAlignment="Right" verticalAlignment="Top"
rotation="None" lineSpacing="Single">
<font reportFont="Arial_Bold"/>
</textElement>
<text><![CDATA[Game 1]]></text>
</staticText>
<staticText>
<reportElement
mode="Transparent"
x="100"
y="4"
width="30"
height="15"
forecolor="#000000"
backcolor="#FFFFFF"
key="staticText"
stretchType="NoStretch"
positionType="FixRelativeToTop"
isPrintRepeatedValues="true"
isRemoveLineWhenBlank="false"
isPrintInFirstWholeBand="false"
isPrintWhenDetailOverflows="false"/>
<box topBorder="None" topBorderColor="#000000" leftBorder="None"
leftBorderColor="#000000" rightBorder="None" rightBorderColor="#000000"
bottomBorder="None" bottomBorderColor="#000000"/>
<textElement textAlignment="Right" verticalAlignment="Top"
rotation="None" lineSpacing="Single">
<font reportFont="Arial_Bold"/>
</textElement>
<text><![CDATA[Game 2]]></text>
</staticText>
<staticText>
<reportElement
mode="Transparent"
x="140"
y="4"
width="30"
height="15"
forecolor="#000000"
backcolor="#FFFFFF"
key="staticText"
stretchType="NoStretch"
positionType="FixRelativeToTop"
isPrintRepeatedValues="true"
isRemoveLineWhenBlank="false"
isPrintInFirstWholeBand="false"
isPrintWhenDetailOverflows="false"/>
<box topBorder="None" topBorderColor="#000000" leftBorder="None"
leftBorderColor="#000000" rightBorder="None" rightBorderColor="#000000"
bottomBorder="None" bottomBorderColor="#000000"/>
<textElement textAlignment="Right" verticalAlignment="Top"
rotation="None" lineSpacing="Single">
<font reportFont="Arial_Bold"/>
</textElement>
<text><![CDATA[Game 3]]></text>
</staticText>
<staticText>
<reportElement
mode="Transparent"
x="180"
y="4"
width="30"
height="15"
forecolor="#000000"
backcolor="#FFFFFF"
key="staticText"
stretchType="NoStretch"
positionType="FixRelativeToTop"
isPrintRepeatedValues="true"
isRemoveLineWhenBlank="false"
isPrintInFirstWholeBand="false"
isPrintWhenDetailOverflows="false"/>
<box topBorder="None" topBorderColor="#000000" leftBorder="None"
leftBorderColor="#000000" rightBorder="None" rightBorderColor="#000000"
bottomBorder="None" bottomBorderColor="#000000"/>
<textElement textAlignment="Right" verticalAlignment="Top"
rotation="None" lineSpacing="Single">
<font reportFont="Arial_Bold"/>
</textElement>
<text><![CDATA[Series]]></text>
</staticText>
<staticText>
<reportElement
mode="Transparent"
x="220"
y="4"
width="40"
height="15"
forecolor="#000000"
backcolor="#FFFFFF"
key="staticText"
stretchType="NoStretch"
positionType="FixRelativeToTop"
isPrintRepeatedValues="true"
isRemoveLineWhenBlank="false"
isPrintInFirstWholeBand="false"
isPrintWhenDetailOverflows="false"/>
<box topBorder="None" topBorderColor="#000000" leftBorder="None"
leftBorderColor="#000000" rightBorder="None" rightBorderColor="#000000"
bottomBorder="None" bottomBorderColor="#000000"/>
<textElement textAlignment="Right" verticalAlignment="Top"
rotation="None" lineSpacing="Single">
<font reportFont="Arial_Bold"/>
</textElement>
<text><![CDATA[Average]]></text>
</staticText>
</band>
</pageHeader>
<columnHeader>
<band height="0" isSplitAllowed="true" >
</band>
</columnHeader>
<detail>
<band height="20" isSplitAllowed="true" >
<textField isStretchWithOverflow="false" pattern="" isBlankWhenNull="false"
evaluationTime="Now" hyperlinkType="None" hyperlinkTarget="Self" >
<reportElement
mode="Transparent"
x="0"
y="4"
width="50"
height="15"
forecolor="#000000"
backcolor="#FFFFFF"
key="textField"
stretchType="NoStretch"
positionType="FixRelativeToTop"
isPrintRepeatedValues="true"
isRemoveLineWhenBlank="false"
isPrintInFirstWholeBand="false"
isPrintWhenDetailOverflows="false"/>
<box topBorder="None" topBorderColor="#000000" leftBorder="None"
leftBorderColor="#000000" rightBorder="None" rightBorderColor="#000000"
bottomBorder="None" bottomBorderColor="#000000"/>
<textElement textAlignment="Left" verticalAlignment="Top" rotation="None"
lineSpacing="Single">
<font fontName="Arial" pdfFontName="Helvetica" size="8"
isBold="false" isItalic="false" isUnderline="false" isPdfEmbedded
="false" pdfEncoding ="Cp1252" isStrikeThrough="false" />
</textElement>
<textFieldExpression
class="java.lang.String"><![CDATA[$F{bowlerName}]]></textFieldExpression>
</textField>
<textField isStretchWithOverflow="false" pattern="" isBlankWhenNull="false"
evaluationTime="Now" hyperlinkType="None" hyperlinkTarget="Self" >
<reportElement
mode="Transparent"
x="60"
y="4"
width="30"
height="15"
forecolor="#000000"
backcolor="#FFFFFF"
key="textField"
stretchType="NoStretch"
positionType="FixRelativeToTop"
isPrintRepeatedValues="true"
isRemoveLineWhenBlank="false"
isPrintInFirstWholeBand="false"
isPrintWhenDetailOverflows="false"/>
<box topBorder="None" topBorderColor="#000000" leftBorder="None"
leftBorderColor="#000000" rightBorder="None" rightBorderColor="#000000"
bottomBorder="None" bottomBorderColor="#000000"/>
<textElement textAlignment="Right" verticalAlignment="Top"
rotation="None" lineSpacing="Single">
<font fontName="Arial" pdfFontName="Helvetica" size="8"
isBold="false" isItalic="false" isUnderline="false" isPdfEmbedded
="false" pdfEncoding ="Cp1252" isStrikeThrough="false" />
</textElement>
<textFieldExpression
class="java.lang.Integer"><![CDATA[$F{game1}]]></textFieldExpression>
</textField>
<textField isStretchWithOverflow="false" pattern="" isBlankWhenNull="false"
evaluationTime="Now" hyperlinkType="None" hyperlinkTarget="Self" >
<reportElement
mode="Transparent"
x="100"
y="4"
width="30"
height="15"
forecolor="#000000"
backcolor="#FFFFFF"
key="textField"
stretchType="NoStretch"
positionType="FixRelativeToTop"
isPrintRepeatedValues="true"
isRemoveLineWhenBlank="false"
isPrintInFirstWholeBand="false"
isPrintWhenDetailOverflows="false"/>
<box topBorder="None" topBorderColor="#000000" leftBorder="None"
leftBorderColor="#000000" rightBorder="None" rightBorderColor="#000000"
bottomBorder="None" bottomBorderColor="#000000"/>
<textElement textAlignment="Right" verticalAlignment="Top"
rotation="None" lineSpacing="Single">
<font fontName="Arial" pdfFontName="Helvetica" size="8"
isBold="false" isItalic="false" isUnderline="false" isPdfEmbedded
="false" pdfEncoding ="Cp1252" isStrikeThrough="false" />
</textElement>
<textFieldExpression
class="java.lang.Integer"><![CDATA[$F{game2}]]></textFieldExpression>
</textField>
<textField isStretchWithOverflow="false" pattern="" isBlankWhenNull="false"
evaluationTime="Now" hyperlinkType="None" hyperlinkTarget="Self" >
<reportElement
mode="Transparent"
x="140"
y="4"
width="30"
height="15"
forecolor="#000000"
backcolor="#FFFFFF"
key="textField"
stretchType="NoStretch"
positionType="FixRelativeToTop"
isPrintRepeatedValues="true"
isRemoveLineWhenBlank="false"
isPrintInFirstWholeBand="false"
isPrintWhenDetailOverflows="false"/>
<box topBorder="None" topBorderColor="#000000" leftBorder="None"
leftBorderColor="#000000" rightBorder="None" rightBorderColor="#000000"
bottomBorder="None" bottomBorderColor="#000000"/>
<textElement textAlignment="Right" verticalAlignment="Top"
rotation="None" lineSpacing="Single">
<font fontName="Arial" pdfFontName="Helvetica" size="8"
isBold="false" isItalic="false" isUnderline="false" isPdfEmbedded
="false" pdfEncoding ="Cp1252" isStrikeThrough="false" />
</textElement>
<textFieldExpression
class="java.lang.Integer"><![CDATA[$F{game3}]]></textFieldExpression>
</textField>
<textField isStretchWithOverflow="false" pattern="" isBlankWhenNull="false"
evaluationTime="Now" hyperlinkType="None" hyperlinkTarget="Self" >
<reportElement
mode="Transparent"
x="180"
y="4"
width="30"
height="15"
forecolor="#000000"
backcolor="#FFFFFF"
key="textField"
stretchType="NoStretch"
positionType="FixRelativeToTop"
isPrintRepeatedValues="true"
isRemoveLineWhenBlank="false"
isPrintInFirstWholeBand="false"
isPrintWhenDetailOverflows="false"/>
<box topBorder="None" topBorderColor="#000000" leftBorder="None"
leftBorderColor="#000000" rightBorder="None" rightBorderColor="#000000"
bottomBorder="None" bottomBorderColor="#000000"/>
<textElement textAlignment="Right" verticalAlignment="Top"
rotation="None" lineSpacing="Single">
<font fontName="Arial" pdfFontName="Helvetica" size="8"
isBold="false" isItalic="false" isUnderline="false" isPdfEmbedded
="false" pdfEncoding ="Cp1252" isStrikeThrough="false" />
</textElement>
<textFieldExpression
class="java.lang.Integer"><![CDATA[]]></textFieldExpression>
</textField>
<textField isStretchWithOverflow="false" pattern="" isBlankWhenNull="false"
evaluationTime="Now" hyperlinkType="None" hyperlinkTarget="Self" >
<reportElement
mode="Transparent"
x="220"
y="4"
width="40"
height="15"
forecolor="#000000"
backcolor="#FFFFFF"
key="textField"
stretchType="NoStretch"
positionType="FixRelativeToTop"
isPrintRepeatedValues="true"
isRemoveLineWhenBlank="false"
isPrintInFirstWholeBand="false"
isPrintWhenDetailOverflows="false"/>
<box topBorder="None" topBorderColor="#000000" leftBorder="None"
leftBorderColor="#000000" rightBorder="None" rightBorderColor="#000000"
bottomBorder="None" bottomBorderColor="#000000"/>
<textElement textAlignment="Right" verticalAlignment="Top"
rotation="None" lineSpacing="Single">
<font fontName="Arial" pdfFontName="Helvetica" size="8"
isBold="false" isItalic="false" isUnderline="false" isPdfEmbedded
="false" pdfEncoding ="Cp1252" isStrikeThrough="false" />
</textElement>
<textFieldExpression class="java.lang.Integer"><![CDATA[new
Integer(($F{game1}.intValue() + $F{game2}.intValue() +
$F{game3}.intValue())/$V{noOfGames}.intValue())]]></textFieldExpression>
</textField>
</band>
</detail>
<columnFooter>
<band height="0" isSplitAllowed="true" >
</band>
</columnFooter>
<pageFooter>
<band height="0" isSplitAllowed="true" >
</band>
</pageFooter>
<summary>
<band height="0" isSplitAllowed="true" >
</band>
</summary>
</jasperReport>
Listing 2
<!--
JasperReport Task Definition.
-->
<taskdef name="jasperReportCompile"
classname="net.sf.jasperreports.ant.JRAntCompileTask">
<classpath>
<fileset dir="${lib.dir}">
<include name="**/*.jar"/>
</fileset>
</classpath>
</taskdef>
<!--
Compiles the .jrxml reports in the report directory
to a .jasper report file in the same directory.
-->
<target name="compileReport">
<jasperReportCompile
srcdir="${report.dir}"
destdir="${report.dir}"
tempdir="${report.dir}"
keepjava="true"
xmlvalidation="true">
<src>
<fileset dir="${report.dir}">
<include name="**/*.jrxml"/>
</fileset>
</src>
<classpath refid="project.classpath"/>
</jasperReportCompile>
</target>
Listing 3
private Object[][] staticData = {
{"Pete", new Integer(200), new Integer(201), new Integer(202)},
{"Jason", new Integer(201), new Integer(200), new Integer(199)},
{"Craig", new Integer(193), new Integer(213), new Integer(190)},
{"Geoff", new Integer(190), new Integer(184), new Integer(240)},
{"Fred", new Integer(178), new Integer(204), new Integer(230)}
};
Listing 4
/**
* next() method.
*
* Increments the current array data index, and checks if the
* index exceeds the size of the data array.
*
* NB. On initial call index will be -1.
*
* @return - true if there is another entry in the data array
*/
public boolean next() throws JRException
{
// Increment the current index value
index++;
// Return true if the current index value
// is smaller than the array data length.
return (index < staticData.length);
}
Listing 5
/**
* getFieldValue() method
*
* This method is called for each field encountered in a
* report. It returns the value of the field requested for
* the current data index.
*
* @parameter field - the mapped field from the report.
* @return - the field value for the current data array index.
*/
public Object getFieldValue(JRField field) throws JRException
{
Object value = null;
String fieldName = field.getName();
if ("bowlerName".equals(fieldName))
{
value = staticData[index][0];
}
else if ("game1".equals(fieldName))
{
value = staticData[index][1];
}
else if ("game2".equals(fieldName))
{
value = staticData[index][2];
}
else if ("game3".equals(fieldName))
{
value = staticData[index][3];
}
return value;
}
Listing 6
/*
* JDBCDataSourceExample.java
*
* Peter Sellars - 20/11/05
*
*/
package example.datasource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
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.JREmptyDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRResultSetDataSource;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;
/**
* This class demonstrates how to implement a java.sql.Connection
* data source as the source for a JasperReports report.
*
* @author Peter Sellars
*/
public class JDBCDataSourceExample {
public static void main(String[] args) {
String jdbcSampleReportFile =
new String("reports/jdbcSampleReport.jrxml");
// Set up the database connectivity
// Change these settings according to your local configuration
String driver = "org.gjt.mm.mysql.Driver";
String connectString = "jdbc:mysql://localhost:3306/sample-data";
String user = "username";
String password = "password";
Connection conn = null;
// Set up database connection
try {
Class.forName(driver);
conn = DriverManager.getConnection(connectString, user, password);
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
} catch (SQLException sqle) {
sqle.printStackTrace();
}
// Fill the parameters
HashMap parameters = new HashMap();
parameters.put("ReportTitle", "Bowling Scores");
parameters.put("NoOfGames", new Integer(3));
try {
// Load the sample report file from the XML file
// into the JasperDesign object.
JasperDesign design =
JRXmlLoader.load(jdbcSampleReportFile);
// Compile the Report in Memory storing it in
// a JasperReport object no .jasper report
// file is created.
JasperReport report =
new JasperCompileManager().compileReport(design);
// Fill the report using the java.sql.Connection instance.
JasperPrint print =
JasperFillManager.fillReport(report, parameters, conn);
// Export to PDF file.
JasperExportManager.exportReportToPdfFile(print,"jdbcDataSourceReport.pdf");
} catch (JRException jre) {
jre.printStackTrace();
}
}
}
Listing 7
/*
* SimpleHibernateExample.java
*
* Peter Sellars - 20/11/05
*
*/
package example.hibernate;
import net.sf.hibernate.MappingException;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Session;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.cfg.Configuration;
import java.util.HashMap;
import java.util.List;
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.JRException;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;
/**
* This class demonstrates how to implement a java.sql.Connection
* data source as the source for a JasperReports report.
*
* @author Peter Sellars
*/
public class SimpleHibernateExample {
public static void main(String[] args) {
String sampleReportFile =
new String("reports/sampleReport.jrxml");
// Hibernate Result Set Holder.
List bowlerInfo = null;
try {
// Configure the Hibernate session.
Configuration cfg = new Configuration();
cfg.addResource("hibernate-mapping.xml");
SessionFactory sessions = cfg.buildSessionFactory();
// Open the Hibernate Session.
Session session = sessions.openSession();
// Returns all SampleData records. Simple POJO object.
bowlerInfo = session.createQuery("from SampleData").list();
// Fill the parameters
HashMap parameters = new HashMap();
parameters.put("ReportTitle", "Bowling Scores");
parameters.put("NoOfGames", new Integer(3));
// Load the sample report file from the XML file
// into the JasperDesign object.
JasperDesign design =
JRXmlLoader.load(sampleReportFile);
// Compile the Report in Memory storing it in
// a JasperReport object no .jasper report
// file is created.
JasperReport report =
new JasperCompileManager().compileReport(design);
// Fill the report using the JRBeanCollectionDataSource passed
// a Hibernate query result set.
JasperPrint print =
JasperFillManager.
fillReport(report, parameters, new JRBeanCollectionDataSource(bowlerInfo));
// Export to PDF file.
JasperExportManager.exportReportToPdfFile(print,"simpleHibernatExample.pdf");
// Close the Hibernate Session.
session.close();
} catch (JRException jre) {
jre.printStackTrace();
} catch (MappingException me) {
me.printStackTrace();
} catch (HibernateException he) {
he.printStackTrace();
}
}
}
Listing 8
/*
* HibernateDataSource.java
*
* Peter Sellars - 20/11/05
*
*/
package example.hibernate;
import java.util.Iterator;
import java.util.List;
import net.sf.jasperreports.engine.*;
/**
* This class demonstrates how to implement a JRDataSource
* using a Hibernate query result set containing a tuple of objects
* to a JasperReport detail section.
*
* @author Peter Sellars
*/
public class HibernateDataSource implements JRDataSource {
/* The Mapped Field Names */
private String[] fields;
/* The object iterator */
private Iterator iterator;
/* The current object value */
private Object currentValue;
/**
* Constructor that accpets the list of data objects
* and the names of the fields.
*
* @parameter list - the data objects contained in the result set.
* @parameter fields - an array of field names.
*/
public HibernateDataSource(List list, String[] fields) {
this.fields = fields;
this.iterator = list.iterator();
}
/**
* Gets the current field index based on the position in
* the mapped fields passed to the constructor. Then gets
* the current object value held at the field index.
*
* @return the value of a field
*/
public Object getFieldValue(JRField field) throws JRException {
Object value = null;
int index = getFieldIndex(field.getName());
if (index > -1) {
Object[] values = (Object[])currentValue;
value = values[index];
}
return value;
}
/**
* @return true if there is another object in the result set.
*/
public boolean next() throws JRException {
currentValue = iterator.hasNext() ? iterator.next() : null;
return (currentValue != null);
}
/**
* Uses the mapped field name to get the index of the field
* in the object passed to it.
*
* @return the index of a mapped field in the object information
*/
private int getFieldIndex(String field) {
int index = -1;
for (int i = 0; i < fields.length; i++) {
if (fields[i].equals(field)) {
index = i;
break;
}
}
return index;
}
}
Listing 9
package example.servlet;
import net.sf.hibernate.MappingException;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Session;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.cfg.Configuration;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.export.JRPrintServiceExporter;
public class PrintServlet extends HttpServlet {
String sampleReportFileName =
"/reports/sampleReport.jasper";
// Hibernate Result Set Holder.
List bowlerInfo = null;
public void service(
HttpServletRequest request,
HttpServletResponse response) {
// Get Servlet Context
ServletContext context = this.getServletConfig().getServletContext();
// Set the Jasper Design template file
File sampleReportFile = new File(context.getRealPath(sampleReportFileName));
// Fills the report with data.
try {
// Configure the Hibernate session.
Configuration cfg = new Configuration();
cfg.addResource("hibernate-mapping.xml");
SessionFactory sessions = cfg.buildSessionFactory();
// Open the Hibernate Session.
Session session = sessions.openSession();
// Returns all SampleData records. Simple POJO object.
bowlerInfo = session.createQuery("from SampleData").list();
// Add the report parameters required
Map params = new HashMap();
params.put("ReportTitle", "Bowling Scores");
params.put("NoOfGames", new Integer(3));
// Get the report file
InputStream reportStream = new FileInputStream(sampleReportFile.getPath());
// Set the response content type and set the output stream
response.setContentType("application/pdf");
ServletOutputStream outputStream = response.getOutputStream();
// Stream the PDF to the users Browser.
JasperRunManager.runReportToPdfStream(
reportStream, outputStream,
params, new JRBeanCollectionDataSource((bowlerInfo)));
outputStream.flush();
outputStream.close();
// Close the Hibernate session
session.close();
} catch (JRException jre) {
jre.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (MappingException me) {
me.printStackTrace();
} catch (HibernateException he) {
he.printStackTrace();
}
}
}
Listing 10
package example.servlet;
import net.sf.hibernate.MappingException;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Session;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.cfg.Configuration;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
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.JRRuntimeException;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
public class DataExtractServlet extends HttpServlet {
String sampleReportFileName =
"/reports/sampleReport.jasper";
// Hibernate Result Set Holder.
List bowlerInfo = null;
public void service(
HttpServletRequest request,
HttpServletResponse response) {
// Get Servlet Context
ServletContext context = this.getServletConfig().getServletContext();
// Set the Jasper Design template file
File sampleReportFile = new File(context.getRealPath(sampleReportFileName));
// Fills the report with data.
try {
// Configure the Hibernate session.
Configuration cfg = new Configuration();
cfg.addResource("hibernate-mapping.xml");
SessionFactory sessions = cfg.buildSessionFactory();
// Open the Hibernate Session.
Session session = sessions.openSession();
// Returns all SampleData records. Simple POJO object.
bowlerInfo = session.createQuery("from SampleData").list();
// Add the report parameters required
Map params = new HashMap();
params.put("ReportTitle", "Bowling Scores");
params.put("NoOfGames", new Integer(3));
// Get the report file
// InputStream reportStream = new FileInputStream(sampleReportFile.getPath());
JasperPrint jasperPrint =
JasperFillManager.fillReport(
sampleReportFile.getPath(),
params, new JRBeanCollectionDataSource((bowlerInfo)) );
// Export to Excel File
JRXlsExporter xlsExporter = new JRXlsExporter();
// Input and output parameters.
response.setHeader(
"Content-Disposition",
"attachment; filename=\"" + "sampleReport.xls" + "\"");
response.setContentType("application/vnd.ms-excel");
xlsExporter.setParameter(JRExporterParameter.OFFSET_X, new Integer(-30));
xlsExporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET,
Boolean.FALSE);
xlsExporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS,
Boolean.TRUE);
xlsExporter.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint);
xlsExporter.setParameter(JRXlsExporterParameter.OUTPUT_STREAM,
response.getOutputStream());
// Does the export.
xlsExporter.exportReport();
} catch (JRException jre) {
jre.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (MappingException me) {
me.printStackTrace();
} catch (HibernateException he) {
he.printStackTrace();
}
}
}