Jasper Reports - Multi axis chart - Only one plot showing - java

I'm trying to create a multi axis chart with one plot which shows a bar chart and another plot which shows a line chart. I found the multi axis chart to do this, but when I run my code only one plot is showing (image provided here). Any idea's on how to solve this?
In my search for a solution I came accross this post, but when I execute this it just does the same.
(When I switch the order of the barChart and lineChart in the jrxml it only shows the lineChart. Code provided below.)
Java bean
public class OperationSuccessrateBean {
private Integer week;
private Integer totalOrders;
private Double successrate;
public OperationSuccessrateBean(Integer week, Integer totalOrders, Double successrate) {
this.week = week;
this.totalOrders = totalOrders;
this.successrate = successrate;
}
public Integer getWeek() {
return week;
}
public Integer getTotalOrders() {
return totalOrders;
}
public Double getSuccessrate() {
return successrate;
}
}
Java: Filling the report
private void setOperationSuccessrate(String operationType, Map<String, Object> paramMap,
List<OperationSuccessrateBean> successrateBeans) {
paramMap.put(operationType + "_OPERATION_SUCCESSRATE_SET", new JRBeanCollectionDataSource(
successrateBeans));
paramMap.put(operationType + "_OPERATION_SUCCESSRATE_ORDERS_SET",
new JRBeanCollectionDataSource(successrateBeans));
}
jrxml: define datasets and parameters
<subDataset name="loadOperationSuccesrateSet" uuid="247b3e44-ef98-45f4-a909-e8b5678acc8f">
<field name="week" class="java.lang.Integer"/>
<field name="totalOrders" class="java.lang.Integer"/>
<field name="successrate" class="java.lang.Double"/>
</subDataset>
<subDataset name="loadOperationSuccesrateOrdersSet" uuid="247b3e44-ef98-45f4-a909-e8b5678acc8f">
<field name="week" class="java.lang.Integer"/>
<field name="totalOrders" class="java.lang.Integer"/>
<field name="successrate" class="java.lang.Double"/>
</subDataset>
<parameter name="LOAD_OPERATION_SUCCESSRATE_SET" class="net.sf.jasperreports.engine.data.JRBeanCollectionDataSource" isForPrompting="false"/>
<parameter name="LOAD_OPERATION_SUCCESSRATE_ORDERS_SET" class="net.sf.jasperreports.engine.data.JRBeanCollectionDataSource" isForPrompting="false"/>
jrxml: multi chart
<multiAxisChart>
<chart evaluationTime="Report">
<reportElement x="0" y="41" width="550" height="200" uuid="5078c050-dd35-43db-bf30-d04152672bd6"/>
<chartTitle/>
<chartSubtitle/>
<chartLegend/>
</chart>
<multiAxisPlot>
<plot/>
<axis position="rightOrBottom">
<lineChart>
<chart evaluationTime="Report">
<reportElement positionType="Float" x="0" y="25" width="270" height="175" backcolor="#FFFFFF" uuid="013d7a7d-2280-46d0-8d44-d537d062a182"/>
<chartTitle color="#000000"/>
<chartSubtitle color="#000000"/>
<chartLegend textColor="#000000" backgroundColor="#FFFFFF"/>
</chart>
<categoryDataset>
<dataset>
<datasetRun subDataset="loadOperationSuccesrateSet" uuid="53426928-1245-4443-97da-509b00ba1f98">
<dataSourceExpression><![CDATA[$P{LOAD_OPERATION_SUCCESSRATE_SET}]]></dataSourceExpression>
</datasetRun>
</dataset>
<categorySeries>
<seriesExpression><![CDATA["Success rate"]]></seriesExpression>
<categoryExpression><![CDATA[$F{week}]]></categoryExpression>
<valueExpression><![CDATA[$F{successrate}]]></valueExpression>
</categorySeries>
</categoryDataset>
<linePlot>
<plot/>
<categoryAxisFormat>
<axisFormat/>
</categoryAxisFormat>
<valueAxisLabelExpression><![CDATA["Success rate"]]></valueAxisLabelExpression>
<valueAxisFormat>
<axisFormat labelColor="#000000" tickLabelColor="#000000" tickLabelMask="#0%" axisLineColor="#000000">
<labelFont/>
</axisFormat>
</valueAxisFormat>
<rangeAxisMinValueExpression><![CDATA[0]]></rangeAxisMinValueExpression>
<rangeAxisMaxValueExpression><![CDATA[1]]></rangeAxisMaxValueExpression>
</linePlot>
</lineChart>
</axis>
<axis>
<barChart>
<chart evaluationTime="Report">
<reportElement x="0" y="0" width="0" height="0" backcolor="#FFFFFF" uuid="15a15c89-a2d4-4971-b4b3-1c5ac224a91e"/>
<chartTitle color="#000000"/>
<chartSubtitle color="#000000"/>
<chartLegend textColor="#000000" backgroundColor="#FFFFFF"/>
</chart>
<categoryDataset>
<dataset>
<datasetRun subDataset="loadOperationSuccesrateOrdersSet" uuid="4d001c74-1fde-47cd-b525-85d828d6ccf2">
<dataSourceExpression><![CDATA[$P{LOAD_OPERATION_SUCCESSRATE_ORDERS_SET}]]></dataSourceExpression>
</datasetRun>
</dataset>
<categorySeries>
<seriesExpression><![CDATA["TotalOrders"]]></seriesExpression>
<categoryExpression><![CDATA[$F{week}]]></categoryExpression>
<valueExpression><![CDATA[$F{totalOrders}]]></valueExpression>
</categorySeries>
</categoryDataset>
<barPlot>
<plot/>
<itemLabel/>
<categoryAxisFormat>
<axisFormat/>
</categoryAxisFormat>
<valueAxisLabelExpression><![CDATA["# Orders"]]></valueAxisLabelExpression>
<valueAxisFormat>
<axisFormat labelColor="#000000" tickLabelColor="#000000" tickLabelMask="# ##0" axisLineColor="#000000">
<labelFont/>
</axisFormat>
</valueAxisFormat>
<rangeAxisMinValueExpression><![CDATA[0]]></rangeAxisMinValueExpression>
</barPlot>
</barChart>
</axis>
</multiAxisPlot>
</multiAxisChart>
When I run my code without the multi axis chart so just to create the 2 plots next to each other it creates just fine. So I assume the data is correctely passed to the report.
The relevant libraries I use are:
net.sf.jasperreports.engine-6.4.0.jar
jfreechart-1.0.19.jar

Lorenz, I had the same issue.
The reason for the missing graph was that I was passing directly a net.sf.jasperreports.engine.data.JRBeanCollectionDataSource as parameter in the report.
Apparently for this to work you have to pass a List:
<parameter name="FIRST_DATA_SOURCE" class="java.util.List" isForPrompting="false"/>
<parameter name="SECOND_DATA_SOURCE" class="java.util.List" isForPrompting="false"/>
and then create the JRBeanCollectionDataSource inside the report:
<dataset>
<datasetRun subDataset="YOUR_SUBDATASET" uuid="a5941ba5-2088-4a31-8236-64704b54d979">
<dataSourceExpression><![CDATA[new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($P{FIRST_DATA_SOURCE})]]></dataSourceExpression>
</datasetRun>
</dataset>
In the post you referenced it was used this way and it worked!

Related

How to create nested table like jasper report?

I have been trying to create a jasper report which should look like the following image:
For my sample report, Out-1 and Out-2 are rows for the outer table and asd, asds, adasd are rows for the inner table.
I am trying to achieve it using nested tables. But the table takes the field and I can not assign field to the inner-table.
I am creating jasper reports in Java code rather than using SQL connection to the table for some reason.
JXML
<?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="report1" language="groovy" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="ec55a262-fec4-45f4-9b48-5be98088aafa">
<property name="ireport.zoom" value="1.0"/>
<property name="ireport.x" value="0"/>
<property name="ireport.y" value="0"/>
<subDataset name="New Dataset 1" uuid="cdef25ec-abc4-45ba-b70e-28d82716626b">
<field name="sachNr" class="java.lang.String"/>
<field name="akundenNr" class="java.lang.String"/>
<field name="nestedTable" class="java.lang.String"/>
</subDataset>
<subDataset name="New Dataset 2" uuid="eec983aa-a227-4a28-9c44-73cbe31fa024">
<field name="packStNr" class="java.lang.String"/>
<field name="prodDatum" class="java.lang.String"/>
<field name="stueck" class="java.lang.String"/>
</subDataset>
<parameter name=" artikeldatenTable" class="java.lang.String"/>
<background>
<band splitType="Stretch"/>
</background>
<title>
<band height="79" splitType="Stretch"/>
</title>
<pageHeader>
<band height="35" splitType="Stretch"/>
</pageHeader>
<columnHeader>
<band height="61" splitType="Stretch"/>
</columnHeader>
<detail>
<band height="125" splitType="Stretch">
<componentElement>
<reportElement key="table" x="0" y="28" width="360" height="50" uuid="fae14075-18a8-4fcc-b6f9-c14e3623e75d"/>
<jr:table xmlns:jr="http://jasperreports.sourceforge.net/jasperreports/components" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/components http://jasperreports.sourceforge.net/xsd/components.xsd">
<datasetRun subDataset="New Dataset 1" uuid="17a10558-3a43-47c2-809d-6362924e5015">
<dataSourceExpression><![CDATA[new net.sf.jasperreports.engine.JREmptyDataSource(1)]]></dataSourceExpression>
</datasetRun>
<jr:column width="137" uuid="7a8ca2ff-7a1a-41a0-8c30-b02f7be6e2b9">
<jr:tableHeader height="30" rowSpan="1">
<textField>
<reportElement x="0" y="0" width="137" height="30" uuid="0fe0e502-dea8-45f6-9f96-633f5db90cd8"/>
<textFieldExpression><![CDATA[$F{sachNr}]]></textFieldExpression>
</textField>
</jr:tableHeader>
<jr:detailCell height="42" rowSpan="1">
<componentElement>
<reportElement key="table" x="0" y="0" width="137" height="42" uuid="9e72ca8c-182d-41c0-a021-98493162c7da"/>
<jr:table>
<datasetRun subDataset="New Dataset 2" uuid="7475e256-4bc5-4e88-be92-b6d2eb2fd4c5">
<dataSourceExpression><![CDATA[new net.sf.jasperreports.engine.JREmptyDataSource()]]></dataSourceExpression>
</datasetRun>
<jr:column width="90" uuid="cd851138-c894-459f-91c9-636c3602b247">
<jr:detailCell height="20" rowSpan="1">
<textField>
<reportElement x="0" y="0" width="90" height="20" uuid="ce21338e-c593-4bae-b7c4-08741127575c"/>
<textFieldExpression><![CDATA[$F{packStNr}]]></textFieldExpression>
</textField>
</jr:detailCell>
</jr:column>
<jr:column width="90" uuid="5f2b25a9-e34a-4698-b1ab-e8843dafec3c">
<jr:detailCell height="20" rowSpan="1">
<textField>
<reportElement x="0" y="0" width="90" height="20" uuid="5487305d-d22f-46fa-97bc-88e671f7085c"/>
<textFieldExpression><![CDATA[$F{prodDatum}]]></textFieldExpression>
</textField>
</jr:detailCell>
</jr:column>
<jr:column width="90" uuid="93c28f55-9bda-4be0-989a-03ce573715ba">
<jr:detailCell height="20" rowSpan="1">
<textField>
<reportElement x="0" y="0" width="90" height="20" uuid="53c4e2b3-7591-49b3-9b13-50cc1f16641a"/>
<textFieldExpression><![CDATA[$F{stueck}]]></textFieldExpression>
</textField>
</jr:detailCell>
</jr:column>
</jr:table>
</componentElement>
</jr:detailCell>
</jr:column>
<jr:column width="90" uuid="f898d2e7-1c2f-48fe-9357-61ee5d767a51">
<jr:tableHeader height="30" rowSpan="1">
<textField>
<reportElement x="0" y="0" width="90" height="30" uuid="16b70095-2900-46f0-96ec-d638edb784f3"/>
<textFieldExpression><![CDATA[$F{akundenNr}]]></textFieldExpression>
</textField>
</jr:tableHeader>
<jr:detailCell height="42" rowSpan="1"/>
</jr:column>
<jr:column width="111" uuid="0121d9c8-d1f0-447f-84ed-15385693a072">
<jr:tableHeader height="30" rowSpan="1"/>
<jr:detailCell height="42" rowSpan="1"/>
</jr:column>
<jr:column width="90" uuid="ca27e48c-a1d6-4c32-a1de-2580b6786b3d">
<jr:tableHeader height="30" rowSpan="1"/>
<jr:detailCell height="42" rowSpan="1"/>
</jr:column>
</jr:table>
</componentElement>
</band>
</detail>
<columnFooter>
<band height="45" splitType="Stretch"/>
</columnFooter>
<pageFooter>
<band height="54" splitType="Stretch"/>
</pageFooter>
<summary>
<band height="42" splitType="Stretch"/>
</summary>
</jasperReport>
Outer Table POJO
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
public class OuterTable {
private String sachNr;
private String akundenNr;
private String SUBREPORT_DIR;
private JRBeanCollectionDataSource nestedTable;
public String getSachNr() {
return sachNr;
}
public void setSachNr(String sachNr) {
this.sachNr = sachNr;
}
public String getAkundenNr() {
return akundenNr;
}
public void setAkundenNr(String akundenNr) {
this.akundenNr = akundenNr;
}
public String getSUBREPORT_DIR() {
return SUBREPORT_DIR;
}
public void setSUBREPORT_DIR(String sUBREPORT_DIR) {
SUBREPORT_DIR = sUBREPORT_DIR;
}
public JRBeanCollectionDataSource getNestedTable() {
return nestedTable;
}
public void setNestedTable(JRBeanCollectionDataSource nestedTable) {
this.nestedTable = nestedTable;
}
}
Inner Table POJO
public class InnerTable {
private String packStNr;
private String prodDatum;
private Integer stueck;
public String getPackStNr() {
return packStNr;
}
public void setPackStNr(String packStNr) {
this.packStNr = packStNr;
}
public String getProdDatum() {
return prodDatum;
}
public void setProdDatum(String prodDatum) {
this.prodDatum = prodDatum;
}
public Integer getStueck() {
return stueck;
}
public void setStueck(Integer stueck) {
this.stueck = stueck;
}
}
My Controller
private void generateLagerbestand(List<Artikeldaten> artikelList) throws JRException, FileNotFoundException {
JasperReport jasperReport;
Map<String, Object> parameters = new HashMap<String, Object>();
List <OuterTable> outerTableList = new ArrayList<OuterTable>();
for(int i = 0; i < artikelList.size(); i++) {
List <InnerTable> innerTableList = new ArrayList<InnerTable>();
List<Lager> lagersList = artikelList.get(i).getLagers();
for(int j = 0; j < lagersList.size(); j++) {
InnerTable innerTable = new InnerTable();
innerTable.setPackStNr(lagersList.get(j).getPackstnr());
innerTable.setProdDatum(lagersList.get(j).getProddatum().toString());
innerTable.setStueck(lagersList.get(j).getStueck());
innerTableList.add(innerTable);
}
OuterTable outerTable = new OuterTable();
outerTable.setAkundenNr(artikelList.get(i).getAkundennr());
outerTable.setSachNr(artikelList.get(i).getSachnr());
JRBeanCollectionDataSource nestedTable = new JRBeanCollectionDataSource(innerTableList);
outerTable.setNestedTable(nestedTable);
outerTableList.add(OuterTable);
}
try {
jasperReport = JasperCompileManager.compileReport("PathToMyReport\\MyReport.jrxml");
JRBeanCollectionDataSource outerTableItems = new JRBeanCollectionDataSource(outerTableList);
// artikeldatenTable is outerTable
parameters.put("artikeldatenTable", outerTableItems);
JREmptyDataSource jrEmptyDataSource = new JREmptyDataSource();
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, jrEmptyDataSource);
OutputStream outputStream = new FileOutputStream(new File("PathToMyPDF:\\MyPDF.pdf"));
JasperExportManager.exportReportToPdfStream(jasperPrint, outputStream);
} catch(Exception ex) {
ex.printStackTrace();
}
}
You are missing the concept of the detail band, the detail will iterate on the datasource you pass to report
JasperFillManager.fillReport(jasperReport, parameters, jrEmptyDataSource)
That's an empty datasource!, it will not iterate at all.
Instead, pass
JRBeanCollectionDataSource outerTableItems = new JRBeanCollectionDataSource(outerTableList);
To the report, define the fields of OuterTable in your main report (not a subDatasource) including nestedTable
<field name="nestedTable" class="net.sf.jasperreports.engine.data.JRBeanCollectionDataSource"/>
Then
In detail band you put textFields related to first level "Out-1" and "Out-2" in your example.
Bellow you add the jr:table component taking the datasource from the bean
<datasetRun subDataset="New Dataset 1" uuid="17a10558-3a43-47c2-809d-6362924e5015">
<dataSourceExpression><![CDATA[$F{nestedTable}]]></dataSourceExpression>
</datasetRun>
In general within the bean I would not have JRBeanCollectionDatasource but instead store the data in a normal List<>, the reason is that a JRDatasource is consumable you can only use it once, see this to understand better How to use same JRBeanCollectionDataSource on multiple sub reports?

Working with multiple data sources in jaspersoft studio

After being able to add custom data source from java bean to a report according to Add custom data source to Jaspersoft Studio , I get to the second point of my reporting with jasper.
I have a main report which uses a data base as its data source. Then I add a bean.xml data source to the report and add a table to the main report which uses this bean.xml data source to get java beans.
My goal is to get a field value from the main report and manipulate
its value, then fill the beans with these values and at last fill the
table with the beans.
To do this I have written 3 classes which I use as Scriptlet in the table data set:
This is an illustration of what I need to do:
The problem is in FillTable class, when I us String kNFormelGG = (String) this.getParameterValue("gg"); the created bean.xml fails the test connection with java.lang.reflect.InvocationTargetException
Caused by: java.lang.NullPointerException
at net.sf.jasperreports.engine.JRAbstractScriptlet.getParameterValue(JRAbstractScriptlet.java:95)
at net.sf.jasperreports.engine.JRAbstractScriptlet.getParameterValue(JRAbstractScriptlet.java:86)
at org.iqtig.reporting.dataSource.bean.dataSourceXML.FillTable.fillTable(FillTable.java:45)
at org.iqtig.reporting.dataSource.bean.dataSourceXML.JRDataSourceFactory.createCollection(JRDataSourceFactory.java:27)
... 34 more
If I assign a fix value like String kNFormelGG ="Test me" the bean connection encounters no error and after assigning bean.xml as the value for Default Data Adapter in Dataset1 it fills the table with static values.
How can get the data from a parameter or a value dynamically from the main report data source and use it in beans?
I have this assumption that at the time of calling the static factory class from my adapter, the fields are still empty. Maybe I am wrong but I do not find any other declaration for this problem.
BeanFactory Class
import java.util.Collection;
import net.sf.jasperreports.engine.JRDefaultScriptlet;
import net.sf.jasperreports.engine.JRScriptletException;
/**
* Factory for TableCellsBean Klasse
*
* #author iman.gharib
*/
public class JRDataSourceFactory extends JRDefaultScriptlet {
/**
* #return collection der TableCellsBean Objekten
* #throws JRScriptletException
*/
public static Collection<TableCellsBean> createCollection()
throws JRScriptletException {
FillTable ft = new FillTable();
Collection<TableCellsBean> reportRows = ft.fillTable();
return reportRows;
}
}
Bean Class
public class TableCellsBean {
private String fieldName;
private String keyFormel;
private String mK;
private String notation;
private String item;
/**
* Constructor.
*
* #param fieldName
* #param keyFormel
* #param mK
* #param notation
* #param item
*/
public TableCellsBean(final String fieldName, final String keyFormel, final String mK, final String notation, final String item) {
this.fieldName = fieldName;
this.keyFormel = keyFormel;
this.mK = mK;
this.notation = notation;
this.item = item;
}
/**
* Constructo Leer
*/
public TableCellsBean() {
}
public TableCellsBean getme() {
return this;
}
// getter and setters
}
Class for preparing and creating beans
public class FillTable extends JRDefaultScriptlet {
#Override
public void afterColumnInit()
throws JRScriptletException {
fillTable();
}
public ArrayList<String> splitGGArray(final String kNFormelGG) {
ArrayList<String> fieldNames = new ArrayList<>();
String[] array = (kNFormelGG.split(" "));
for (String sub : array) {
fieldNames.add(sub);
}
return fieldNames;
}
public Collection<TableCellsBean> fillTable()
throws JRScriptletException {
// gg is a parameter for table dataset. It is mapped to KN_FormelGG
// which comes from the main report data base
String kNFormelGG = (String) this.getParameterValue("gg");
List<TableCellsBean> listTableCells = new ArrayList<>();
// TableCellsBean tableCell = new TableCellsBean();
for (String fn : splitGGArray(kNFormelGG)) {
listTableCells.add(new TableCellsBean(fn, fn, fn, fn, fn));
// listTableCells.add(tableCell);
}
// JRBeanCollectionDataSource tableCellJRBean = new JRBeanCollectionDataSource(listTableCells);
// Map<String, Object> parameters = new HashMap<>();
// parameters.put("FieldDataSource", tableCellJRBean);
return listTableCells;
}
}
JRXML
<?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 6.3.0.final using JasperReports Library version 6.3.0 -->
<!-- 2016-08-08T14:30:03 -->
<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="main" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="4f1480cf-f8f9-420f-96b4-7fc1e41e791b">
<property name="com.jaspersoft.studio.data.sql.tables" value=""/>
<property name="com.jaspersoft.studio.data.defaultdataadapter" value="QIDBReport"/>
<style name="Table_TH" mode="Opaque" backcolor="#F0F8FF">
<box>
<pen lineWidth="0.5" lineColor="#000000"/>
<topPen lineWidth="0.5" lineColor="#000000"/>
<leftPen lineWidth="0.5" lineColor="#000000"/>
<bottomPen lineWidth="0.5" lineColor="#000000"/>
<rightPen lineWidth="0.5" lineColor="#000000"/>
</box>
</style>
<style name="Table_CH" mode="Opaque" backcolor="#BFE1FF">
<box>
<pen lineWidth="0.5" lineColor="#000000"/>
<topPen lineWidth="0.5" lineColor="#000000"/>
<leftPen lineWidth="0.5" lineColor="#000000"/>
<bottomPen lineWidth="0.5" lineColor="#000000"/>
<rightPen lineWidth="0.5" lineColor="#000000"/>
</box>
</style>
<style name="Table_TD" mode="Opaque" backcolor="#FFFFFF">
<box>
<pen lineWidth="0.5" lineColor="#000000"/>
<topPen lineWidth="0.5" lineColor="#000000"/>
<leftPen lineWidth="0.5" lineColor="#000000"/>
<bottomPen lineWidth="0.5" lineColor="#000000"/>
<rightPen lineWidth="0.5" lineColor="#000000"/>
</box>
</style>
<subDataset name="Dataset1" uuid="5677929d-813b-4d39-828c-de966a9d7689">
<property name="com.jaspersoft.studio.data.defaultdataadapter" value="bean.xml"/>
<property name="net.sf.jasperreports.data.adapter" value="bean.xml"/>
<scriptlet name="Scriptlet_1" class="org.iqtig.reporting.dataSource.bean.mapBeanAsDatasource.JRDataSourceFactory"/>
<parameter name="gg" class="java.lang.String"/>
<field name="item" class="java.lang.String">
<fieldDescription><![CDATA[item]]></fieldDescription>
</field>
<field name="fieldName" class="java.lang.String">
<fieldDescription><![CDATA[fieldName]]></fieldDescription>
</field>
<field name="me" class="org.iqtig.reporting.dataSource.bean.dataSourceXML.TableCellsBean">
<fieldDescription><![CDATA[me]]></fieldDescription>
</field>
<field name="keyFormel" class="java.lang.String">
<fieldDescription><![CDATA[keyFormel]]></fieldDescription>
</field>
<field name="mK" class="java.lang.String">
<fieldDescription><![CDATA[mK]]></fieldDescription>
</field>
</subDataset>
<parameter name="LB_ID" class="java.lang.Integer">
<defaultValueExpression><![CDATA[62]]></defaultValueExpression>
</parameter>
<parameter name="KN_OffeziellGruppe" class="java.lang.Integer">
<defaultValueExpression><![CDATA[3]]></defaultValueExpression>
</parameter>
<parameter name="FieldDataSource" class="net.sf.jasperreports.engine.data.JRBeanCollectionDataSource" isForPrompting="false"/>
<parameter name="KN_FormelGG" class="java.lang.String" isForPrompting="false"/>
<queryString>
<![CDATA[select * from "KennzahlReferenz2015_QIBericht", "Images"
where LB_ID = $P{LB_ID}
and KN_OffiziellGruppe = $P{KN_OffeziellGruppe}
and IMG_ID = 1]]>
</queryString>
<field name="QI_Praefix" class="java.lang.String"/>
<field name="KN_Id" class="java.lang.Integer"/>
<field name="bewertungsArtTypNameKurz" class="java.lang.String"/>
<field name="refbereich" class="java.lang.String"/>
<field name="refbereichVorjahres" class="java.lang.String"/>
<field name="KN_GGAlleinstehend" class="java.lang.String"/>
<field name="erlaueterungDerRechregeln" class="java.lang.String"/>
<field name="teildatensatzbezug" class="java.lang.String"/>
<field name="mindesanzahlZaeler" class="java.lang.Integer"/>
<field name="mindesanzahlNenner" class="java.lang.Integer"/>
<field name="KN_FormelZ" class="java.lang.String"/>
<field name="KN_FormelGG" class="java.lang.String"/>
<field name="verwendeteFunktionen" class="java.lang.String"/>
<field name="idLb" class="java.lang.String"/>
<field name="LB_LangBezeichnung" class="java.lang.String"/>
<field name="LB_ID" class="java.lang.Integer"/>
<field name="nameAlleinstehend" class="java.lang.String"/>
<field name="KN_BezeichnungAlleinstehendKurz" class="java.lang.String"/>
<field name="QI_ID" class="java.lang.Integer"/>
<field name="IMG_ID" class="java.lang.Integer"/>
<field name="Name" class="java.lang.String"/>
<field name="Image" class="java.lang.Object"/>
<group name="id" isStartNewPage="true">
<groupExpression><![CDATA[$F{KN_Id}]]></groupExpression>
<groupHeader>
<band height="44"/>
</groupHeader>
<groupFooter>
<band height="50"/>
</groupFooter>
</group>
<background>
<band splitType="Stretch"/>
</background>
<title>
<band height="44" splitType="Stretch"/>
</title>
<pageHeader>
<band height="35" splitType="Stretch"/>
</pageHeader>
<columnHeader>
<band height="34" splitType="Stretch"/>
</columnHeader>
<detail>
<band height="149" splitType="Stretch">
<componentElement>
<reportElement x="170" y="20" width="350" height="100" uuid="38d917fb-dfc2-4c08-890a-09cfe6e2214d">
<property name="com.jaspersoft.studio.layout" value="com.jaspersoft.studio.editor.layout.VerticalRowLayout"/>
<property name="com.jaspersoft.studio.table.style.table_header" value="Table_TH"/>
<property name="com.jaspersoft.studio.table.style.column_header" value="Table_CH"/>
<property name="com.jaspersoft.studio.table.style.detail" value="Table_TD"/>
<property name="net.sf.jasperreports.export.headertoolbar.table.name" value=""/>
<property name="com.jaspersoft.studio.components.autoresize.proportional" value="true"/>
</reportElement>
<jr:table xmlns:jr="http://jasperreports.sourceforge.net/jasperreports/components" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/components http://jasperreports.sourceforge.net/xsd/components.xsd" whenNoDataType="AllSectionsNoDetail">
<datasetRun subDataset="Dataset1" uuid="1b3548f6-7d6b-4070-bb8e-aaefbabdc7c9">
<datasetParameter name="gg">
<datasetParameterExpression><![CDATA[$F{KN_FormelGG}]]></datasetParameterExpression>
</datasetParameter>
</datasetRun>
<jr:column width="70" uuid="048812d7-0ed1-4db8-a09a-e6242f77c6ce">
<property name="com.jaspersoft.studio.components.table.model.column.name" value="Column1"/>
<jr:tableHeader style="Table_TH" height="30" rowSpan="1"/>
<jr:detailCell style="Table_TD" height="30">
<textField>
<reportElement x="0" y="0" width="70" height="30" uuid="c5aaea84-1367-41df-be8d-7f71e3ea5153"/>
<textFieldExpression><![CDATA[$F{item}]]></textFieldExpression>
</textField>
</jr:detailCell>
</jr:column>
<jr:column width="70" uuid="11b85ada-c9fe-42b6-a646-8bd1697cdec2">
<property name="com.jaspersoft.studio.components.table.model.column.name" value="Column2"/>
<jr:tableHeader style="Table_TH" height="30" rowSpan="1"/>
<jr:detailCell style="Table_TD" height="30">
<textField>
<reportElement x="0" y="0" width="70" height="30" uuid="728ff44d-1dbd-404c-b8b3-7cc0e1f07f60"/>
<textFieldExpression><![CDATA[$F{fieldName}]]></textFieldExpression>
</textField>
</jr:detailCell>
</jr:column>
<jr:column width="70" uuid="892f30cb-fb41-444f-889b-1e005484c35e">
<property name="com.jaspersoft.studio.components.table.model.column.name" value="Column3"/>
<jr:tableHeader style="Table_TH" height="30" rowSpan="1"/>
<jr:detailCell style="Table_TD" height="30">
<textField>
<reportElement x="0" y="0" width="70" height="30" uuid="e38ac951-71bc-45a6-8ed2-313805a77050"/>
<textFieldExpression><![CDATA[$F{keyFormel}]]></textFieldExpression>
</textField>
</jr:detailCell>
</jr:column>
<jr:column width="70" uuid="7d0d700a-5a75-4c26-94c0-9ef7c53bd719">
<property name="com.jaspersoft.studio.components.table.model.column.name" value="Column4"/>
<jr:tableHeader style="Table_TH" height="30" rowSpan="1">
<textField>
<reportElement x="0" y="0" width="70" height="30" uuid="68577007-0344-406c-8aa2-3127d1da1c65"/>
</textField>
</jr:tableHeader>
<jr:detailCell style="Table_TD" height="30">
<textField>
<reportElement x="0" y="0" width="70" height="30" uuid="873d63c1-1b91-4441-b7bd-f67db7729e7f"/>
<textFieldExpression><![CDATA[$F{mK}]]></textFieldExpression>
</textField>
</jr:detailCell>
</jr:column>
<jr:column width="70" uuid="cf5a1a2f-594d-429f-8925-62d001e1dd00">
<property name="com.jaspersoft.studio.components.table.model.column.name" value="Column5"/>
<jr:tableHeader style="Table_TH" height="30" rowSpan="1">
<textField>
<reportElement x="0" y="0" width="70" height="30" uuid="7fb46eb8-d0e1-44ab-89f9-ec31d49b8109"/>
<textFieldExpression><![CDATA[$P{gg}]]></textFieldExpression>
</textField>
</jr:tableHeader>
<jr:detailCell style="Table_TD" height="30"/>
</jr:column>
</jr:table>
</componentElement>
<textField>
<reportElement x="20" y="80" width="100" height="30" uuid="b89cd04c-2569-43ef-9730-445b874855dd"/>
<textFieldExpression><![CDATA[$F{KN_FormelGG}]]></textFieldExpression>
</textField>
<staticText>
<reportElement x="20" y="32" width="100" height="30" uuid="e91b4461-5e53-4f85-8992-14e69a1aa05f"/>
<text><![CDATA[KN_FormelGG]]></text>
</staticText>
</band>
</detail>
<columnFooter>
<band height="45" splitType="Stretch"/>
</columnFooter>
<pageFooter>
<band height="54" splitType="Stretch"/>
</pageFooter>
<summary>
<band height="42" splitType="Stretch"/>
</summary>
</jasperReport>
My goal is to get a field value from the main report and manipulate
its value, then fill the beans with these values and at last fill the
table with the beans.
I will ignore all your scriplets and other code and show you the simplest way to create a dynamic datasource for another component using a current field, variable or parameter value.
As example we will have these String values in field1 (row1, row2)
Test1_1.23:Test2_4.32:Test3_1.08
Test1_2.12:Test2_5.12:Test3_2.13
We want to split on : and create rows (List of beans), then split on _ to create columns (properties on bean) and display this in a jr:table component.
java code (or Bean)
public class TableCellsBean {
private String name;
private double value;
public TableCellsBean(String name,double value){
this.name = name;
this.value = value;
}
public static JRBeanCollectionDataSource getDatasource(String fieldValue){
List<TableCellsBean> retList = new ArrayList<>();
String[] values = fieldValue.split(":");
for (String v : values) {
String[] sp = v.split("_");
retList.add(new TableCellsBean(sp[0], Double.parseDouble(sp[1])));
}
return new JRBeanCollectionDataSource(retList);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getValue() {
return value;
}
public void setValue(double value) {
this.value = value;
}
}
As you can see already inside this bean class I have added a static method that returns a JRBeanCollectionDataSource depending on value passed as parameter.
Basically you pass a fieldValue to this method, it does some logic, creates the TableCellBean, adds them to list and return a JRBeanCollectionDataSource
Note: The method does not need to be static nor inside this class, furthermore exception handling is not considered.
Report - the jrxml
In example we will have field1 containing Test1_1.23:Test2_4.32:Test3_1.08 on row 1 and Test1_2.12:Test2_5.12:Test3_2.13 on row 2.
We define a subdataset that represents out TableCellsBean
<subDataset name="table_dataset" uuid="4dc1b0fb-2588-4f98-8c8d-f0afefbb2fd1">
<field name="name" class="java.lang.String"/>
<field name="value" class="java.lang.Double"/>
</subDataset>
as datasource we call our static method passing the field1 content in current row.
<dataSourceExpression><![CDATA[my.package.TableCellsBean.getDatasource($F{field1})]]></dataSourceExpression>
Full jrxml
<?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="test" language="java" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="886a547e-11bd-434b-a330-d93ee5e4a280">
<style name="table">
<box>
<pen lineWidth="1.0" lineColor="#000000"/>
</box>
</style>
<style name="table_TH" mode="Opaque" backcolor="#F0F8FF">
<box>
<pen lineWidth="0.5" lineColor="#000000"/>
</box>
</style>
<style name="table_CH" mode="Opaque" backcolor="#BFE1FF">
<box>
<pen lineWidth="0.5" lineColor="#000000"/>
</box>
</style>
<style name="table_TD" mode="Opaque" backcolor="#FFFFFF">
<box>
<pen lineWidth="0.5" lineColor="#000000"/>
</box>
</style>
<subDataset name="table_dataset" uuid="4dc1b0fb-2588-4f98-8c8d-f0afefbb2fd1">
<field name="name" class="java.lang.String"/>
<field name="value" class="java.lang.Double"/>
</subDataset>
<field name="field1" class="java.lang.String">
<fieldDescription><![CDATA[_THIS]]></fieldDescription>
</field>
<detail>
<band height="40" splitType="Stretch">
<textField>
<reportElement x="0" y="0" width="555" height="20" uuid="a73343b1-ccb2-4a59-b882-381b98efd664"/>
<textElement verticalAlignment="Middle"/>
<textFieldExpression><![CDATA[$F{field1}]]></textFieldExpression>
</textField>
<componentElement>
<reportElement key="table" style="table" x="0" y="20" width="555" height="20" uuid="09a9a5b8-499b-40d2-b391-ece25772a31e"/>
<jr:table xmlns:jr="http://jasperreports.sourceforge.net/jasperreports/components" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/components http://jasperreports.sourceforge.net/xsd/components.xsd">
<datasetRun subDataset="table_dataset" uuid="05601bdb-5579-4253-90f7-6742739d9714">
<dataSourceExpression><![CDATA[bounty.TableCellsBean.getDatasource($F{field1})]]></dataSourceExpression>
</datasetRun>
<jr:column width="90" uuid="afbbb3d0-573a-495d-ab51-0ae4d601e6fb">
<jr:tableHeader style="table_TH" height="20" rowSpan="1">
<staticText>
<reportElement x="0" y="0" width="90" height="20" uuid="e476f026-bbec-4b19-9bd4-f4b21f3377ef"/>
<textElement textAlignment="Center" verticalAlignment="Middle"/>
<text><![CDATA[Name]]></text>
</staticText>
</jr:tableHeader>
<jr:detailCell style="table_TD" height="20" rowSpan="1">
<textField>
<reportElement x="0" y="0" width="90" height="20" uuid="49cac181-b16b-4ab3-b600-78a56fb0f42b"/>
<box leftPadding="3" rightPadding="3"/>
<textElement verticalAlignment="Middle"/>
<textFieldExpression><![CDATA[$F{name}]]></textFieldExpression>
</textField>
</jr:detailCell>
</jr:column>
<jr:column width="90" uuid="4a1b0759-c347-4294-82c5-3aed4762f0c4">
<jr:tableHeader style="table_TH" height="20" rowSpan="1">
<staticText>
<reportElement x="0" y="0" width="90" height="20" uuid="bfa965b5-b5a4-484d-bfbd-d8bc753718b1"/>
<textElement textAlignment="Center" verticalAlignment="Middle"/>
<text><![CDATA[Value]]></text>
</staticText>
</jr:tableHeader>
<jr:detailCell style="table_TD" height="20" rowSpan="1">
<textField>
<reportElement x="0" y="0" width="90" height="20" uuid="925192bc-a761-48f5-bad5-097d15587198"/>
<box leftPadding="3" rightPadding="3"/>
<textElement textAlignment="Right" verticalAlignment="Middle"/>
<textFieldExpression><![CDATA[$F{value}]]></textFieldExpression>
</textField>
</jr:detailCell>
</jr:column>
</jr:table>
</componentElement>
</band>
</detail>
</jasperReport>
Test the example
Adding main method to export to pdf
public static void main(String[] args) throws JRException {
//Compile report
JasperReport report = JasperCompileManager.compileReport("myJasperReport.jrxml");
//Setting up some arbitrary data to test the auto creation of datasource
List<String> someData = new ArrayList<>();
someData.add("Test1_1.23:Test2_4.32:Test3_1.08");
someData.add("Test1_2.12:Test2_5.12:Test3_2.13");
//Fill report
JasperPrint jasperPrint = JasperFillManager.fillReport(report, new HashMap<>(),new JRBeanCollectionDataSource(someData));
//Export to pdf
JRPdfExporter exporter = new JRPdfExporter();
exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput("myJasperReport.pdf"));
SimplePdfExporterConfiguration configuration = new SimplePdfExporterConfiguration();
exporter.setConfiguration(configuration);
exporter.exportReport();
}
Output
Conclusion
The simplest way to provide components with custom datasource depending on running reports values (fields, variables, parameter), is to create a method that generates the datasource and call this in dataSourceExpression

Add custom data source to Jaspersoft Studio

I am trying to fill a table by passing a custom data source to it.
I have created a simple report with a table on it. The report it self gets the data from a ms sql database. I have written a java class similar to the class in this Example. But I get no value in table. At the example there is no scriptlet. I have checked the (String) this.getFieldValue("KN_FormelGG"); line of code. It gets the data from field and can show it on report. So I guess the bean data source is not filled. I call the fill Table method in a afterGroupInit. How can I use Collection of data from java in jasper? I tried also adding the java bean in dataset and query dialog, but it did not help me either. Should I add the scriptlet to subreport/table? The main emphasis of my problem having the custom data source in a scriptlet. I went the other problem through, but I still get no answer. I added $P{FieldDataSource}.getData() to check the data, but it delivers null.
java class 1:
package testProjektIman.scriptlets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.jasperreports.engine.JRDefaultScriptlet;
import net.sf.jasperreports.engine.JRScriptletException;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
public class FillTable extends JRDefaultScriptlet {
#Override
public void afterGroupInit(final String id)
throws JRScriptletException {
fillTable();
}
public ArrayList<String> splitGGArray(final String kNFormelGG) {
ArrayList<String> fieldNames = new ArrayList<>();
String[] array = (kNFormelGG.split(" "));
for (String sub : array) {
fieldNames.add(sub);
}
return fieldNames;
}
public Map<String, Object> fillTable()
throws JRScriptletException {
String kNFormelGG = null;
kNFormelGG = (String) this.getFieldValue("KN_FormelGG");
List<TableCells> listTableCells = new ArrayList<>();
TableCells tableCell;
for (String fn : splitGGArray(kNFormelGG)) {
tableCell = new TableCells();
tableCell.setFieldName(fn);
listTableCells.add(tableCell);
}
JRBeanCollectionDataSource tableCellJRBean = new JRBeanCollectionDataSource(listTableCells);
Map<String, Object> parameters = new HashMap<>();
parameters.put("FieldDataSource", tableCellJRBean);
return parameters;
}
}
Java class 2
package testProjektIman.scriptlets;
public class TableCells {
private String fieldName;
private String keyFormel;
private String mK;
private String notation;
private String Item;
//getters setters
}
jrxml
<?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="tableAutoFill" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="37fc3a9c-38e9-41be-9039-56249c5283d7">
<subDataset name="TableDataSource" uuid="5999e646-aeec-4b2b-b29b-68e897d56999">
<queryString>
<![CDATA[]]>
</queryString>
<field name="fieldName" class="java.lang.String"/>
</subDataset>
<scriptlet name="Filltable" class="testProjektIman.scriptlets.FillTable"/>
<parameter name="FieldDataSource" class="net.sf.jasperreports.engine.data.JRBeanCollectionDataSource" isForPrompting="false"/>
<queryString>
<![CDATA[select * from "KennzahlReferenz2015_QIBericht", "Images"
where LB_ID = 62
and KN_OffiziellGruppe = 3
and IMG_ID = 1]]>
</queryString>
<field name="KN_Id" class="java.lang.Integer"/>
<field name="KN_FormelZ" class="java.lang.String"/>
<field name="KN_FormelGG" class="java.lang.String"/>
<group name="id">
<groupExpression><![CDATA[$F{KN_Id}]]></groupExpression>
<groupHeader>
<band height="50"/>
</groupHeader>
<groupFooter>
<band height="50"/>
</groupFooter>
</group>
<detail>
<band height="191" splitType="Stretch">
<componentElement>
<reportElement x="50" y="18" width="260" height="120" uuid="942ab836-df83-4a2f-8215-845073ad163f">
<property name="com.jaspersoft.studio.layout" value="com.jaspersoft.studio.editor.layout.VerticalRowLayout"/>
<property name="com.jaspersoft.studio.table.style.table_header" value="Table_TH"/>
<property name="com.jaspersoft.studio.table.style.column_header" value="Table_CH"/>
<property name="com.jaspersoft.studio.table.style.detail" value="Table_TD"/>
</reportElement>
<jr:table xmlns:jr="http://jasperreports.sourceforge.net/jasperreports/components" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/components http://jasperreports.sourceforge.net/xsd/components.xsd" whenNoDataType="AllSectionsNoDetail">
<datasetRun subDataset="TableDataSource" uuid="b554ada5-c388-4534-af8e-93571a417adb">
<parametersMapExpression><![CDATA[$P{FieldDataSource}]]></parametersMapExpression>
<dataSourceExpression><![CDATA[$P{FieldDataSource}]]></dataSourceExpression>
</datasetRun>
<jr:column width="100" uuid="f57e4e8e-8a2e-405f-b9ab-7a704e0986fd">
<property name="com.jaspersoft.studio.components.table.model.column.name" value="Column1"/>
<jr:columnHeader style="Table_CH" height="30">
<staticText>
<reportElement x="0" y="0" width="100" height="30" uuid="9a55dd73-71e3-4559-9a8b-17d98bf17753"/>
<textElement>
<font isBold="true"/>
</textElement>
<text><![CDATA[FieldName]]></text>
</staticText>
</jr:columnHeader>
<jr:detailCell style="Table_TD" height="30">
<textField>
<reportElement x="0" y="0" width="100" height="30" uuid="c3e6ccfc-9f91-4d7a-800a-613f5dded928"/>
<textFieldExpression><![CDATA[$F{fieldName}]]></textFieldExpression>
</textField>
</jr:detailCell>
</jr:column>
</jr:table>
</componentElement>
</band>
</detail>
</jasperReport>
Data Adapter
Create a data adapter file, for example adapter.xml, through the user interface. The contents might resemble:
<?xml version="1.0" encoding="UTF-8" ?>
<beanDataAdapter class="net.sf.jasperreports.data.bean.BeanDataAdapterImpl">
<name>YourClass</name>
<factoryClass>com.yourcompany.jasper.JRDataSourceFactory</factoryClass>
<methodName>createCollection</methodName>
<useFieldDescription>false</useFieldDescription>
</beanDataAdapter>
Data Class
Create a class that has a createCollection method, as per the data adapter definition above:
package com.compay.jasper;
public class JRDataSourceFactory {
/**
* #return A collection of data for the report.
*/
public static Collection<YourClass> createCollection() {
return Arrays.asList( new YourClass() );
}
}
Set Report Properties
Ensure that the report has the following property (links the report to the custom data adapter):
<property name="com.jaspersoft.studio.data.defaultdataadapter" value="adapter.xml"/>
Set Report Fields
The report fields should now be able to reference the bean properties:
<field name="yourObject.property" class="java.lang.String">
<fieldDescription><![CDATA[yourObject.property]]></fieldDescription>
</field>
It's important that the fieldDescription element contain a value that reflects the bean property (i.e., the Java code you would normally call to retrieve the value from the bean on an instance of that bean).
Application
The JRDataSourceFactory class stands alone -- it's used by the data adapter to create a collection of bean instances. The static method (createCollection) does the work here and does not, indeed cannot, use inheritance.
Example
If possible, borrow the field names for the report from the bean's attributes. The code as written in the question makes it difficult to discern where the value for KN_Id comes from.
The following example links the data adapter to the field names in the report.
Bean Class
A bean exposes some properties:
package com.company.domain;
public final class Student extends Entity {
private String firstName;
private String lastName;
public String getFirstName() {
return this.firstName;
}
public String getLastName() {
return this.lastName;
}
}
Data Adapter
The data adapter looks like:
<?xml version="1.0" encoding="UTF-8" ?>
<beanDataAdapter class="net.sf.jasperreports.data.bean.BeanDataAdapterImpl">
<name>Student</name>
<factoryClass>com.company.jasper.JRDataSourceFactory</factoryClass>
<methodName>createCollection</methodName>
<useFieldDescription>false</useFieldDescription>
</beanDataAdapter>
Data Class
The data class creates instances of the bean:
package com.compay.jasper;
import com.company.domain.Student;
public class JRDataSourceFactory {
public static Collection<Student> createCollection() {
return Arrays.asList( new Student() );
}
}
Report Fields
The report fields reflect the bean fields:
<field name="firstName" class="java.lang.String">
<fieldDescription><![CDATA[firstName]]></fieldDescription>
</field>
<field name="lastName" class="java.lang.String">
<fieldDescription><![CDATA[lastName]]></fieldDescription>
</field>
A collection of "student" instances is passed into the report. In this example, the collection contains a single instance. In your example, the collection could contain many instances. As the report library iterates over the collection, different values of firstName and lastName will be made available.
The mechanics for how the Student instance data is initially populated is outside the scope of this answer. As far as the reporting tool is concerned, it simply uses pre-populated instances of Student. If FillTable populates TableCells, that's not a concern for the reporting tool.

Filling reports from json using JasperReports [duplicate]

This question already has answers here:
How to fill report using JSON datasource without getting null values?
(3 answers)
Closed 6 years ago.
I'm beginner with JasperReports ( first try ) so,
I set up my netbeans, and my first try using data from database was successful. But now I just want to create my report from json data using Jasper Reports in Netbeans And I think it's not like getting data from Database.
By the way I tried to edit my xml file and add this :
<textField>
<reportElement x="0" y="31" width="555" height="20" uuid="9678a129-61e8-4034-ab8e-739ee5723c87"/>
<textElement textAlignment="Right">
<font size="12" isBold="true"/>
</textElement>
<textFieldExpression><![CDATA[$F{nom}]]></textFieldExpression>
</textField>
But it gives me null in report.
Here is what I did in java side :
Map parametersMap = new HashMap();
parametersMap.put("name", json.getString("Name"));
parametersMap.put("start", json.getString("Start"));
parametersMap.put("end", json.getString("end"));
String report = "C:\\My\\Path\\toReport\\report1.jrxml";
JasperReport Jasp = JasperCompileManager.compileReport(report);
JasperPrint JASP_PRINT = JasperFillManager.fillReport(Jasp,parametersMap);
JasperViewer.viewReport(JASP_PRINT);
UPDATED:
Here is my Java code
public void start(Future<Void> startFuture){
String fileJSON = "C:\\Users\\PathToMyFile\\data.txt";
String file = "/Test1/:name";
Router router = Router.router(vertx);
router.route(file).handler(routingContext -> {
HttpServerResponse response = routingContext.response();
response.setChunked(true);
routingContext.vertx().setTimer(1000, tid -> routingContext.response().end());
});
vertx.createHttpServer()
.requestHandler(router::accept)
.listen(8089, "localhost", res -> {
if (res.succeeded())
startFuture.complete();
else
startFuture.fail(res.cause());
});
vertx.fileSystem().readFile(fileJSON, (AsyncResult<Buffer> result) -> {
if (result.succeeded()) {
JsonObject json = result.result().toJsonObject();
try{
Map parametersMap = new HashMap();
parametersMap.put("name",json.getString("name"));
parametersMap.put("start",json.getString("start"));
parametersMap.put("end",json.getString("end"));
String report = "C:\\Users\\pathToMyPackage\\report1.jrxml";
JasperReport Jasp = JasperCompileManager.compileReport(report);
JasperPrint JASP_PRINT = JasperFillManager.fillReport(Jasp,parametersMap);
JasperViewer.viewReport(JASP_PRINT);
And for my JRXML file :
<property name="ireport.zoom" value="1.0"/>
<property name="ireport.x" value="0"/>
<property name="ireport.y" value="0"/>
<queryString language="json">
<![CDATA[]]>
</queryString>
<field name="nom" class="java.lang.String">
<fieldDescription><![CDATA[name]]></fieldDescription>
</field>
<field name="dateDebut" class="java.lang.String">
<fieldDescription><![CDATA[start]]></fieldDescription>
</field>
<background>
<band splitType="Stretch"/>
</background>
<detail>
<band height="125" splitType="Stretch">
<textField>
<reportElement x="100" y="0" width="100" height="30" uuid="02b279da-3795-4655-8571-5a36a3ef378c"/>
<textFieldExpression><![CDATA[$F{name}]]></textFieldExpression>
</textField>
<staticText>
<reportElement x="0" y="0" width="100" height="30" uuid="671e61ad-8d8f-48cb-969f-78c05a516398"/>
<text><![CDATA[name]]></text>
</staticText>
<textField>
<reportElement x="100" y="30" width="100" height="30" uuid="9d53f46f-a252-48b3-9213-8c3092c29f49"/>
<textFieldExpression><![CDATA[$F{start}]]></textFieldExpression>
</textField>
<staticText>
<reportElement x="0" y="30" width="100" height="30" uuid="3b49affb-685a-4df2-a872-c0e6fdcab94b"/>
<text><![CDATA[start]]></text>
</staticText>
</band>
</detail>
And my JSON file :
{
"Name": "Test",
"Start": "16-06-2015",
"End":"16-06-2019"
}
You need to pass the data as a datasource, in json this is done by passing the stream through the parameter map (since you are using vertex, get the json in String format and then pass it as a stream).
Example
InputStream iostream = new ByteArrayInputStream(jsonString.getBytes(StandardCharsets.UTF_8));
parametersMap.put(JsonQueryExecuterFactory.JSON_INPUT_STREAM, iostream);
Then you can define the fields related to your json and json (xpath) query

Getting null values in report when using JavaBean Data Source

When I tried to generate a report by using JavaBean Data Source and displaying the bean's field values in the table, the PDF report is showing null values.
I have a simple bean (PersonBean) as follows:
public class PersonBean {
private String Field1;
private String Field2;
public String getField1() {
return Field1;
}
public void setField1(String field1) {
Field1 = field1;
}
public String getField2() {
return Field2;
}
public void setField2(String field2) {
Field2 = field2;
}
}
The Person class which populate and return the collection of bean is as follows:
import java.util.ArrayList;
import java.util.List;
public class Person {
public static java.util.List<PersonBean> getReportData() throws Exception {
List<PersonBean> personBeanList = null;
try {
personBeanList = new ArrayList<PersonBean>();
PersonBean personBean1 = new PersonBean();
personBean1.setField1("Hina");
personBean1.setField2("Sachdev");
personBeanList.add(personBean1);
PersonBean personBean2 = new PersonBean();
personBean2.setField1("Swathi");
personBean2.setField2("Singh");
personBeanList.add(personBean2);
} catch (Exception e) {
e.printStackTrace();
}
return personBeanList;
}
}
The PersonReport class which creates report is as follows:
import java.io.FileNotFoundException;
import java.util.*;
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;
import net.sf.jasperreports.view.JasperViewer;
public class PersonReport implements JRDataSource {
public static void main(String[] args) throws JRException, FileNotFoundException {
try {
Map<String, Object> params = new HashMap<String, Object>();
JasperDesign jasperDesign = JRXmlLoader.load("C:/Users/sachdevh/Desktop/reports/personReport.jrxml");
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params,
new JRBeanCollectionDataSource(Person.getReportData()));
JasperExportManager.exportReportToPdfFile(jasperPrint, "./Util/bean.pdf");
JasperViewer.viewReport(jasperPrint);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public Object getFieldValue(JRField arg0) throws JRException {
return null;
}
#Override
public boolean next() throws JRException {
return false;
}
}
By using iReport 4.6.0, I designed a report by inserting table component.
The jrxml file is as follows:
<?xml version="1.0" encoding="UTF-8"?>
<jasperReport ..>
<subDataset name="New Dataset 1" uuid="50bff6d9-9b98-444b-9851-bdd37ea570e4">
<queryString><![CDATA[]]></queryString>
<field name="field1" class="java.lang.String">
<fieldDescription><![CDATA[field1]]></fieldDescription>
</field>
<field name="field2" class="java.lang.String">
<fieldDescription><![CDATA[field2]]></fieldDescription>
</field>
</subDataset>
<parameter name="SUBREPORT_DIR" class="java.lang.String" isForPrompting="false">
<defaultValueExpression><![CDATA["C:\\Users\\sachdevh\\Desktop\\reports\\"]]></defaultValueExpression>
</parameter>
<parameter name="parameter1" class="java.lang.String">
<defaultValueExpression><![CDATA[$F{field1}]]></defaultValueExpression>
</parameter>
<queryString>
<![CDATA[]]>
</queryString>
<field name="field1" class="java.lang.String">
<fieldDescription><![CDATA[field1]]></fieldDescription>
</field>
<field name="field2" class="java.lang.String">
<fieldDescription><![CDATA[field2]]></fieldDescription>
</field>
<background>
<band splitType="Stretch"/>
</background>
<title>
<band height="79" splitType="Stretch"/>
</title>
<pageHeader>
<band height="35" splitType="Stretch"/>
</pageHeader>
<columnHeader>
<band height="61" splitType="Stretch">
<componentElement>
<reportElement uuid="b3e3e08d-91d9-4e01-ae74-abdfc270551a" key="table" x="0" y="0" width="555"
height="61"/>
<jr:table xmlns:jr="http://jasperreports.sourceforge.net/jasperreports/components"
xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/components http://jasperreports.sourceforge.net/xsd/components.xsd">
<datasetRun subDataset="New Dataset 1" uuid="f5f39e4f-4349-4e5d-9736-03f84a7a7617">
<dataSourceExpression>
<![CDATA[new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource(Person.getReportData())]]></dataSourceExpression>
</datasetRun>
<jr:column uuid="9e2a6076-7f96-40c8-86ae-318b521a4f81" width="90">
<jr:tableHeader height="30"/>
<jr:tableFooter height="30"/>
<jr:columnHeader height="30">
<staticText>
<reportElement uuid="99411482-c1d5-44fa-aef7-9d9f4bf392ec" x="0" y="0" width="90"
height="30"/>
<textElement/>
<text><![CDATA[field1]]></text>
</staticText>
</jr:columnHeader>
<jr:columnFooter height="30"/>
<jr:detailCell height="20">
<textField>
<reportElement uuid="74861d9e-48a8-47ce-a477-81d4f497d483" x="0" y="0" width="90"
height="20"/>
<textElement/>
<textFieldExpression><![CDATA[$F{field1}]]></textFieldExpression>
</textField>
</jr:detailCell>
</jr:column>
<jr:column uuid="84c3b078-0114-452e-b3a3-f1c7dcd1b8cb" width="90">
<jr:tableHeader height="30"/>
<jr:tableFooter height="30"/>
<jr:columnHeader height="30">
<staticText>
<reportElement uuid="cb87f1a0-bbbf-40b2-bb19-292ecf8d9a18" x="0" y="0" width="90"
height="30"/>
<textElement/>
<text><![CDATA[field2]]></text>
</staticText>
</jr:columnHeader>
<jr:columnFooter height="30"/>
<jr:detailCell height="20">
<textField>
<reportElement uuid="84fd788f-24e8-4dfa-8c83-ce388c663f45" x="0" y="0" width="90"
height="20"/>
<textElement/>
<textFieldExpression><![CDATA[$F{field2}]]></textFieldExpression>
</textField>
</jr:detailCell>
</jr:column>
</jr:table>
</componentElement>
</band>
</columnHeader>
<detail>
<band height="125" splitType="Stretch"/>
</detail>
<columnFooter>
<band height="45" splitType="Stretch"/>
</columnFooter>
<pageFooter>
<band height="54" splitType="Stretch"/>
</pageFooter>
<summary>
<band height="42" splitType="Stretch"/>
</summary>
</jasperReport>
I think the datasource expression below
<dataSourceExpression><![CDATA[new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource(Person.getReportData())]]></dataSourceExpression>
You can solve this issue in two steps:
Move table component to the Title band (now it lies in Column Header band) - to prevent occurring of net.sf.jasperreports.engine.JRRuntimeException: Infinite loop creating new page due to column header overflow exception in cases when datasource has a lot of elements;
Change the table's subDataset dataSourceExpression to value below, that is relevant to your Java code:
<datasetRun subDataset="New Dataset 1" uuid="f5f39e4f-4349-4e5d-9736-03f84a7a7617">
<dataSourceExpression><![CDATA[$P{REPORT_DATA_SOURCE}]]></dataSourceExpression>
</datasetRun>

Categories