Hot questions for Using JasperReports in datasource

Question:

I'm using Jasper Reports to build a simple report pdf. I have a JSON file that looks like this:

{"employees": [
    {"firstName" : "John", "lastName" : "Doe"},
    {"firstName" : "Anna", "lastName" : "Smith"},
    {"firstName" : "Peter", "lastName" : "Jones"}
]}

And I'm trying to read it in like this:

File file = new File("E:/Workspaces/jasperPDFreport/src/main/resources/emp.json");
JsonDataSource datasource = new JsonDataSource(file);

JasperDesign jasperDesign = JRXmlLoader.load("E:/Workspaces/jasperPDFreport/src/main/resources/jsonTemplate.jrxml");
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
Map parameters = new HashMap();
JasperPrint jasperPrint;
jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, datasource);
JasperExportManager.exportReportToPdfFile(jasperPrint, "BasicReport.pdf");
JasperViewer.viewReport(jasperPrint);

However my the values from the JSON file are not passed to my pdf.

This is my Template:

<?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 6.1.1.final using JasperReports Library version 6.1.1  -->
<!-- 2015-10-22T13:45:32 -->
<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="Blank_A4_2" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="9e494ebe-c1fb-4448-bcee-38994e9720f7">
    <!--property name="net.sf.jasperreports.json.source" value="emp.json"/-->
    <queryString language="json">
        <![CDATA[employees]]>
    </queryString>  
    <field name="firstName" class="java.lang.String">
        <fieldDescription><![CDATA[firstName]]></fieldDescription>
    </field>
    <field name="lastName" class="java.lang.String">
        <fieldDescription><![CDATA[lastName]]></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{firstName}]]></textFieldExpression>
            </textField>
            <staticText>
                <reportElement x="0" y="0" width="100" height="30" uuid="671e61ad-8d8f-48cb-969f-78c05a516398"/>
                <text><![CDATA[firstName]]></text>
            </staticText>
            <textField>
                <reportElement x="100" y="30" width="100" height="30" uuid="9d53f46f-a252-48b3-9213-8c3092c29f49"/>
                <textFieldExpression><![CDATA[$F{lastName}]]></textFieldExpression>
            </textField>
            <staticText>
                <reportElement x="0" y="30" width="100" height="30" uuid="3b49affb-685a-4df2-a872-c0e6fdcab94b"/>
                <text><![CDATA[lastName]]></text>
            </staticText>
        </band>
    </detail>
</jasperReport>

Now you see the commented out line

property name="net.sf.jasperreports.json.source" value="emp.json"

If I comment this in, everything works as intended, I don't want to hard code my JSON values into the template, because later on I want to get them from a rest service, that's not ready yet. I do not understand, why the values are not getting parsed into the report, instead i just get two null values.


Answer:

From JasperReports - JSON Data Source Sample (version 6.4.3)

The built-in JSON query executer (see the JsonQueryExecuter class) is a tool that uses the query string to produce a JsonDataSource instance, based on specific built-in parameters (or equivalent report properties). This query executer is registered via JsonQueryExecuterFactory factory class. In order to prepare the data source, the JSON query executer looks for the JSON_INPUT_STREAM parameter that contains the JSON source objects in the form of an java.io.InputStream. If no JSON_INPUT_STREAM parameter is provided, then the query executer looks for the alternate net.sf.jasperreports.json.source String parameter or report property that stores the path to the location of the JSON source file. JsonQueryExecuter runs the query over the input source and stores the result in an in-memory JsonDataSource object.

So if you do not want to use:

<property name="net.sf.jasperreports.json.source" value="emp.json"/>

You need to pass the file as java.io.InputStream in the parameter JSON_INPUT_STREAM

Hence you are currently passing it as datasource you should try something like this

params.put(JsonQueryExecuterFactory.JSON_INPUT_STREAM, new FileInputStream(file));
JasperFillManager.fillReportToFile(jasperReport, params);

If you instead like to use the new JsonQLQueryExecuterFactory JSONQL Data Source

params.put(JsonQLQueryExecuterFactory.JSON_INPUT_STREAM, new FileInputStream(file));
JasperFillManager.fillReportToFile(jasperReport, params);

Question:

I work at a report that need a subreport, so I want to pass datasource from a Java method to subreport, but I don't arrive at the correct way. Usually I use the followin piece of code to create my report. What is the correct way to send datasource to subreport?

Map<String, Object> param = new HashMap<>();
param.put("rapportNom", "Module");
param.put("PAR_IMAGE_BACKGROUND", "/dz/suivi/reporting/sources/BackgroundElit.png");
param.put("PAR_IMAGE_HEADER", "/dz/suivi/reporting/sources/headerElit.png");
param.put("SUBREPORT_DIR", "/dz/suivi/reporting/sources/moduleAllDetail_subreport1.jasper");
param.put("SUBREPORT_DATA", "LIST OF OBJECT");

return Reporting.printEtat(getClass().getResourceAsStream("/dz/suivi/reporting/sources/moduleAllDetail.jasper"),
                param, new JRBeanCollectionDataSource(reportingModuleViewFacade.findById(module)));

Answer:

If you have your datasource as a List<MyBean> as simple method is:

  1. Pass it in the parameter map

    param.put("SUBREPORT_DATA", myBeanList);
    
  2. Define the parameter in jrxml

    <parameter name="SUBREPORT_DATA" class="java.util.List"/>
    
  3. Create a JRBeanCollectionDataSource using your parameter

    <subreport>
        <reportElement x="0" y="0" width="200" height="100" uuid="406c9014-e74b-42d9-b9e1-4af106bfb779"/>
        <dataSourceExpression><![CDATA[new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($P{SUBREPORT_DATA})]]></dataSourceExpression>
        <subreportExpression><![CDATA[$P{SUBREPORT_DIR} + "theSubreport.jasper"]]></subreportExpression>
    </subreport>
    

Question:


Answer:

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

Question:


Answer:

The JRBeanCollectionDataSource as you can see in api implements both JRDataSource and JRRewindableDataSource.

The JRDataSource is a consumable datasource (only next() method) but the JRRewindableDataSource adds a moveFirst() method which makes it possibile to rewind the datasource.

However, this is not simple to do in the jrxml file (the design file) and I would not recommend doing it.

The simplest solution in your case is that instead of passing a JRBeanCollectionDataSource pass the List (your summaryList) and create the JRBeanCollectionDataSource in side your jrxml as many times as you need.

Example

In java

paramsMap.put("statsData", summaryList);

In jrxml

<parameter name="statsData" class="java.util.List"/>
...
<subreportParameter name="statsData">
    <subreportParameterExpression><![CDATA[new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($P{statsData})]]></subreportParameterExpression>
</subreportParameter>
...

Note for future readers: This subreport is particular it passes a datasource as a parameter (that will be used to populate a jr:table in the subreport), normally you would pass the datasource in the <dataSourceExpression>

Question:

In my case i need to use both JRBeanCollectionDataSource and embedded query in jasper report.

if i need a connection i feed the report as below ,

JasperPrint jprint = (JasperPrint) JasperFillManager.fillReport(is, hm, ds.getConnection() );

and if i have a collection to show in report, feed as below ,

JasperPrint jprint = (JasperPrint) JasperFillManager.fillReport(is, hm, getBeanDataSource());

getBeanDataSource method returns a JRBeanColleactionDataSource object contains the desired data in it .

Both works fine. But in some cases i need to feed a section of a report with beans and an other with query. Is there a way to do this ?


Answer:

Yes and no, The main report needs one datasource, but you can use sub reports within your report and if you like to send the datasource you do it trough the parameters.

HashMap<String,Object> hm= new HashMap<String,Object>();
hm.put("datasource", getBeanDataSource());

in jrxml

<parameter name="datasource" 
 class="net.sf.jasperreports.engine.data.JRBeanCollectionDataSource"/>

the subreport to use this datasource would be something like this

<subreport>
  <reportElement positionType="Float" x="-20" y="28" width="595" height="102" isRemoveLineWhenBlank="true" uuid="84c78233-8870-4563-9138-e166bb6000fd"/>
   <dataSourceExpression><![CDATA[$P{datasource}]]></dataSourceExpression>
   <subreportExpression><![CDATA[$P{your sub report jrxml}]]></subreportExpression>
</subreport>

Question:

I have to print a sub report for each row in main report, but the problem is I got my data for sub report only when I am returning a field value for one of the column (Subreport depends upon the value returned for that field value in each row) in main report.

I read jasper reports do not support typical data types in field values ($F{abc} can hold only limited data types like string, number etc) like Arrays, List, Collection or JRDataSource.

These complex data types are supported by Parameters but parameter values should be passed to main report during JasperFillManager.fillreport() function at that time I don't have data source for my sub report.

Is there any way by which I can pass my JRDataSource to sub report during exporting main report?

Is possible or not? If it is, then how?


Answer:

In report designer click on the subreport and set Data Source Expression

new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($F{List<YourObjectObject>})

And in main report you can create List<YourObjectObject>

Question:

I am trying to use Jasper Reports 6.5.1 to pass data from Java into the field properties in the report using JRBeanCollectionDataSource.

I have created the JavaBean and the report and all the data seems to be passing through without any issues, but the final result is a blank page which I can't seem to resolve. Any assistance would be greatly appreciated. Please see my code below...

Thanks in advance

Code generating report

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
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.data.JRBeanCollectionDataSource;

public class Jasper{

    public static void main(String[] args) throws JRException, FileNotFoundException {

        ArrayList<JasperBean> list = new ArrayList<JasperBean>();

        String reportFile = "C:\\test\\tester.jrxml";
        String output = "C:\\test\\Jasper.pdf";

        JasperBean data = new JasperBean();

        data.setName("Freddie");
        data.setSurname("Wilson");
        data.setTitle("Mr.");

        list.add(data);
        JasperReport jr = JasperCompileManager.compileReport(reportFile);
        JRDataSource dataSource = new JRBeanCollectionDataSource(list);
        Map<String, Object> params = new HashMap<>();
        params.put("DataSource", dataSource);
        JasperPrint print = JasperFillManager.fillReport(jr, params);
        FileOutputStream out = new FileOutputStream(new File(output));
        JasperExportManager.exportReportToPdfStream(print, out);        
    }
}

JavaBean

import java.io.Serializable;

public class JasperBean implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    private String name;
    private String Surname;
    private String title;

    public String getName() {
        return name;
    }

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

    public String getSurname() {
        return Surname;
    }

    public void setSurname(String surname) {
        Surname = surname;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }   
}

Herewith the Report Source XML

<?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 6.5.1.final using JasperReports Library version 6.5.1  -->
<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="tester" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="2dabb962-4ca0-4006-881b-9c608349031a">
    <property name="com.jaspersoft.studio.data.defaultdataadapter" value="One Empty Record"/>
    <field name="DataSource" class="testing.JasperBean"/>
    <field name="title" class="java.lang.String"/>
    <field name="name" class="java.lang.String"/>
    <field name="surname" class="java.lang.String"/>
    <background>
        <band splitType="Stretch"/>
    </background>
    <detail>
        <band height="311" splitType="Stretch">
            <textField>
                <reportElement x="50" y="162" width="232" height="18" uuid="00051b07-d9a7-4531-a757-70afa89f17cf"/>
                <textFieldExpression><![CDATA[$F{title} + " " + $F{name} + " " + $F{surname}]]></textFieldExpression>
            </textField>
        </band>
    </detail>
</jasperReport>

Answer:

Use in the main() method:

JasperPrint print = JasperFillManager.fillReport(jr, params, dataSource);

Remove from the jrxml file:

<field name="DataSource" class="testing.JasperBean"/>

Question:

I have two different classes, One is Person and another one is Address. The Person class has an object of Address class as one of its property. For example

class Person{
   String name;
   Address address;
}

I cannot change the structure of the class and cannot add any new collections because of other problems.

My problem is, I want to use objects of Person class as datasource for my JasperReports's report which has fields from both Person and Address Class. Can Somebody Please Help


Answer:

You can try something like this:

  1. Declare only the instances variables of the Person class as jasper reports fields: one field will be "name" of type java.lang.String and another field will be "address" of type your.package.Address (that's it).

  2. Then, if you want to print address specific information in the report, create a Text Field square where you want such info to be displayed and use the expression editor to write something like this: $F{address}.getZipCode() (assuming that Address class has such method and you want to print such info)...

Hope this help...

Question:

I have already worked with Jasper Reports using JRResultSetDataSource, but it's the first time I working with Jasper using JRBeanCollectionDataSource.

I'm trying to run a report test with the following code:

Cliente.java

public class Cliente {
    private String nomeCliente;

    public String getNomeCliente() {
        return nomeCliente;
    }

    public void setNomeCliente(String nomeCliente) {
        this.nomeCliente = nomeCliente;
    }
}

Report.java

public class Report<T> {
    private Collection<T> dataList;
    private String jrxml;

    public Report() {
    }

    public Report(Collection<T> dataList, String jrxml) {
        super();
        this.dataList = dataList;
        this.jrxml = jrxml;
    }

    public Collection<T> getDataList() {
        return dataList;
    }

    public void setDataList(Collection<T> dataList) {
        this.dataList = dataList;
    }

    public String getJrxml() {
        return jrxml;
    }

    public void setJrxml(String jrxml) {
        this.jrxml = jrxml;
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public void getReport(Collection<T> dataList, String jrxml) throws Exception {
        JasperReport report = null;
        JasperDesign reportDesign;

        try {
            reportDesign = JRXmlLoader.load(jrxml);
            report = JasperCompileManager.compileReport(reportDesign);

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

        JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(dataList);

        Map params = new HashMap();
        params.put("dataSource", dataList);

        JasperPrint jsPrint = null;

        try {
            jsPrint = JasperFillManager.fillReport(report, params, beanColDataSource);
        } catch (JRException e1) {
            e1.printStackTrace();
        }

        JasperViewer viewer = new JasperViewer(jsPrint, false);
        viewer.setVisible(true);
    }
}

clientereport.jrxml

<?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 6.6.0.final using JasperReports Library version 6.6.0  -->
<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="estiloinstitutobeleza_report" language="groovy" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="05a86d77-8b2c-49cc-9bf6-27fbf7a545d5">
    <property name="ireport.zoom" value="1.0"/>
    <property name="ireport.x" value="0"/>
    <property name="ireport.y" value="0"/>
    <property name="com.jaspersoft.studio.data.defaultdataadapter" value="One Empty Record"/>
    <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>
    <style name="Table 1_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 1_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 1_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="d50d967c-8a6d-4e1e-b44e-49261df940e9">
        <queryString>
            <![CDATA[]]>
        </queryString>
        <field name="nomeCliente" class="java.lang.String"/>
    </subDataset>
    <parameter name="dataSource" class="net.sf.jasperreports.engine.data.JRBeanCollectionDataSource"/>
    <field name="id" class="java.lang.Integer"/>
    <field name="nome" class="java.lang.String"/>
    <field name="sexo" class="java.lang.Integer"/>
    <field name="datanascimento" class="java.lang.String"/>
    <field name="logradouro" class="java.lang.String"/>
    <field name="numero" class="java.lang.Integer"/>
    <field name="complemento" class="java.lang.String"/>
    <field name="bairro" class="java.lang.String"/>
    <field name="cidade" class="java.lang.String"/>
    <field name="uf" class="java.lang.Integer"/>
    <field name="cep" class="java.lang.String"/>
    <field name="telefone" class="java.lang.String"/>
    <field name="celular1" class="java.lang.String"/>
    <field name="celular2" class="java.lang.String"/>
    <field name="email1" class="java.lang.String"/>
    <field name="email2" class="java.lang.String"/>
    <group name="nome">
        <groupExpression><![CDATA[$F{nomeCliente}]]></groupExpression>
    </group>
    <background>
        <band splitType="Stretch"/>
    </background>
    <title>
        <band height="23" splitType="Stretch">
            <staticText>
                <reportElement x="202" y="0" width="167" height="23" uuid="6ec26fa8-d021-455c-8bf5-b2716a0c7919"/>
                <textElement>
                    <font size="16" isBold="true"/>
                </textElement>
                <text><![CDATA[Relatório de Clientes]]></text>
            </staticText>
            <image>
                <reportElement x="1" y="-20" width="172" height="43" uuid="d382676c-4568-4b4f-b9a6-6e4741aab5ee"/>
                <imageExpression><![CDATA["images/EstiloInstitutoBelezaLogo.png"]]></imageExpression>
            </image>
        </band>
    </title>
    <pageHeader>
        <band height="20" splitType="Stretch">
            <textField>
                <reportElement x="435" y="0" width="80" height="20" uuid="06d08240-2804-45f3-8c68-199839537286"/>
                <textElement textAlignment="Right"/>
                <textFieldExpression><![CDATA["Página "+$V{PAGE_NUMBER}+" de"]]></textFieldExpression>
            </textField>
            <textField evaluationTime="Report">
                <reportElement x="515" y="0" width="40" height="20" uuid="9db45469-0ec8-4a69-8e02-95ecd71639ce"/>
                <textFieldExpression><![CDATA[" " + $V{PAGE_NUMBER}]]></textFieldExpression>
            </textField>
        </band>
    </pageHeader>
    <columnHeader>
        <band height="14" splitType="Stretch">
            <line>
                <reportElement x="0" y="13" width="555" height="1" uuid="3d9ff8e2-9dfa-4e1a-bf04-4c08222532aa"/>
            </line>
            <line>
                <reportElement x="198" y="0" width="1" height="13" uuid="3ccdd4cc-2dcc-4547-981a-7dd0c0795ef3"/>
            </line>
            <line>
                <reportElement x="300" y="0" width="1" height="13" uuid="2c50fa85-487d-4595-9144-f78adb6d8f32"/>
            </line>
            <line>
                <reportElement x="398" y="0" width="1" height="13" uuid="856b71be-60fd-450f-933e-b092ef412abb"/>
            </line>
            <staticText>
                <reportElement x="0" y="0" width="202" height="14" uuid="36ac836a-63d7-47b5-82b1-c2fb15034dc6"/>
                <text><![CDATA[Nome]]></text>
            </staticText>
            <staticText>
                <reportElement x="202" y="0" width="100" height="14" uuid="8ff1d64c-ae30-4c97-a544-c6eb1989ce05"/>
                <text><![CDATA[Data de Nascimento]]></text>
            </staticText>
            <staticText>
                <reportElement x="402" y="0" width="100" height="14" uuid="01153fec-09ae-4945-b3cb-04c254fb0e65"/>
                <text><![CDATA[Celular]]></text>
            </staticText>
            <staticText>
                <reportElement x="302" y="0" width="100" height="14" uuid="5ab92c2e-f72c-442a-b321-d84841953aa3"/>
                <text><![CDATA[Telefone]]></text>
            </staticText>
        </band>
    </columnHeader>
    <detail>
        <band height="205" splitType="Stretch">
            <line>
                <reportElement x="0" y="13" width="555" height="1" uuid="ab35d598-27d4-4410-a86a-0876cf839aef"/>
            </line>
            <line>
                <reportElement x="198" y="0" width="1" height="13" uuid="1dd11b36-1226-4917-a2b5-ae60c5c3ef8b"/>
            </line>
            <line>
                <reportElement x="300" y="0" width="1" height="13" uuid="abef3282-f707-4dd8-bd23-a0a07ef60fb6"/>
            </line>
            <line>
                <reportElement x="398" y="0" width="1" height="13" uuid="4b153f11-2e81-4f19-97d3-64f40cda5ffb"/>
            </line>
            <componentElement>
                <reportElement x="1" y="0" width="554" height="13" uuid="21f104d0-3d32-4bf7-a5bf-a062dcb67f89">
                    <property name="com.jaspersoft.studio.layout" value="com.jaspersoft.studio.editor.layout.VerticalRowLayout"/>
                    <property name="com.jaspersoft.studio.table.style.table_header" value="Table 1_TH"/>
                    <property name="com.jaspersoft.studio.table.style.column_header" value="Table 1_CH"/>
                    <property name="com.jaspersoft.studio.table.style.detail" value="Table 1_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">
                    <datasetRun subDataset="Dataset1" uuid="ec5065e1-b31a-4ae5-8ad9-574969eadcfb">
                        <datasetParameter name="REPORT_DATA_SOURCE">
                            <datasetParameterExpression><![CDATA[$P{dataSource}]]></datasetParameterExpression>
                        </datasetParameter>
                    </datasetRun>
                    <jr:column width="554" uuid="c5e7b9ad-85cf-40fe-aa2d-8f8af92bab6f">
                        <jr:detailCell style="Table 1_TD" height="30">
                            <textField>
                                <reportElement x="0" y="0" width="554" height="30" uuid="ed6e2650-5949-404b-a542-05e79b134580"/>
                                <textFieldExpression><![CDATA[$F{nomeCliente}]]></textFieldExpression>
                            </textField>
                        </jr:detailCell>
                    </jr:column>
                </jr:table>
            </componentElement>
        </band>
    </detail>
    <columnFooter>
        <band splitType="Stretch"/>
    </columnFooter>
    <pageFooter>
        <band height="20" splitType="Stretch">
            <textField evaluationTime="Report">
                <reportElement x="515" y="0" width="40" height="20" uuid="e564df6b-0f6f-4ea1-8a9d-aac36c0a1914"/>
                <textFieldExpression><![CDATA[" " + $V{PAGE_NUMBER}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="435" y="0" width="80" height="20" uuid="9cb91f0b-9fb2-475e-a59b-706eb9beccef"/>
                <textElement textAlignment="Right"/>
                <textFieldExpression><![CDATA["Página "+$V{PAGE_NUMBER}+" de"]]></textFieldExpression>
            </textField>
        </band>
    </pageFooter>
    <summary>
        <band splitType="Stretch"/>
    </summary>
</jasperReport>

Main.java

import java.util.ArrayList;
import java.util.List;

import br.com.cts.model.Cliente;
import br.com.cts.util.Report;

public class Main {

    public static void main(String[] args) throws Exception {
        Cliente cliente1 = new Cliente();
        cliente1.setNomeCliente("John");

        Cliente cliente2 = new Cliente();
        cliente2.setNomeCliente("Mike");

        List<Cliente> clientes = new ArrayList<>();
        clientes.add(cliente1);
        clientes.add(cliente2);

        Report<Cliente> report = new Report<Cliente>();
        report.getReport(clientes, "reports/clientereport.jrxml");
    }
}

I'm getting the following error:

net.sf.jasperreports.engine.design.JRValidationException: Report design not valid : 
     1. Field not found : nomeCliente
    at net.sf.jasperreports.engine.design.JRAbstractCompiler.verifyDesign(JRAbstractCompiler.java:280)
    at net.sf.jasperreports.engine.design.JRAbstractCompiler.compileReport(JRAbstractCompiler.java:152)
    at net.sf.jasperreports.engine.JasperCompileManager.compile(JasperCompileManager.java:357)
    at net.sf.jasperreports.engine.JasperCompileManager.compileReport(JasperCompileManager.java:617)
    at br.com.cts.util.Report.getReport(Report.java:53)
    at br.com.cts.main.Main.main(Main.java:23)
Exception in thread "main" java.lang.NullPointerException
    at net.sf.jasperreports.engine.fill.JRFiller.createReportFiller(JRFiller.java:267)
    at net.sf.jasperreports.engine.fill.JRFiller.fill(JRFiller.java:156)
    at net.sf.jasperreports.engine.fill.JRFiller.fill(JRFiller.java:145)
    at net.sf.jasperreports.engine.JasperFillManager.fill(JasperFillManager.java:689)
    at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:1005)
    at br.com.cts.util.Report.getReport(Report.java:68)
    at br.com.cts.main.Main.main(Main.java:23)

I don't know what is wrong at my code.


Answer:

It looks like you are trying to add an extra layer that does not belong. You are passing to the report a data source that is List<Cliente>. Therefore, your report shouldn't have a subDataset.

Your main report should have

<field name="nomeCliente" class="java.lang.String" />

It should not have all the other field names that you have unless they are also part of Cliente.

So you are getting the error because the field name is not in the list of fields, just like the error suggests. One reason to have a subDataset would be if you have another List within your main data source (another property in Cliente that is List<String> nicknames or something like that).

Question:

We designed a new report using json data with jsonql as the query language and multiple sub report levels that generates fine in Jaspersoft studio (v6.6.0).

We need some java code to take the generated json data and create a report using precompiled jasper files on server, running Jasper 6.6.0 on server, however when we try to generate the pdf's in java, some sub reports crash saying it cant find the data to use and when we remove those problematic sub reports, it generates a mostly blank file with 1 or 2 headings and no relevant information/tables are shown.

    InputStream jasperTemplateStream = getReportingTemplate();

    JRDataSource jsonDataSource = new JsonQLDataSource(request);

    JasperReport jasperReport = (JasperReport) JRLoader.loadObject(jasperTemplateStream);

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

    JasperExportManager.exportReportToPdfStream(jasperPrint, response);

Any ideas as to why? Our Jaspersoft Studio and Jasper mvn versions are the same.

The stacktrace is as follows:

net.sf.jasperreports.engine.JRRuntimeException: net.sf.jasperreports.engine.fill.JRExpressionEvalException: Error evaluating expression for source text: ((net.sf.jasperreports.engine.data.JsonQLDataSource)$P{REPORT_DATA_SOURCE}).subDataSource("assetClasses") 
...
Caused by: net.sf.jasperreports.engine.fill.JRExpressionEvalException: Error evaluating expression for source text: ((net.sf.jasperreports.engine.data.JsonQLDataSource)$P{REPORT_DATA_SOURCE}).subDataSource("assetClasses")
...
Caused by: net.sf.jasperreports.engine.JRException: No JSON data to operate on!

Answer:

Instead of passing the data input stream to the fillReport() method, try passing it through in the parameter map instead:

Map<String, Object> params = new HashMap<>();
params.put(JsonQLQueryExecuterFactory.JSON_INPUT_STREAM, request);
JasperReport jasperReport = (JasperReport) 
JRLoader.loadObject(jasperTemplateStream);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params);
JasperExportManager.exportReportToPdfStream(jasperPrint, response);

Question:

I want to compile a .JRXML file with an XML Datasource in Java. It works perfectly within iReport. In Java, it does not work.

When I set the main query language to 'xpath', the report is generated, but with no xml data in it.

With 'xpath2' as the main query language, I get an error "No query executer factory registered for the 'xpath2' language" and the report is not being generated.

It doesn't even work with the simplest report you can think of.

What I've tried so far:

  • Checked for the following line in jasperreports.properties: net.sf.jasperreports.query.executer.factory.xpath2=com.jaspersoft.jrx.query.JRXPathQueryExecuterFactory
  • Checked for the .jar file "jasperreports-extensions-3.5.3.jar" in my applications classpath
  • Added this line to my Java code: jasperReport.setProperty("net.sf.jasperreports.query.executer.factory.xpath2", "com.jaspersoft.jrx.query.JRXPathQueryExecuterFactory");
  • Set the XML Datasource in Java: org.w3c.dom.Document document = JRXmlUtils.parse(JRLoader.getLocationInputStream(args[2])); params.put(JRXPathQueryExecuterFactory.PARAMETER_XML_DATA_DOCUMENT, document);

My report generation code:

JasperReport jasperReport = JasperCompileManager.compileReport(args[0]);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, new JREmptyDataSource());
JasperExportManager.exportReportToPdfFile(jasperPrint, args[1]);

After adding jasper-compiler-jdt-5.5.23.jar to my Java Build Path, I got rid of the xpath2 error. The report is generated, but with no data source.


Answer:

It now works with an xpath datasource. I created the datasource in my Java application instead of passing the XML_URL. It's not perfect, but a good workaround. This is the code I used:

org.w3c.dom.Document document = JRXmlUtils.parse(JRLoader.getLocationInputStream("/file/location.xml"));
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, new JRXmlDataSource(document, "/xpath"));

Question:

I have specific class like that:

public class testClass {

  private String name;

  private List<ListData> listDatas;

  public String getName() {
      return name;
  }

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

  public List<ListData> getListData() {
      return listData;
  }

  public void setListData(List<ListData> listData) {
      this.listData = listData;
  }
}

This class comes from @RestController side and @RequestBody sets all data with JSON. I also using JPA here.

On @Service layer I want to use testClass data, to JasperFillManager.

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

fillReport's 3. parameter expect JRDataSource type of data. But my object is not JRDataSource. How can I cast it to JRDataSource. İs there any way?


Answer:

You don't cast the object as a JRDataSource because they aren't related to each other polymorphically. Instead you need write an implementation of JRDataSource that accesses your data. Something like this:

public class MyJRDataSource implements JRDataSource {
    private final testClass data;

    public MyJRDataSource(testClass data) {
        this.data = data;
    }

    @Override
    Object getFieldValue(JRField field) {
        // get value of field here
    }

    @Override
    boolean next() {
        // move to next row of data
    }
}

Question:

Cannot view main report with subreport...

Main Java Class

   public class SubRepoExample {

    public static void main(String[] args) throws JRException {
       SubRepoExample repo = new SubRepoExample();
       repo.combineMasterAndSubreport();
    }

     public void combineMasterAndSubreport() throws JRException{

         JasperReport main = JasperCompileManager.compileReport("src/subrepoexample/masterReport.jrxml");

        JasperReport sub = JasperCompileManager.compileReport("src/subrepoexample/subReport.jrxml");

        //create a list for holding the subreport object



        SubreportWrapper subDataWrap = new SubreportWrapper();

        List<SubreportObject> subData = subDataWrap.getSubData();

        Map para = new HashMap();
        //pass the report itself through a parameter
        para.put("SUBREPORT", sub);
        //pass the list to parameter
        para.put("subData",subData);


        JasperPrint jp = JasperFillManager.fillReport(main, para,new   JRTableModelDataSource(createMasterData()));
        JasperViewer.viewReport(jp, false);  

    }

      public DefaultTableModel createMasterData(){

        String [] cols = {"COL_1","COL_2","COL_3"};
        Object[][] data = {{"Data","Data","Data"},
                        {"Data","Data","Data"},                                  
                      };
         DefaultTableModel dtm = new DefaultTableModel(data,cols);

    return dtm;}

}

SubreportObject class reponsible for creating subreport data which eventually is placed on a List.

 public class SubreportObject {
      String name;
      int age;

     public SubreportObject(String name,int age){
         this.name = name;
         this.age = age;  
         }

     public String getName() {
     return name;
         }

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

     public int getAge() {
     return age;
         }

     public void setAge(int age) {
     this.age = age;
         }

      }

Bean Factory Class

 public class SubreportWrapper {
    //String name;
    List<SubreportObject> subData;

//    public SubreportWrapper(List<SubreportObject> subData){
//        this.subData = subData;
//    }

    public List<SubreportObject> getSubData() {

        subData = new ArrayList();
        subData.add(new SubreportObject("Jane",20));
        subData.add(new SubreportObject("Mike",25));
        subData.add(new SubreportObject("Kev",20));
        return subData;
    }
    public void setSubData(List<SubreportObject> subData) {
        this.subData = subData;
    }  
  }

JRXML snippets both in Main jrxml and Subreport jrxml

Datasorce snippet through JRBeanCollection The SUBREPORT_DIR is in place

Error stacktrace

What am I doing wrong?


Answer:

You are setting JRBeanCollectionDatasource constructor with subdata as field $F{subData}, use parameter instead: $P{subData}.

No need to pass subreport in SUBREPORT parameter since the .jasper file will be loaded based on subreportExpression and SUBREPORT_DIR parameter.

Question:

I am getting error in iReport when during subreport compilation:

Errors compiling E:\workspace_new\kidslake\src\main\resources\admissionForm_sub_1.jasper!
Compilation exceptions: com.jaspersoft.ireport.designer.compiler.ErrorsCollector@28f84e61  
net.sf.jasperreports.engine.JRException: Errors were encountered when compiling report expressions class file: 
1. The method getFullName() is undefined for the type Object                 
value = ((java.lang.Object)field_director.getValue()).getFullName(); //$JR_EXPR_ID=17$                                                                       
2. The method getFullName() is undefined for the type Object                 
value = ((java.lang.Object)field_director.getOldValue()).getFullName(); //$JR_EXPR_ID=17$                                                                          
3. The method getFullName() is undefined for the type Object                 
value = ((java.lang.Object)field_director.getValue()).getFullName(); //$JR_EXPR_ID=17$                                                                       
3 errors      
at net.sf.jasperreports.engine.design.JRAbstractCompiler.compileReport(JRAbstractCompiler.java:204)     
at com.jaspersoft.ireport.designer.compiler.IReportCompiler.run(IReportCompiler.java:512)     
at org.openide.util.RequestProcessor$Task.run(RequestProcessor.java:572)     

My bean class is like

 class Mainclass{
     private List<AdmissionForm> admissionForm;
     //getter
     //setter
 }

 class AdmissionForm{
    private Director director;
    //getter
    //setter
 }

 class Director{
    private String fullName;
    //getter
    //setter
 }

I am passing JRBeanCollectionDataSource as list of MainClass in my main report

I defined subreport and pass field like new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($F{admissionFormList})

I define to access director fullname property in my subreport

$F{director}.getFullName()

but when i compile main report or subreport getting the error above.

Help me to resolve my issue


Answer:

You can do one of the following:

  1. Set the type of the director report field to Director (full/qualified class name). Apparently the current field type is java.lang.Object
  2. Change the report language to Groovy.
  3. Declare a report field called director.fullName and use the field directly instead of $F{director}.getFullName()

Question:

WHAT I HAVE

My Main Report shows all values are null from my subreport.

WHAT I WANT

I am passing data to subReport from MainReport through a parameter called subData as shown in the MainReport JRXML snippet below.

NB: Its a List

My subReport snippet in the MainReport is given below, the dataSource expression is clearly "$P{subData}"

My main java class passes an instance of a List (named subData) through a parameter (named subDataOrion) shown below.

public class SubRepoExample {

public static void main(String[] args) throws JRException {
   SubRepoExample repo = new SubRepoExample();
   repo.combineMasterAndSubreport();
}

public void combineMasterAndSubreport() throws JRException{

    JasperReport main = JasperCompileManager.compileReport("src/subrepoexample/masterReport.jrxml");

    JasperReport sub = JasperCompileManager.compileReport("src/subrepoexample/subReport.jrxml");



   //create a list for holding the subreport object

    //SubreportWrapper subDataWrap = new SubreportWrapper();

    List<SubreportObject> subData = new ArrayList();
    //subData.add(subDataWrap.getSubData());
    subData.add(new SubreportObject("Kevin",20));
    subData.add(new SubreportObject("Jane",20));
    subData.add(new SubreportObject("Mike",20));
    subData.add(new SubreportObject("Simon",20)); 
    //subData.add(new SubreportObject("Naomi",25));
    //subData.add(new SubreportObject("Pat",20));


    //SubreportWrapper subDataWrap = new SubreportWrapper();

    //List<SubreportObject> subData = subDataWrap.getSubData();

    Map para = new HashMap();
    //pass the report itself through a parameter
    //para.put("SUBREPORT", sub);
    //pass the list to parameter
    //JRDataSource subx = new JRBeanCollectionDataSource(subData);
    para.put("subDataOrion",subData);

    //JasperPrint jp = JasperFillManager.fillReport(sub, para,new JRBeanCollectionDataSource(subData));      
    //JasperPrint jp = JasperFillManager.fillReport(main, para,new JRTableModelDataSource(createMasterData()));


     JasperCompileManager.compileReportToFile(
            "src/subrepoexample/subReport.jrxml", 
            "src/subrepoexample/subReport.jasper"); 


    JasperPrint jp = JasperFillManager.fillReport(main, para,new JRTableModelDataSource(createMasterData()));
    JasperViewer.viewReport(jp, false);  

}

 public DefaultTableModel createMasterData(){

    String [] cols = {"COL_1","COL_2","COL_3"};
    Object[][] data = {{"Data","Data","Data"},
                       {"Data","Data","Data"},       
                       {"Data","Data","Data"},   
                       {"Data","Data","Data"},   
                       {"Data","Data","Data"},  
                      };
    DefaultTableModel dtm = new DefaultTableModel(data,cols);

return dtm;}

}

SubReport class that creates the subReport objects

public class SubreportObject {
  String name;
  int age;

 public SubreportObject(String name,int age){
     this.name = name;
     this.age = age;  
     }

 public String getName() {
 return name;
     }

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

 public int getAge() {
 return age;
     }

 public void setAge(int age) {
 this.age = age;
     }

  }

I am aware there are two issues here, the arrangement issue of the data since the subreport data is mixed. or scrambled with the main report data as shown in the first screen shot. This I think can be fixed by groups, which is not my question here.

MY QUESTION:

I need first to eliminate the 'null' values so that I can go to the next stage of using group expression. Am stuck here and not sure what is wrong? At least I asked this question and at least 'null' values appeared, earlier they were completely not appearing.

Why is the data in the List appearing as 'null', when compiled separately, they compile wonderfully.

EDIT 1:

Sorry for being sloppy on the earlier version of this question. Thank you people.

EDIT 2:

I have added the JRBeanCollection as shown below

Even changed the parameter class to JRDataSource as below

but still shows null values..???


Answer:

You are missing the JRBeanCollectionDatasource, a List is not a datasource per se, unless it implements the JRDataSource interface should be wrapped/adapted by a JRDataSource.

Question:

I am new to jasper reports. I am trying to generate a pdf from a son file, which contains some info like name, class etc and an array marks. I am trying to render the marks array as a table. my JSON is

{"data": {"name" : "Johny",
    "class" : "A2",
    "sub" : "cs",
    "interest" : "films",
    "marks" : [{
               "subject" : "Maths",
               "mark" : "24",
               "grade" : "A",
               "remarks" : "",
               "slNo" : "1"
               },
               {
               "subject" : "English",
               "mark" : "24",
               "grade" : "A",
               "remarks" : "",
               "slNo" : "2"
               },

               ]
}}

I have given subdatasource expression as

<dataSourceExpression><![CDATA[((net.sf.jasperreports.engine.data.JsonDataSource)$P{REPORT_DATA_SOURCE}).subDataSource()]]></dataSourceExpression>

Full jrxml - Here

Now I call these from java like,

File jsonFile = new File("/Volumes/Johny/Work/EclipseWorkspace/SecondReport/res/Marks.Json");
JasperDesign jasperDesign = JRXmlLoader.load(new File("/Volumes/Johny/Work/EclipseWorkspace/SecondReport/res/First.jrxml"));
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);

parameters.put(JsonQueryExecuterFactory.JSON_INPUT_STREAM, new FileInputStream(jsonFile));
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters);
JasperExportManager.exportReportToPdfFile(jasperPrint, "/Users/johnykutty/Desktop/Sample2.pdf");

Other fields are getting populated, but table values are getting as null.


Answer:

Found answer from here The issue was I have to pass the key for the array in dataSourceExpression. So, the dataSourceExpression should be like

<dataSourceExpression><![CDATA[((net.sf.jasperreports.engine.data.JsonDataSource)$P{REPORT_DATA_SOURCE}).subDataSource("marks")]]></dataSourceExpression>

Note the "marks" parameter to subDataSource() method

Question:

I am trying to create a report which populates a table of data. I have all the data within a collection of this structure:

Collection<Map<String, ?>> dataSource = new ArrayList<>();

I create the data as follows:

Collection<BatchValue> cashBatches = new ArrayList<BatchValue>();
Collection<BatchValue> checkBatches = new ArrayList<BatchValue>();
Collection<Map<String, ?>> dataSource = new ArrayList<>();    
Map<String, Object> depositMap = new HashMap<>();
depositMap.put("phoneNumber",   deposit.getControllersPhoneNumber());
depositMap.put("accountNumber", deposit.getAccountNumber());
depositMap.put("depositNumber", deposit.getDepositNumber().toString());
depositMap.put("depositDate",   dateFormat.format(deposit.getDepositDate()));
depositMap.put("checkCount", Long.toString(deposit.getTotalPayments()));
depositMap.put("depositAmount", NumberFormat.getCurrencyInstance(Locale.US).format(deposit.getTotalDepositAmount()));
depositMap.put("cashBatches", cashBatches); //Collection of objects
depositMap.put("checkBatches", checkBatches); //Collection of objects

dataSource.add(depositMap);

The object in the collection looks like this:

public class BatchValue {

    public BatchValue(String batchNumber, String batchTotal, String checkTotal) {
        super();
        this.batchNumber = batchNumber;
        this.batchTotal = batchTotal;
        this.checkTotal = checkTotal;
    }
    public String batchNumber;
    public String batchTotal;
    public String checkTotal;
    public String getBatchNumber() {
        return batchNumber;
    }
    public String getBatchTotal() {
        return batchTotal;
    }
    public String getCheckTotal() {
        return checkTotal;
    }
}

Printing out works except my table data is null. The report looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 6.1.1.final using JasperReports Library version 6.1.1  -->
<!-- 2016-01-07T13:29:51 -->
<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="cashReceiptsBalanceTape" pageWidth="260" pageHeight="600" columnWidth="220" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="c88ca9b5-e46e-4379-a4a6-aa91568a6750">
    <property name="com.jaspersoft.studio.data.defaultdataadapter" value="One Empty Record"/>
    <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>
    <style name="Table 1_TH" mode="Opaque" backcolor="#FFFFFF">
        <box>
            <pen lineWidth="0.5" lineColor="rgba(0, 0, 0, 0.0)"/>
            <topPen lineWidth="0.5" lineColor="rgba(0, 0, 0, 0.0)"/>
            <leftPen lineWidth="0.5" lineColor="rgba(0, 0, 0, 0.0)"/>
            <bottomPen lineWidth="0.5" lineColor="rgba(0, 0, 0, 0.0)"/>
            <rightPen lineWidth="0.5" lineColor="rgba(0, 0, 0, 0.0)"/>
        </box>
    </style>
    <style name="Table 1_CH" mode="Opaque" backcolor="rgba(255, 191, 191, 0.0)">
        <box>
            <pen lineWidth="0.5" lineColor="rgba(0, 0, 0, 0.0)"/>
            <topPen lineWidth="0.5" lineColor="rgba(0, 0, 0, 0.0)"/>
            <leftPen lineWidth="0.5" lineColor="rgba(0, 0, 0, 0.0)"/>
            <bottomPen lineWidth="0.5" lineColor="rgba(0, 0, 0, 0.0)"/>
            <rightPen lineWidth="0.5" lineColor="rgba(0, 0, 0, 0.0)"/>
        </box>
    </style>
    <style name="Table 1_TD" mode="Opaque" backcolor="#FFFFFF">
        <box>
            <pen lineWidth="0.5" lineColor="rgba(0, 0, 0, 0.0)"/>
            <topPen lineWidth="0.5" lineColor="rgba(0, 0, 0, 0.0)"/>
            <leftPen lineWidth="0.5" lineColor="rgba(0, 0, 0, 0.0)"/>
            <bottomPen lineWidth="0.5" lineColor="rgba(0, 0, 0, 0.0)"/>
            <rightPen lineWidth="0.5" lineColor="rgba(0, 0, 0, 0.0)"/>
        </box>
    </style>
    <subDataset name="cashBatches" uuid="d4f4efbb-3bc1-4134-b8a7-4f6fae0756b2">
        <queryString>
            <![CDATA[]]>
        </queryString>
        <field name="batchNumber" class="java.lang.String"/>
        <field name="checkCount" class="java.lang.String"/>
        <field name="batchTotal" class="java.lang.String">
            <fieldDescription><![CDATA[]]></fieldDescription>
        </field>
    </subDataset>
    <subDataset name="checkBatches" uuid="b40af45e-8c43-49eb-815a-592bec1f5140">
        <queryString>
            <![CDATA[]]>
        </queryString>
        <field name="batchNumber" class="java.lang.String"/>
        <field name="checkCount" class="java.lang.String"/>
        <field name="batchTotal" class="java.lang.String">
            <fieldDescription><![CDATA[]]></fieldDescription>
        </field>
    </subDataset>
    <queryString>
        <![CDATA[]]>
    </queryString>
    <field name="accountNumber" class="java.lang.String">
        <fieldDescription><![CDATA[]]></fieldDescription>
    </field>
    <field name="phoneNumber" class="java.lang.String">
        <fieldDescription><![CDATA[]]></fieldDescription>
    </field>
    <field name="depositNumber" class="java.lang.String">
        <fieldDescription><![CDATA[]]></fieldDescription>
    </field>
    <field name="depositDate" class="java.lang.String">
        <fieldDescription><![CDATA[]]></fieldDescription>
    </field>
    <field name="checkCount" class="java.lang.String">
        <fieldDescription><![CDATA[]]></fieldDescription>
    </field>
    <field name="depositAmount" class="java.lang.String">
        <fieldDescription><![CDATA[]]></fieldDescription>
    </field>
    <field name="checkList" class="java.lang.String">
        <fieldDescription><![CDATA[]]></fieldDescription>
    </field>
    <field name="cashBatches" class="java.util.Collection"/>
    <background>
        <band splitType="Stretch"/>
    </background>
    <title>
        <band height="18" splitType="Stretch">
            <property name="com.jaspersoft.studio.unit.height" value="pixel"/>
            <printWhenExpression><![CDATA[$V{PAGE_NUMBER} == 1]]></printWhenExpression>
            <staticText>
                <reportElement x="9" y="1" width="196" height="16" uuid="7151aef5-2d0d-4982-a07f-602530cd14db">
                    <property name="com.jaspersoft.studio.unit.height" value="pixel"/>
                </reportElement>
                <textElement textAlignment="Center"/>
                <text><![CDATA[Deposit Tape]]></text>
            </staticText>
        </band>
    </title>
    <pageHeader>
        <band height="35" splitType="Stretch">
            <property name="com.jaspersoft.studio.unit.height" value="pixel"/>
            <printWhenExpression><![CDATA[$V{PAGE_NUMBER} == 1]]></printWhenExpression>
            <staticText>
                <reportElement x="9" y="4" width="60" height="16" uuid="2b6a4e34-7d68-4acf-8cd5-fd97ca24e16b"/>
                <textElement verticalAlignment="Top"/>
                <text><![CDATA[Date Printed]]></text>
            </staticText>
            <textField pattern="M/d/yy h:mm a">
                <reportElement x="69" y="3" width="136" height="16" uuid="2b533300-6aae-428b-a2be-117ea5560848">
                    <property name="com.jaspersoft.studio.unit.height" value="pixel"/>
                </reportElement>
                <textElement verticalAlignment="Top"/>
                <textFieldExpression><![CDATA[new java.util.Date()]]></textFieldExpression>
            </textField>
            <staticText>
                <reportElement x="9" y="19" width="100" height="16" uuid="3b875843-da5d-424a-8540-f305c8d2b189">
                    <property name="com.jaspersoft.studio.unit.height" value="pixel"/>
                </reportElement>
                <text><![CDATA[State Insurance Fund]]></text>
            </staticText>
        </band>
    </pageHeader>
    <detail>
        <band height="400" splitType="Stretch">
            <property name="com.jaspersoft.studio.unit.height" value="pixel"/>
            <property name="com.jaspersoft.studio.layout" value="com.jaspersoft.studio.editor.layout.FreeLayout"/>
            <textField>
                <reportElement x="69" y="1" width="100" height="16" uuid="3884d87f-bc02-408a-8de8-60bc9869532d">
                    <property name="com.jaspersoft.studio.unit.height" value="pixel"/>
                </reportElement>
                <textFieldExpression><![CDATA[$F{accountNumber}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="9" y="19" width="100" height="16" uuid="b6c1b69a-4353-4315-99ba-19dd7e75b209">
                    <property name="com.jaspersoft.studio.unit.height" value="pixel"/>
                </reportElement>
                <textFieldExpression><![CDATA[$F{phoneNumber}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="113" y="41" width="85" height="16" uuid="070b177a-3384-4886-aac1-1a0fda6e6109">
                    <property name="com.jaspersoft.studio.unit.width" value="pixel"/>
                </reportElement>
                <textElement textAlignment="Right"/>
                <textFieldExpression><![CDATA[$F{depositNumber}]]></textFieldExpression>
            </textField>
            <staticText>
                <reportElement x="9" y="41" width="100" height="16" uuid="4e698823-3523-4b98-884e-72541da8e37e">
                    <property name="com.jaspersoft.studio.unit.height" value="pixel"/>
                </reportElement>
                <text><![CDATA[Deposit No.]]></text>
            </staticText>
            <textField>
                <reportElement x="113" y="57" width="85" height="16" uuid="a3c67e6f-15a1-4f90-ad44-dfca3259a96d">
                    <property name="com.jaspersoft.studio.unit.height" value="pixel"/>
                </reportElement>
                <textElement textAlignment="Right"/>
                <textFieldExpression><![CDATA[$F{depositDate}]]></textFieldExpression>
            </textField>
            <staticText>
                <reportElement x="9" y="57" width="100" height="16" uuid="3dacca23-94c7-4f5b-829e-406147029ed0"/>
                <text><![CDATA[Deposit Date]]></text>
            </staticText>
            <textField>
                <reportElement x="113" y="73" width="85" height="16" uuid="38c09b4e-33ad-48d5-828b-43ccb09d408e">
                    <property name="com.jaspersoft.studio.unit.height" value="pixel"/>
                </reportElement>
                <textElement textAlignment="Right"/>
                <textFieldExpression><![CDATA[$F{checkCount}]]></textFieldExpression>
            </textField>
            <staticText>
                <reportElement x="9" y="73" width="100" height="16" uuid="176c17e0-40c0-458e-adb2-5b7df73586a1"/>
                <text><![CDATA[Check Count]]></text>
            </staticText>
            <staticText>
                <reportElement x="9" y="89" width="100" height="16" uuid="22f6ee5c-7e7f-4436-b363-7a7611c20a1a"/>
                <text><![CDATA[Deposit Amount]]></text>
            </staticText>
            <textField>
                <reportElement x="113" y="89" width="85" height="16" uuid="111ecf32-09d9-4fc8-99a6-f83fed971e99">
                    <property name="com.jaspersoft.studio.unit.height" value="pixel"/>
                </reportElement>
                <textElement textAlignment="Right"/>
                <textFieldExpression><![CDATA[$F{depositAmount}]]></textFieldExpression>
            </textField>
            <staticText>
                <reportElement x="9" y="1" width="60" height="16" uuid="28512e49-36e3-4f4d-970d-97fe1996cb0f">
                    <property name="com.jaspersoft.studio.unit.height" value="pixel"/>
                </reportElement>
                <text><![CDATA[Account No.]]></text>
            </staticText>
            <componentElement>
                <reportElement x="16" y="137" width="189" height="103" isPrintWhenDetailOverflows="true" uuid="4709e78f-8a76-440c-a660-261c3ece5482">
                    <property name="com.jaspersoft.studio.layout" value="com.jaspersoft.studio.editor.layout.VerticalRowLayout"/>
                    <property name="net.sf.jasperreports.export.headertoolbar.table.name" value="cashBatches"/>
                </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="cashBatches" uuid="9bd659a0-e16c-47fa-abcf-d0ee807cd1c2">
                        <dataSourceExpression><![CDATA[new net.sf.jasperreports.engine.JREmptyDataSource()]]></dataSourceExpression>
                    </datasetRun>
                    <jr:column width="50" uuid="d09b02c6-a73e-4020-8198-8a742bfbe7ee">
                        <jr:columnHeader style="Table 1_CH" height="30">
                            <staticText>
                                <reportElement x="0" y="0" width="50" height="30" uuid="3ba095fd-0b7c-4e85-b2ad-52c4c0d959f4"/>
                                <text><![CDATA[Batch Number]]></text>
                            </staticText>
                        </jr:columnHeader>
                        <jr:detailCell style="Table 1_TD" height="30">
                            <textField>
                                <reportElement x="0" y="0" width="50" height="30" uuid="cb8ca692-b96f-41d5-af5f-b6bbd325166a"/>
                                <textFieldExpression><![CDATA[$F{batchNumber}]]></textFieldExpression>
                            </textField>
                        </jr:detailCell>
                    </jr:column>
                    <jr:column width="30" uuid="0b05b7df-e05c-45c7-ab76-467eb9679a15">
                        <jr:columnHeader style="Table 1_CH" height="30">
                            <staticText>
                                <reportElement x="0" y="0" width="30" height="30" uuid="de68b063-cc82-4b37-a849-827f9c9d2b59"/>
                                <text><![CDATA[Check Count]]></text>
                            </staticText>
                        </jr:columnHeader>
                        <jr:detailCell style="Table 1_TD" height="30">
                            <textField>
                                <reportElement x="0" y="0" width="30" height="30" uuid="f6756213-69f2-4d88-9d7b-0d7de889a9c5"/>
                                <textFieldExpression><![CDATA[$F{checkCount}]]></textFieldExpression>
                            </textField>
                        </jr:detailCell>
                    </jr:column>
                    <jr:column width="102" uuid="6038b058-f354-4322-9c1a-e425c6301ae7">
                        <jr:columnHeader style="Table 1_CH" height="30">
                            <staticText>
                                <reportElement x="0" y="0" width="102" height="30" uuid="f5fc6b01-aa5c-44c3-95f6-da3c1c9c8357"/>
                                <text><![CDATA[Batch Total]]></text>
                            </staticText>
                        </jr:columnHeader>
                        <jr:detailCell style="Table 1_TD" height="30">
                            <textField>
                                <reportElement x="0" y="0" width="102" height="30" uuid="b4a9187e-7b20-49e5-873a-9ee67ae2a555"/>
                                <textFieldExpression><![CDATA[$F{batchTotal}]]></textFieldExpression>
                            </textField>
                        </jr:detailCell>
                    </jr:column>
                </jr:table>
            </componentElement>
            <textField>
                <reportElement x="-11" y="250" width="191" height="150" uuid="93ad77fe-963b-49df-b4c7-abb6891ea914"/>
                <textFieldExpression><![CDATA[$F{cashBatches}]]></textFieldExpression>
            </textField>
        </band>
    </detail>
    <summary>
        <band height="48" splitType="Stretch">
            <textField>
                <reportElement x="95" y="10" width="85" height="16" uuid="a6ca03fc-5921-489a-b9f1-5049e0a7a0e0">
                    <property name="com.jaspersoft.studio.unit.height" value="pixel"/>
                </reportElement>
                <textElement textAlignment="Right"/>
                <textFieldExpression><![CDATA[$F{depositAmount}]]></textFieldExpression>
            </textField>
            <line>
                <reportElement x="84" y="4" width="98" height="1" uuid="3a51cf9c-87c4-4017-8bab-e0e868443242"/>
            </line>
        </band>
    </summary>
</jasperReport>

However if I print the field - the data is there as you can see in this image.


Answer:

Ok I found the issue and I am posting to help others.

One: I needed to use the following to unwrap my class:

new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource
        ($F{cashBatches})

Then I needed to ensure that both the field name and field description were set to the property name or I got an error:

Caused by: java.lang.NoSuchMethodException: Unknown property '' 

Question:

I'm working on a simple JRBeanCollection example, i am just trying to print all the property values of a javabean collection to a pdf report.

The problem is that my code prints only those of the first bean of the list i create.

Here is all the code i have written,

public static void main(String[] args) {
    String fileName = "src/test/report2.jasper";
    String outFileName = "test.pdf";
    HashMap hm = new HashMap();
    JRBeanCollectionDataSource beanCollectionDataSource = new JRBeanCollectionDataSource(FundBeanFactory.createBeanCollection());
    try {
        JasperPrint print = JasperFillManager.fillReport(
                fileName,
                hm,
                beanCollectionDataSource);

        JRPdfExporter exporter = new JRPdfExporter();

        exporter.setExporterInput(new SimpleExporterInput(print));
        exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(outFileName));
        SimplePdfExporterConfiguration configuration = new SimplePdfExporterConfiguration();
        configuration.setCreatingBatchModeBookmarks(true);
        exporter.setConfiguration(configuration);
        exporter.exportReport();
    } catch (JRException e) {
        e.printStackTrace();
    }
}

The bean class,

public class FundBean {

  private Double debit;
  private Double credit;

  public Double getCredit() {
      return credit;
  }

  public void setCredit(Double credit) {
      this.credit = credit;
  }

  public Double getDebit() {
      return debit;
  }

  public void setDebit(Double debit) {
      this.debit = debit;
  }
}

The beanFactory class which creates the list,

public class FundBeanFactory {

  public static List<FundBean> createBeanCollection(){
    List<FundBean> fundBeans   = new ArrayList<FundBean>();

    FundBean bean1 = new FundBean();
    bean1.setCredit(89201.12);
    bean1.setDebit(122392.23);

    FundBean bean2 = new FundBean();
    bean2.setCredit(95650.16);
    bean2.setDebit(787878.80);
    fundBeans.add(bean1);
    fundBeans.add(bean2);

    return fundBeans;
  }
 }

The jrxml file:

<parameter name="Credit" class="java.lang.Double"/>
<field name="debit" class="java.lang.Double"/>
<field name="credit" class="java.lang.Double"/>
<background>
    <band splitType="Stretch"/>
</background>
<title>
    <band height="79" splitType="Stretch">
        <staticText>
            <reportElement mode="Opaque" x="61" y="17" width="420" height="43" backcolor="#999999" uuid="6878b8e7-ffdc-4465-842f-c1b6de0b5d87"/>
            <textElement>
                <font size="24"/>
            </textElement>
            <text><![CDATA[              Available Funds Test]]></text>
        </staticText>
    </band>
</title>
<pageHeader>
    <band height="35" splitType="Stretch"/>
</pageHeader>
<columnHeader>
    <band height="151" splitType="Stretch">
        <staticText>
            <reportElement mode="Opaque" x="0" y="0" width="100" height="41" backcolor="#0033CC" uuid="2fca55e7-bfc3-4795-9735-5f4ca5b621e6"/>
            <textElement>
                <font size="24"/>
            </textElement>
            <text><![CDATA[Debits]]></text>
        </staticText>
        <staticText>
            <reportElement mode="Opaque" x="100" y="0" width="100" height="41" backcolor="#0066CC" uuid="25536a17-ca40-4256-bc82-fca3b79be2ab"/>
            <textElement>
                <font size="24"/>
            </textElement>
            <text><![CDATA[Credits]]></text>
        </staticText>
        <textField>
            <reportElement x="0" y="41" width="100" height="67" uuid="56004fd8-48e8-4cfe-9ecc-53324b94f8a2"/>
            <textFieldExpression><![CDATA[$F{debit}]]></textFieldExpression>
        </textField>
        <textField>
            <reportElement x="100" y="41" width="100" height="67" uuid="ba4e4ab6-4a0f-4486-b2e6-15ffc0d04808"/>
            <textFieldExpression><![CDATA[$F{credit}]]></textFieldExpression>
        </textField>
    </band>
</columnHeader>

bean2 credit and debit values are not printed, why is this happening?


Answer:

To output report rows you need to put your fields in the detail band of the report. You have used the column header band which is, naturally, only printed once.

Question:

I'm trying to print a report. I send to the report 1 a DataSource with 3 objects. The Band Detail contains a Subreport (report 2). My Problem: Why is it printed only once?

Each object sent contains another DataSource with 3 objects. Report 2 sends this DataSource to report 3 and the rows are printed. (How I expected).

Why does it work from report 2 to report 3? Why does it not work from report 1 to report 2?

It is a JavaFX application.

MY TEST:

try {
   File report1File = Actions.getReportFromPackage("layout/spProgramm.jrxml");
   File report2File = Actions.getReportFromPackage("layout/spWeek.jrxml");

   JasperReport report1 = JasperCompileManager.compileReport(report1File.getAbsolutePath());
   JasperReport report2 = JasperCompileManager.compileReport(report2File.getAbsolutePath());

   ArrayList<JRWeek> report2ArrayList = new ArrayList<>();

   report2ArrayList.add(JRWeek.newObject("1"));
   report2ArrayList.add(JRWeek.newObject("2"));
   report2ArrayList.add(JRWeek.newObject("3"));

   JRBeanCollectionDataSource report2DataSource = new JRBeanCollectionDataSource(report2ArrayList);

   Map<String, Object> parameters = new HashMap<String, Object>();
   parameters.put("report2", report2);
   parameters.put("report2DataSource", report2DataSource);

   JasperPrint jasperPrint = JasperFillManager.fillReport(report1, parameters, new JREmptyDataSource());

   JasperViewer jv = new JasperViewer(jasperPrint, false);
} catch (JRException e) {
   System.out.println(e.getMessage());
}

Class: JRWeek

public class JRWeek {

  private JasperReport report3;
  private JRBeanCollectionDataSource report3DataSource;

  public static JRWeek newObject(String week) throws JRException {
    JRWeek jrWeek = new JRWeek();

    File report3File = Actions.getReportFromPackage("layout/spRows.jrxml");
    JasperReport report3 = JasperCompileManager.compileReport(report3File.getAbsolutePath());

    ArrayList<JRRow> jrRows = new ArrayList<>();
    jrRows.add(new JRRow("REPORT 3 WEEK" + week, "ROW 1"));
    jrRows.add(new JRRow("REPORT 3 WEEK" + week, "ROW 2"));
    jrRows.add(new JRRow("REPORT 3 WEEK" + week, "ROW 3"));

    jrWeek.setReport3(report3);
    jrWeek.setReport3DataSource(new JRBeanCollectionDataSource(jrRows));

    return jrWeek;
  }
// Getter and Setter
}

Class: JRRow

public class JRRow {

  private String text1;
  private String text2;

  public JRRow(String text1, String text2) {
    super();
    this.text1 = text1;
    this.text2 = text2;
  }
// Getter and Setter
}

Report 1: spProgramm.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="spMeetingProgramm" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="0053568c-4b27-4125-bdd4-3172dc64051b">
    <property name="com.jaspersoft.studio.data.defaultdataadapter" value="One Empty Record"/>
    <parameter name="report2" class="net.sf.jasperreports.engine.JasperReport"/>
    <parameter name="report2DataSource" class="net.sf.jasperreports.engine.data.JRBeanCollectionDataSource"/>
    <pageHeader>
        <band height="60">
            <rectangle>
                <reportElement x="0" y="0" width="555" height="60" forecolor="#FFFFFF" backcolor="#0B6798" uuid="976d792c-c89b-4ea1-bda7-af6b30392492"/>
                <graphicElement>
                    <pen lineWidth="0.0" lineColor="#0B6798"/>
                </graphicElement>
            </rectangle>
            <textField>
                <reportElement x="0" y="0" width="555" height="30" forecolor="#FFFFFF" uuid="43b185ef-16a8-40b2-a933-ecc0fe3adc70"/>
                <textElement textAlignment="Center" verticalAlignment="Middle">
                    <font size="14" isBold="true"/>
                </textElement>
                <textFieldExpression><![CDATA["REPORT 1 HEADER 1"]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="0" y="30" width="555" height="30" forecolor="#FFFFFF" uuid="9172e851-2e29-4f95-9542-519930e7aa3d"/>
                <textElement textAlignment="Center" verticalAlignment="Middle">
                    <font size="16" isBold="true"/>
                </textElement>
                <textFieldExpression><![CDATA["REPORT 1 HEADER 2"]]></textFieldExpression>
            </textField>
        </band>
    </pageHeader>
    <detail>
        <band height="35">
            <subreport>
                <reportElement stretchType="RelativeToBandHeight" x="0" y="10" width="555" height="25" uuid="aae0c36a-3373-45cb-a030-ed835e3d0005"/>
                <dataSourceExpression><![CDATA[$P{report2DataSource}]]></dataSourceExpression>
                <subreportExpression><![CDATA[$P{report2}]]></subreportExpression>
            </subreport>
        </band>
    </detail>
</jasperReport>

Report 2: spWeek.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="spMeetingWeek" pageWidth="555" pageHeight="842" columnWidth="555" leftMargin="0" rightMargin="0" topMargin="0" bottomMargin="0" uuid="e6d013b3-aa4c-4ba7-ab71-aaec14a42962">
    <property name="com.jaspersoft.studio.data.defaultdataadapter" value="One Empty Record"/>
    <field name="report3" class="net.sf.jasperreports.engine.JasperReport"/>
    <field name="report3DataSource" class="net.sf.jasperreports.engine.data.JRBeanCollectionDataSource"/>
    <group name="weekHeader">
        <groupHeader>
            <band height="17">
                <rectangle>
                    <reportElement x="0" y="0" width="555" height="17" backcolor="#17365D" uuid="70d3c82d-21e2-4dd1-80a9-8ca137ebe569"/>
                    <graphicElement>
                        <pen lineWidth="0.5"/>
                    </graphicElement>
                </rectangle>
                <textField>
                    <reportElement x="5" y="0" width="550" height="17" forecolor="#FFFFFF" uuid="45cdacc1-7833-4296-b942-1ce3ab998189"/>
                    <textElement verticalAlignment="Top">
                        <font fontName="SansSerif" size="12" isBold="true"/>
                    </textElement>
                    <textFieldExpression><![CDATA["REPORT 2 HEADER 1"]]></textFieldExpression>
                </textField>
            </band>
        </groupHeader>
    </group>
    <group name="header1">
        <groupHeader>
            <band height="17">
                <rectangle>
                    <reportElement x="0" y="0" width="555" height="17" backcolor="#DEA900" uuid="a5f3a182-963d-456a-9102-de1bbf18895d"/>
                    <graphicElement>
                        <pen lineWidth="0.5"/>
                    </graphicElement>
                </rectangle>
                <textField>
                    <reportElement x="5" y="0" width="550" height="17" forecolor="#FFFFFF" uuid="4f94c435-2a99-4c90-8fea-2d30e7c04272"/>
                    <textElement verticalAlignment="Top">
                        <font fontName="SansSerif" size="12" isBold="true"/>
                    </textElement>
                    <textFieldExpression><![CDATA["REPORT 2 HEADER 2"]]></textFieldExpression>
                </textField>
            </band>
        </groupHeader>
    </group>
    <group name="header1Rows">
        <groupHeader>
            <band height="5">
                <subreport>
                    <reportElement stretchType="RelativeToBandHeight" x="0" y="0" width="555" height="5" uuid="0daf0871-3f2e-4287-b42a-f99b554bcd62"/>
                    <dataSourceExpression><![CDATA[$F{report3DataSource}]]></dataSourceExpression>
                    <subreportExpression><![CDATA[$F{report3}]]></subreportExpression>
                </subreport>
            </band>
        </groupHeader>
    </group>
</jasperReport>

Report 3: spRows.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="spMeetingMinistryPartRow" pageWidth="555" pageHeight="842" columnWidth="555" leftMargin="0" rightMargin="0" topMargin="0" bottomMargin="0" uuid="e6d013b3-aa4c-4ba7-ab71-aaec14a42962">
    <property name="com.jaspersoft.studio.data.defaultdataadapter" value="One Empty Record"/>
    <field name="text1" class="java.lang.String"/>
    <field name="text2" class="java.lang.String"/>
    <detail>
        <band height="17">
            <rectangle>
                <reportElement stretchType="RelativeToBandHeight" x="0" y="0" width="555" height="17" uuid="09a1f023-2151-43df-831a-6f3a2d19494d"/>
                <graphicElement>
                    <pen lineWidth="0.5"/>
                </graphicElement>
            </rectangle>
            <textField isStretchWithOverflow="true">
                <reportElement stretchType="RelativeToBandHeight" x="60" y="0" width="217" height="17" uuid="0afdce9b-710f-41e3-b271-ca4e828c2be4"/>
                <textElement verticalAlignment="Middle">
                    <font fontName="SansSerif" size="11"/>
                </textElement>
                <textFieldExpression><![CDATA[$F{text1}]]></textFieldExpression>
            </textField>
            <textField isStretchWithOverflow="true" pattern="">
                <reportElement stretchType="RelativeToBandHeight" x="282" y="0" width="134" height="17" uuid="5e325968-5b1f-44f1-a326-89cc52620b6c"/>
                <textElement verticalAlignment="Middle">
                    <font size="11"/>
                </textElement>
                <textFieldExpression><![CDATA[$F{text2}]]></textFieldExpression>
            </textField>
        </band>
    </detail>
</jasperReport>

RESULT


Answer:

Place the report 3/spRows.jrxml subreport element in the detail band of the report 2/spWeek.jrxml report.

You now have it the header of a group with no group expression, and such a header only prints once in the report.

Question:

I have a sample jasper report, with only a table and a chart in it. While my table fills with data, my chart does not even if I use the same JRBeanCollectionDataSource.

I pass the data to JasperReports as parameter as shown below;

    // Parameters for report
    Map<String, Object> params = new HashMap<>();
    List<AccountRate> accountRates = getAccountRates(accountInfo);
    params.put("accountRateList", new JRBeanCollectionDataSource(accountRates));

And this is how I use parameter as datasource both for the table and the chart;

<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="ChartSample" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="2dd48b15-239b-403e-9616-b740c6c8adea">
<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="dsAccountRate" uuid="21e57a6c-f945-4fd9-abb4-1bae216e731f">
    <queryString>
        <![CDATA[]]>
    </queryString>
    <field name="tradeTypeName" class="java.lang.String"/>
    <field name="totalRate" class="java.math.BigDecimal"/>
</subDataset>
<parameter name="accountRateList" class="net.sf.jasperreports.engine.data.JRBeanCollectionDataSource"/>
<queryString>
    <![CDATA[]]>
</queryString>
<background>
    <band splitType="Stretch"/>
</background>
<title>
    <band height="402" splitType="Stretch">
        <staticText>
            <reportElement x="300" y="30" width="230" height="50" uuid="036cf83b-fbe6-4f7f-a250-d60d71422b02"/>
            <textElement textAlignment="Center" verticalAlignment="Middle">
                <font size="20" isBold="true"/>
            </textElement>
            <text><![CDATA[Sample Chart]]></text>
        </staticText>
        <componentElement>
            <reportElement x="10" y="100" width="197" height="59" uuid="cc6ef81b-44a9-4635-a7f7-51d124b98453">
                <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">
                <datasetRun subDataset="dsAccountRate" uuid="8c2d1341-9ebb-4b85-9a32-5b75aa72655b">
                    <dataSourceExpression><![CDATA[$P{accountRateList}]]></dataSourceExpression>
                </datasetRun>
                <jr:column width="100" uuid="c3070f47-bc37-4467-b357-2f8bba72db23">
                    <jr:columnHeader style="Table_CH" height="30">
                        <staticText>
                            <reportElement x="0" y="0" width="100" height="30" uuid="e28b47a7-62b6-4aef-b255-5eeb9898ee1d"/>
                            <textElement textAlignment="Center" verticalAlignment="Middle">
                                <font isBold="true"/>
                            </textElement>
                            <text><![CDATA[tradeTypeName]]></text>
                        </staticText>
                    </jr:columnHeader>
                    <jr:detailCell style="Table_TD" height="30">
                        <textField>
                            <reportElement x="0" y="0" width="100" height="30" uuid="d3400acf-28a5-47df-9d60-a653dd60f249"/>
                            <textElement textAlignment="Center" verticalAlignment="Middle"/>
                            <textFieldExpression><![CDATA[$F{tradeTypeName}]]></textFieldExpression>
                        </textField>
                    </jr:detailCell>
                </jr:column>
                <jr:column width="100" uuid="6fc447e1-4817-4e13-9eb0-e011bb70921a">
                    <jr:columnHeader style="Table_CH" height="30">
                        <staticText>
                            <reportElement x="0" y="0" width="100" height="30" uuid="91e14b19-e4d8-4774-a1a6-de8468962343"/>
                            <textElement textAlignment="Center" verticalAlignment="Middle">
                                <font isBold="true"/>
                            </textElement>
                            <text><![CDATA[totalRate]]></text>
                        </staticText>
                    </jr:columnHeader>
                    <jr:detailCell style="Table_TD" height="30">
                        <textField>
                            <reportElement x="0" y="0" width="100" height="30" uuid="0d51e863-95ec-42c3-bbd4-0f85f953284e"/>
                            <textElement textAlignment="Right" verticalAlignment="Middle">
                                <paragraph rightIndent="5"/>
                            </textElement>
                            <textFieldExpression><![CDATA[$F{totalRate}]]></textFieldExpression>
                        </textField>
                    </jr:detailCell>
                </jr:column>
            </jr:table>
        </componentElement>
        <barChart>
            <chart evaluationTime="Report">
                <reportElement x="230" y="100" width="320" height="200" uuid="670a0f51-a0c2-4214-bbc5-7317b79ed82a"/>
                <chartTitle/>
                <chartSubtitle/>
                <chartLegend/>
            </chart>
            <categoryDataset>
                <dataset>
                    <datasetRun subDataset="dsAccountRate" uuid="ef1e7b48-1f55-415e-995b-36edfc85cd1f">
                        <dataSourceExpression><![CDATA[$P{accountRateList}]]></dataSourceExpression>
                    </datasetRun>
                </dataset>
                <categorySeries>
                    <seriesExpression><![CDATA[$F{tradeTypeName}]]></seriesExpression>
                    <categoryExpression><![CDATA[$F{tradeTypeName}]]></categoryExpression>
                    <valueExpression><![CDATA[$F{totalRate}.doubleValue()]]></valueExpression>
                </categorySeries>
            </categoryDataset>
            <barPlot>
                <plot/>
                <itemLabel/>
                <categoryAxisFormat>
                    <axisFormat labelColor="#000000" tickLabelColor="#000000" axisLineColor="#000000"/>
                </categoryAxisFormat>
                <valueAxisFormat>
                    <axisFormat labelColor="#000000" tickLabelColor="#000000" axisLineColor="#000000"/>
                </valueAxisFormat>
            </barPlot>
        </barChart>
    </band>
</title>

I do not know what the problem is, why I can fill table but not chart?

Any help?


Answer:

please defined the sub report's data source as a field,

<field name="accountRateList" class="java.util.ArrayList">
    <fieldDescription><![CDATA[accountRateList}]]></fieldDescription>
</field>

then pass it to the sub report

<dataSourceExpression><![CDATA[new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($F{accountRateList})]]></dataSourceExpression>

Question:

I would like to have a report where shows my Orders classified, grouped, by Currency, and by Country.

It should look like this:

EUR
 - Germany
   - (only orders with EUR as currency and order made in Germany)
 - France
   - (only orders with EUR as currency and order made in France)

US
  - USA
   - (only orders with US as currency and order made in USA)

So, I thought creating a master report, which will have 2 subreports:

master
  - subreport grouping orders by currency
    - subreport grouping orders by country
      - subreport listing the orders

So I did it like this:

master.jrxml

<?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 6.1.0.final using JasperReports Library version 6.1.0  -->
<!-- 2016-11-18T18:37:36 -->
<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="master" pageWidth="595" pageHeight="842" columnWidth="515" leftMargin="40" rightMargin="40" topMargin="50" bottomMargin="50" uuid="bbe115b5-a5a0-4b39-9b73-7092dc59ab6d">
    <property name="com.jaspersoft.studio.data.defaultdataadapter" value="Demo JSON Data Adapter "/>
    <property name="net.sf.jasperreports.json.source" value="/home/vasi/git/valter/reports/Demo/data/northwind.json"/>
    <style name="Sans_Normal" isDefault="true" fontName="DejaVu Sans" fontSize="12" isBold="false" isItalic="false" isUnderline="false" isStrikeThrough="false"/>
    <style name="Sans_Normal_8" style="Sans_Normal" fontSize="8"/>
    <style name="Sans_Bold" fontName="DejaVu Sans" fontSize="12" isBold="true" isItalic="false" isUnderline="false" isStrikeThrough="false"/>
    <style name="Sans_Bold_8" style="Sans_Bold" fontSize="8"/>
    <queryString language="json">
        <![CDATA[Northwind]]>
    </queryString>
    <field name="Customers" class="java.lang.String">
        <fieldDescription><![CDATA[Customers]]></fieldDescription>
    </field>
    <field name="Orders" class="java.lang.String">
        <fieldDescription><![CDATA[Orders]]></fieldDescription>
    </field>
    <title>
        <band height="50">
            <line>
                <reportElement x="0" y="0" width="515" height="1" uuid="fc148b4e-50df-4a12-aa14-8505a4cfa6e1"/>
            </line>
            <staticText>
                <reportElement style="Sans_Normal" x="0" y="10" width="515" height="30" uuid="5bf7651c-cd6b-4eaf-b65a-1413d60faab0"/>
                <textElement textAlignment="Center">
                    <font size="22"/>
                </textElement>
                <text><![CDATA[Orders sorted by currency and country]]></text>
            </staticText>
        </band>
    </title>
    <detail>
        <band height="70">
            <subreport isUsingCache="true">
                <reportElement x="0" y="0" width="515" height="70" uuid="ebd4e147-b294-4367-a072-dc1954980232"/>
                <subreportParameter name="REPORT_DATA_SOURCE">
                    <subreportParameterExpression><![CDATA[((net.sf.jasperreports.engine.data.JsonDataSource)$P{REPORT_DATA_SOURCE}).subDataSource("Orders")]]></subreportParameterExpression>
                </subreportParameter>
                <subreportExpression><![CDATA["reports/orders/subreport/currency.jasper"]]></subreportExpression>
            </subreport>
        </band>
    </detail>
</jasperReport>

subreport/currency.jrxml

    <?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 6.1.0.final using JasperReports Library version 6.1.0  -->
<!-- 2016-11-18T18:38:23 -->
<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="currency" pageWidth="515" pageHeight="742" columnWidth="515" leftMargin="0" rightMargin="0" topMargin="0" bottomMargin="0" uuid="bbe115b5-a5a0-4b39-9b73-7092dc59ab6d">
    <style name="Sans_Normal" isDefault="true" fontName="DejaVu Sans" fontSize="12" isBold="false" isItalic="false" isUnderline="false" isStrikeThrough="false"/>
    <style name="Sans_Normal_8" style="Sans_Normal" fontSize="8"/>
    <style name="Sans_Bold" fontName="DejaVu Sans" fontSize="12" isBold="true" isItalic="false" isUnderline="false" isStrikeThrough="false"/>
    <style name="Sans_Bold_8" style="Sans_Bold" fontSize="8"/>
    <field name="Currency" class="java.lang.String">
        <property name="net.sf.jasperreports.json.field.expression" value="Currency"/>
    </field>
    <sortField name="Currency"/>
    <group name="CurrencyGroup" isReprintHeaderOnEachPage="true">
        <groupExpression><![CDATA[$F{Currency}]]></groupExpression>
        <groupHeader>
            <band height="21">
                <textField>
                    <reportElement style="Sans_Bold" x="5" y="5" width="100" height="15" isPrintWhenDetailOverflows="true" uuid="0aaeed6e-7ba1-4ab9-be59-d6ca702995fc"/>
                    <textFieldExpression><![CDATA[$F{Currency}]]></textFieldExpression>
                </textField>
                <line>
                    <reportElement x="0" y="20" width="515" height="1" isPrintWhenDetailOverflows="true" uuid="6d76c22c-329f-4e77-a886-8580d3cb6bc1"/>
                </line>
            </band>
        </groupHeader>
        <groupFooter>
            <band height="31"/>
        </groupFooter>
    </group>
    <pageHeader>
        <band height="21">
            <staticText>
                <reportElement style="Sans_Bold" mode="Opaque" x="0" y="5" width="515" height="15" forecolor="#FFFFFF" backcolor="#333333" uuid="da0f1cad-f552-424b-bf19-b41cabbfa4ac"/>
                <text><![CDATA[Currency]]></text>
            </staticText>
        </band>
    </pageHeader>
    <detail>
        <band height="60">
            <subreport>
                <reportElement x="10" y="10" width="490" height="40" uuid="d181a0e1-1a31-4723-abe7-8f2f3dc09bce"/>
                <subreportParameter name="REPORT_DATA_SOURCE">
                    <subreportParameterExpression><![CDATA[((net.sf.jasperreports.engine.data.JsonDataSource)$P{REPORT_DATA_SOURCE}).subDataSource()]]></subreportParameterExpression>
                </subreportParameter>
                <subreportExpression><![CDATA["reports/orders/subreport/subreport/countries.jasper"]]></subreportExpression>
            </subreport>
        </band>
    </detail>
</jasperReport>

However, I don't know how to pass my datasource from my subreport to my subreport. From master report to my subreport it was okay, but I'm stuck with this exception:

net.sf.jasperreports.engine.JRException: net.sf.jasperreports.engine.JRRuntimeException: net.sf.jasperreports.engine.fill.JRExpressionEvalException: Error evaluating expression for source text: ((net.sf.jasperreports.engine.data.JsonDataSource)$P{REPORT_DATA_SOURCE}).subDataSource()
    at com.jaspersoft.studio.editor.preview.view.control.ReportControler.fillReport(ReportControler.java:506)
    at com.jaspersoft.studio.editor.preview.view.control.ReportControler.access$20(ReportControler.java:481)
    at com.jaspersoft.studio.editor.preview.view.control.ReportControler$5.run(ReportControler.java:362)
    at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54)
Caused by: net.sf.jasperreports.engine.JRRuntimeException: net.sf.jasperreports.engine.fill.JRExpressionEvalException: Error evaluating expression for source text: ((net.sf.jasperreports.engine.data.JsonDataSource)$P{REPORT_DATA_SOURCE}).subDataSource()
    at net.sf.jasperreports.engine.fill.JRFillSubreport.prepare(JRFillSubreport.java:872)
    at net.sf.jasperreports.engine.fill.JRFillElementContainer.prepareElements(JRFillElementContainer.java:330)
    at net.sf.jasperreports.engine.fill.JRFillBand.fill(JRFillBand.java:382)
    at net.sf.jasperreports.engine.fill.JRFillBand.fill(JRFillBand.java:357)
    at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillColumnBand(JRVerticalFiller.java:2031)
    at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillDetail(JRVerticalFiller.java:755)
    at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReportStart(JRVerticalFiller.java:262)
    at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReport(JRVerticalFiller.java:122)
    at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:551)
    at net.sf.jasperreports.engine.fill.BaseFillHandle$ReportFill.run(BaseFillHandle.java:119)
    at java.lang.Thread.run(Unknown Source)
Caused by: net.sf.jasperreports.engine.fill.JRExpressionEvalException: Error evaluating expression for source text: ((net.sf.jasperreports.engine.data.JsonDataSource)$P{REPORT_DATA_SOURCE}).subDataSource()
    at net.sf.jasperreports.engine.fill.JREvaluator.evaluate(JREvaluator.java:264)
    at net.sf.jasperreports.engine.fill.JRCalculator.evaluate(JRCalculator.java:610)
    at net.sf.jasperreports.engine.fill.JRCalculator.evaluate(JRCalculator.java:578)
    at net.sf.jasperreports.engine.fill.JRFillSubreport.getParameterValues(JRFillSubreport.java:680)
    at net.sf.jasperreports.engine.fill.JRFillSubreport.evaluateParameterValues(JRFillSubreport.java:478)
    at net.sf.jasperreports.engine.fill.JRFillSubreport.evaluateSubreport(JRFillSubreport.java:458)
    at net.sf.jasperreports.engine.fill.JRFillSubreport.evaluate(JRFillSubreport.java:345)
    at net.sf.jasperreports.engine.fill.JRFillElementContainer.evaluate(JRFillElementContainer.java:258)
    at net.sf.jasperreports.engine.fill.JRFillBand.evaluate(JRFillBand.java:454)
    at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillColumnBand(JRVerticalFiller.java:2029)
    at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillDetail(JRVerticalFiller.java:755)
    at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReportStart(JRVerticalFiller.java:262)
    at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReport(JRVerticalFiller.java:122)
    at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:551)
    at net.sf.jasperreports.engine.fill.JRFillSubreport.fillSubreport(JRFillSubreport.java:736)
    at net.sf.jasperreports.engine.fill.JRSubreportRunnable.run(JRSubreportRunnable.java:58)
    at net.sf.jasperreports.engine.fill.AbstractThreadSubreportRunner.run(AbstractThreadSubreportRunner.java:216)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    ... 1 more
Caused by: java.lang.ClassCastException: net.sf.jasperreports.engine.fill.SortedDataSource cannot be cast to net.sf.jasperreports.engine.data.JsonDataSource
    at currency_1479490219429_385194.evaluate(currency_1479490219429_385194:195)
    at net.sf.jasperreports.engine.fill.JREvaluator.evaluate(JREvaluator.java:251)
    ... 19 more

I've created a branch only for this question. This is my json data source.

I've also tried this suggestion, however, I don't know how to get my data source as parameter on my subreport, and how to re-send it again. :(

Any ideas, or sugesstions, would be very appreciated!


Answer:

For those who might have the same issue. The solution was easier than I thought originally. It was necessary to create a second group only, based on the field that I wanted to group.

    <?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 6.3.1.final using JasperReports Library version 6.3.1  -->
<!-- 2016-11-21T16:51:47 -->
<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="currency" pageWidth="515" pageHeight="742" columnWidth="515" leftMargin="0" rightMargin="0" topMargin="0" bottomMargin="0" uuid="bbe115b5-a5a0-4b39-9b73-7092dc59ab6d">
    <style name="Sans_Normal" isDefault="true" fontName="DejaVu Sans" fontSize="12" isBold="false" isItalic="false" isUnderline="false" isStrikeThrough="false"/>
    <style name="Sans_Normal_8" style="Sans_Normal" fontSize="8"/>
    <style name="Sans_Bold" fontName="DejaVu Sans" fontSize="12" isBold="true" isItalic="false" isUnderline="false" isStrikeThrough="false"/>
    <style name="Sans_Bold_8" style="Sans_Bold" fontSize="8"/>
    <queryString>
        <![CDATA[]]>
    </queryString>
    <field name="Currency" class="java.lang.String">
        <property name="net.sf.jasperreports.json.field.expression" value="Currency"/>
    </field>
    <field name="ShipCountry" class="java.lang.String">
        <property name="net.sf.jasperreports.json.field.expression" value="ShipCountry"/>
    </field>
    <field name="Id" class="java.lang.String">
        <property name="net.sf.jasperreports.json.field.expression" value="OrderID"/>
    </field>
    <field name="OrderDate" class="java.lang.String">
        <property name="net.sf.jasperreports.json.field.expression" value="OrderDate"/>
    </field>
    <field name="ShipCity" class="java.lang.String">
        <property name="net.sf.jasperreports.json.field.expression" value="ShipCity"/>
    </field>
    <field name="Freight" class="java.lang.Float">
        <property name="net.sf.jasperreports.json.field.expression" value="Freight"/>
    </field>
    <group name="CurrencyGroup" isReprintHeaderOnEachPage="true">
        <groupExpression><![CDATA[$F{Currency}]]></groupExpression>
        <groupHeader>
            <band height="26">
                <textField>
                    <reportElement style="Sans_Bold" x="5" y="6" width="124" height="15" isPrintWhenDetailOverflows="true" uuid="0aaeed6e-7ba1-4ab9-be59-d6ca702995fc"/>
                    <textElement>
                        <font size="10"/>
                    </textElement>
                    <textFieldExpression><![CDATA[$F{Currency}]]></textFieldExpression>
                </textField>
                <line>
                    <reportElement x="0" y="20" width="515" height="1" isPrintWhenDetailOverflows="true" uuid="6d76c22c-329f-4e77-a886-8580d3cb6bc1"/>
                </line>
                <line>
                    <reportElement x="1" y="6" width="515" height="1" isPrintWhenDetailOverflows="true" uuid="533d7e0a-969c-44c7-8114-eabe53fe2bde"/>
                </line>
            </band>
        </groupHeader>
    </group>
    <group name="ShipCountryGroup" isReprintHeaderOnEachPage="true">
        <groupExpression><![CDATA[$F{ShipCountry}]]></groupExpression>
        <groupHeader>
            <band height="20">
                <textField>
                    <reportElement style="Sans_Bold" x="22" y="3" width="124" height="15" isPrintWhenDetailOverflows="true" uuid="03b06cb9-2565-47fa-845a-9585c2dd2056"/>
                    <textElement>
                        <font size="10"/>
                    </textElement>
                    <textFieldExpression><![CDATA[$F{ShipCountry}]]></textFieldExpression>
                </textField>
            </band>
        </groupHeader>
    </group>
    <pageHeader>
        <band height="21">
            <staticText>
                <reportElement style="Sans_Bold" mode="Opaque" x="0" y="5" width="515" height="15" forecolor="#FFFFFF" backcolor="#333333" uuid="da0f1cad-f552-424b-bf19-b41cabbfa4ac"/>
                <text><![CDATA[Currency]]></text>
            </staticText>
        </band>
    </pageHeader>
    <detail>
        <band height="50">
            <textField>
                <reportElement style="Sans_Normal_8" x="0" y="2" width="51" height="10" uuid="ec54687d-3c95-4647-9db5-fa71a6e81009"/>
                <textElement textAlignment="Right"/>
                <textFieldExpression><![CDATA[$F{Id}]]></textFieldExpression>
            </textField>
            <textField isStretchWithOverflow="true" pattern="yyyy, MMM dd">
                <reportElement style="Sans_Normal_8" positionType="Float" x="54" y="2" width="87" height="10" uuid="a112ba7b-c321-467c-91ec-ffb513c23338"/>
                <textElement textAlignment="Center"/>
                <textFieldExpression><![CDATA[$F{OrderDate}]]></textFieldExpression>
            </textField>
            <textField isStretchWithOverflow="true">
                <reportElement style="Sans_Normal_8" positionType="Float" x="146" y="2" width="108" height="10" uuid="6a61edb3-239e-4791-a046-a6459343ac07"/>
                <textFieldExpression><![CDATA[$F{ShipCity}]]></textFieldExpression>
            </textField>
            <textField isStretchWithOverflow="true" pattern="¤ #,##0.00">
                <reportElement style="Sans_Normal_8" positionType="Float" x="259" y="2" width="92" height="10" uuid="61a8a117-6a43-46a7-9b96-10c5beb578ab"/>
                <textElement textAlignment="Right"/>
                <textFieldExpression><![CDATA[$F{Freight}]]></textFieldExpression>
            </textField>
        </band>
    </detail>
</jasperReport>

I've created a branch for this answer. I hope it helps! :)

Question:

I am trying to generate report with SQL Query:

SELECT brand.id,brand.brand,model.model FROM brand INNER JOIN model ON brand.id=model.id AND model.id=$P{ID}

It is taking the user input from JavaFX TextField. The Model.id will be replaced with single Integer, say 1 and it should output only one row! But when I am passing this parameters to the JasperReports's report, It is printing all rows available in the table.

The Java Code:

@FXML
public TextField one;

public void click(ActionEvent event) throws JRException, SQLException, ClassNotFoundException, IllegalAccessException, UnsupportedLookAndFeelException, InstantiationException {
    String reportSrcFile = "/home/sample/learn.jrxml";

    // First, compile jrxml file.
    JasperReport jasperReport1 = JasperCompileManager.compileReport(reportSrcFile);

    Connection conn = SqliConnect.getMySQLConnection();

    // Parameters for report
    int two = Integer.parseInt(one.getText());
    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("ID",one.getText());//The Exact Parameter name is "ID" in the jrxml file.

    JasperPrint print = JasperFillManager.fillReport(jasperReport1,
            parameters, conn);

    JasperViewer jv = new JasperViewer(print);
    jv.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jv.setTitle("Test Report");

    jv.setVisible(true);
}

Report's template:

<subDataset name="Dataset1" uuid="2691431f-5c6f-403f-94cc-829c17ef1636">
    <queryString>
        <![CDATA[SELECT brand.id,brand.brand,model.model FROM brand INNER JOIN model]]>
    </queryString>
    <field name="id" class="java.lang.Integer"/>
    <field name="brand" class="java.lang.String"/>
    <field name="model" class="java.lang.String"/>
</subDataset>
<parameter name="ID" class="java.lang.String">
    <defaultValueExpression><![CDATA[$P{REPORT_CONTEXT}.getId()]]></defaultValueExpression>
</parameter>
<queryString>
    <![CDATA[SELECT brand.id,brand.brand,model.model FROM brand INNER JOIN model ON brand.id=model.id AND model.id=$P{ID}]]>
</queryString>
<field name="id" class="java.lang.Integer"/>
<field name="brand" class="java.lang.String"/>
<field name="model" class="java.lang.String"/>
<title>
    <band height="79" splitType="Stretch">
        <textField>
            <reportElement x="11" y="16" width="100" height="30" uuid="d1485589-a4cf-4ab9-b896-0ef480beced4"/>
            <textFieldExpression><![CDATA[$P{ID}]]></textFieldExpression>
        </textField>
    </band>
</title>
<detail>
    <band height="250" splitType="Stretch">
        <componentElement>
            <reportElement x="160" y="50" width="200" height="200" uuid="e199bd58-8408-4711-85d5-ba76db9691b7">
                <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">
                <datasetRun subDataset="Dataset1" uuid="7fecdfe6-bed4-433a-97f8-43cc6347c660">
                    <connectionExpression><![CDATA[$P{REPORT_CONNECTION}]]></connectionExpression>
                </datasetRun>
                <jr:column width="66" uuid="9a6b765f-b6d4-4753-909e-dd091b296654">
                    <jr:columnHeader style="Table_CH" height="30">
                        <staticText>
                            <reportElement x="0" y="0" width="66" height="30" uuid="7e644d1c-a893-49df-a18a-bf788eb6b92a"/>
                            <text><![CDATA[id]]></text>
                        </staticText>
                    </jr:columnHeader>
                    <jr:columnFooter style="Table_CH" height="30"/>
                    <jr:detailCell style="Table_TD" height="30">
                        <textField>
                            <reportElement x="0" y="0" width="66" height="30" uuid="848a53bf-2b2e-46df-a7aa-26fc0b897c85"/>
                            <textFieldExpression><![CDATA[$F{id}]]></textFieldExpression>
                        </textField>
                    </jr:detailCell>
                </jr:column>
                <jr:column width="66" uuid="514580a5-f09c-43d1-952e-d4769c2e4686">
                    <jr:columnHeader style="Table_CH" height="30">
                        <staticText>
                            <reportElement x="0" y="0" width="66" height="30" uuid="c01152e9-1547-472b-946e-92011c02bc94"/>
                            <text><![CDATA[brand]]></text>
                        </staticText>
                    </jr:columnHeader>
                    <jr:columnFooter style="Table_CH" height="30"/>
                    <jr:detailCell style="Table_TD" height="30">
                        <textField>
                            <reportElement x="0" y="0" width="66" height="30" uuid="98c84ae5-b289-459a-b34b-a9becf43b9ce"/>
                            <textFieldExpression><![CDATA[$F{brand}]]></textFieldExpression>
                        </textField>
                    </jr:detailCell>
                </jr:column>
                <jr:column width="66" uuid="5c1d2026-45bc-4ec8-8be4-c444e47d093d">
                    <jr:columnHeader style="Table_CH" height="30">
                        <staticText>
                            <reportElement x="0" y="0" width="66" height="30" uuid="81f76de4-a68b-41c3-a2e8-bbaa625b71be"/>
                            <text><![CDATA[model]]></text>
                        </staticText>
                    </jr:columnHeader>
                    <jr:columnFooter style="Table_CH" height="30"/>
                    <jr:detailCell style="Table_TD" height="30">
                        <textField>
                            <reportElement x="0" y="0" width="66" height="30" uuid="d69c690e-05a4-453a-93ea-9061523975ad"/>
                            <textFieldExpression><![CDATA[$F{model}]]></textFieldExpression>
                        </textField>
                    </jr:detailCell>
                </jr:column>
            </jr:table>
        </componentElement>
    </band>
</detail>

What is the right way to do it?

Update: I have added the parameter for Datasources:

<subDataset name="Dataset1" uuid="2691431f-5c6f-403f-94cc-829c17ef1636">
    <property name="com.jaspersoft.studio.data.sql.tables" value=""/>
    <property name="com.jaspersoft.studio.data.defaultdataadapter" value="Learn"/>
    <parameter name="ID" class="java.lang.String"/>
    <queryString>
        <![CDATA[SELECT brand.id,brand.brand,model.model FROM brand INNER JOIN model ON brand.id=model.id AND model.id=$P{ID}]]>
    </queryString>
    <field name="id" class="java.lang.Integer"/>
    <field name="brand" class="java.lang.String"/>
    <field name="model" class="java.lang.String"/>
</subDataset>

But now it is generating blank report.


Answer:

The table component in your report uses the 'Dataset1' subdataset, which has no ID parameter defined and contains only a static query. You'll need to declare the ID parameter in the subdataset too, and use it in the query. I hope this helps, Sanda

PS: Please see the edited Raw Paste Data here: http://pastebin.com/ZMjn4jtP

Question:

I need to pass just one object to my jasper report page.When I send list it works but when I send one object like following code it doesnt work. How I can do it ?

Code of report maker method :

// generatePdfReport
@RequestMapping(method = RequestMethod.GET, value = "/report/{id}")
public ModelAndView generatePdfReport(@PathVariable(value = "id") Long id, ModelAndView modelAndView)
        throws JRException {

    LOG.info("--------------generate PDF report----------");

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

    java.util.List<Node> nodeList = new ArrayList<Node>();
    JRDataSource JRdataSource = new JRBeanCollectionDataSource(nodeList);

    Node node = nodeService.getOne(id);
    nodeList.add(node);
    parameterMap.put("datasource", JRdataSource);

    // pdfReport bean has ben declared in the spring configuration
    modelAndView = new ModelAndView("pdfReport", parameterMap);

    return modelAndView;

}

Answer:

I have solved my problem with following codes,thanks to all :

// generatePdfReport single node
@RequestMapping(method = RequestMethod.GET, value = "/report/{id}")
public ModelAndView generatePdfReport(@PathVariable(value = "id") Long id, ModelAndView modelAndView)
        throws JRException {

    LOG.info("--------------generate PDF report----------");

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

    java.util.List<Node> nodeList = new ArrayList<Node>();
    nodeList.add(nodeService.getOne(id));

    JRDataSource JRdataSource = new JRBeanCollectionDataSource(nodeList);

    parameterMap.put("datasource", JRdataSource);

    // pdfReport bean has ben declared in the spring configuration
    modelAndView = new ModelAndView("nodesReport_PDF", parameterMap);

    return modelAndView;

}

Question:

I am trying to create a simple Jasper report with 1 Table which should be populated by java code using JRResultSetDataSource object. However, I am not able to pass the values to the Table component.

I am not looking for Parameter list or JRBeanCollectionDataSource as a solution.

My report jrxml:

<?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 6.3.1.final using JasperReports Library version 6.3.1  -->
<!-- 2017-03-27T17:04:35 -->
<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="tab1" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="8a63304f-05d6-485c-82e7-5591159f68fb">
    <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="Empty Dataset1" uuid="be9c1aa9-031c-4232-a9f2-cdcb0a5bd17d">
        <field name="MONTH" class="java.lang.Integer"/>
        <field name="YEAR" class="java.lang.Integer"/>
        <field name="COUNT" class="java.lang.Integer"/>
    </subDataset>
    <queryString>
        <![CDATA[]]>
    </queryString>
    <field name="MONTH" class="java.lang.Integer"/>
    <field name="YEAR" class="java.lang.Integer"/>
    <field name="COUNT" class="java.lang.Integer"/>
    <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="360" splitType="Stretch">
            <componentElement>
                <reportElement x="0" y="0" width="200" height="200" uuid="684e26d7-94cf-49cc-874d-104e29444537">
                    <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=""/>
                </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="Blank">
                    <datasetRun subDataset="Empty Dataset1" uuid="0baea769-1082-4618-9eee-520f59145c07">
                        <connectionExpression><![CDATA[]]></connectionExpression>
                    </datasetRun>
                    <jr:column width="60" uuid="ba2a25da-f872-4a99-8703-9e6e15fc988a">
                        <property name="com.jaspersoft.studio.components.table.model.column.name" value="Column1"/>
                        <jr:tableHeader style="Table_TH" height="30" rowSpan="1">
                            <staticText>
                                <reportElement x="0" y="0" width="60" height="30" uuid="a4bbf819-044c-47ff-bff0-627859b51444"/>
                                <text><![CDATA[MONTH]]></text>
                            </staticText>
                        </jr:tableHeader>
                        <jr:tableFooter style="Table_TH" height="30" rowSpan="1"/>
                        <jr:columnHeader style="Table_CH" height="30" rowSpan="1"/>
                        <jr:columnFooter style="Table_CH" height="30" rowSpan="1"/>
                        <jr:detailCell style="Table_TD" height="30">
                            <textField>
                                <reportElement x="0" y="0" width="60" height="30" uuid="91cd6b4f-f09b-4c08-8fe7-0645468bd1cc"/>
                                <textFieldExpression><![CDATA[$F{MONTH}]]></textFieldExpression>
                            </textField>
                        </jr:detailCell>
                    </jr:column>
                    <jr:column width="70" uuid="80e850bb-b112-4b53-aa44-f9fca76710b4">
                        <property name="com.jaspersoft.studio.components.table.model.column.name" value="Column2"/>
                        <jr:tableHeader style="Table_TH" height="30" rowSpan="1">
                            <staticText>
                                <reportElement x="0" y="0" width="70" height="30" uuid="86e7d6fb-ee79-4c11-8e3d-99b59832b978"/>
                                <text><![CDATA[YEAR]]></text>
                            </staticText>
                        </jr:tableHeader>
                        <jr:tableFooter style="Table_TH" height="30" rowSpan="1"/>
                        <jr:columnHeader style="Table_CH" height="30" rowSpan="1"/>
                        <jr:columnFooter style="Table_CH" height="30" rowSpan="1"/>
                        <jr:detailCell style="Table_TD" height="30">
                            <textField>
                                <reportElement x="0" y="0" width="70" height="30" uuid="39a27fc4-79d6-4ff8-aae0-ff67ac43bd09"/>
                                <textFieldExpression><![CDATA[$F{YEAR}]]></textFieldExpression>
                            </textField>
                        </jr:detailCell>
                    </jr:column>
                    <jr:column width="70" uuid="57949a99-6a7c-4911-b01c-1db16d3963bd">
                        <property name="com.jaspersoft.studio.components.table.model.column.name" value="Column3"/>
                        <jr:tableHeader style="Table_TH" height="30" rowSpan="1">
                            <staticText>
                                <reportElement x="0" y="0" width="70" height="30" uuid="cddf1b17-b113-4cc5-a95c-395f59d96181"/>
                                <text><![CDATA[COUNT]]></text>
                            </staticText>
                        </jr:tableHeader>
                        <jr:tableFooter style="Table_TH" height="30" rowSpan="1"/>
                        <jr:columnHeader style="Table_CH" height="30" rowSpan="1"/>
                        <jr:columnFooter style="Table_CH" height="30" rowSpan="1"/>
                        <jr:detailCell style="Table_TD" height="30">
                            <textField>
                                <reportElement x="0" y="0" width="70" height="30" uuid="fefdadb9-d47e-45b5-9aa4-346c53ce0441"/>
                                <textFieldExpression><![CDATA[$F{COUNT}]]></textFieldExpression>
                            </textField>
                        </jr:detailCell>
                    </jr:column>
                </jr:table>
            </componentElement>
        </band>
        <band height="50"/>
    </detail>
    <columnFooter>
        <band height="45" splitType="Stretch"/>
    </columnFooter>
    <pageFooter>
        <band height="54" splitType="Stretch"/>
    </pageFooter>
    <summary>
        <band height="42" splitType="Stretch"/>
    </summary>
</jasperReport>

My Java Code snippet:

resultSet = statement.executeQuery(query);

if(resultSet != null && reportStream !=null)
{               
JRResultSetDataSource jrr = new JRResultSetDataSource(resultSet);
JasperRunManager.runReportToPdfStream(reportStream, servletOutputStream,new HashMap(),jrr);
}

So far I am able to list the data on the report if I dont use the Table component, instead just put the Fields on the report. But I am not able to find a way to push the data inside the Table component, as it has a seperate datasource and a corresponding Fields component.

Is this way of populating table data using a datasource even possible? Can someone give me an example, or point me to an example.

Thanks, Vishalendu


Answer:

You need to do something like this:

In JRXML

<subDataset name="Empty Dataset1" ...>
...
</subDataset>
<parameter name="TableDataSource" class="net.sf.jasperreports.engine.JRDataSource"/>
...
<jr:table ...>
    <datasetRun subDataset="Empty Dataset1" ...>
        <dataSourceExpression><![CDATA[$P{TableDataSource}]]></dataSourceExpression>
    </datasetRun>
...

In Java

JRResultSetDataSource jrr = new JRResultSetDataSource(resultSet);
Map params = new HashMap();
params.put("TableDataSource", jrr);
JasperRunManager.runReportToPdfStream(reportStream, servletOutputStream, params, new JREmptyDataSource());

Question:

I am using Jasper Report with Pie charts and push the data using java code. Here is my java code

data1, data2, data3 are the objects of Data.java have some fields and its value.

ArrayList<Data> selectedDataList = new ArrayList<Data>();
selectedDataList.add(data1);
selectedDataList.add(data2);
selectedDataList.add(data3);

      URL in = CampaignReport.class.getResource("Report.jrxml");
      // Compile jrxml file.
      JasperReport jasperReport = JasperCompileManager.compileReport(in.getPath());

      //Parameters for report
      Map<String, Object> parameters = new HashMap<String, Object>();

      // DataSource
      // This is simple example, no database.
      // then using empty datasource.
      JRDataSource dataSource = new JREmptyDataSource();
      JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(selectedDataList);
      parameters.put("ItemDataSource", beanColDataSource);


      JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, beanColDataSource);
      // Make sure the output directory exists.
      File outDir = new File(folderUrl);
      outDir.mkdirs();

     JasperExportManager.exportReportToPdfFile(jasperPrint, fileName);

Here is the code of Report.jrxml

<?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 6.3.1.final using JasperReports Library version 6.3.1  -->
<!-- 2017-01-30T17:53:54 -->
<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="template_Table" pageWidth="842" pageHeight="595" orientation="Landscape" whenNoDataType="NoPages" columnWidth="802" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="1a0aa80b-dc07-4dca-bdbc-aa78eeb0d12b">
    <property name="com.jaspersoft.studio.data.defaultdataadapter" value="One Empty Record"/>
    <property name="com.jaspersoft.studio.unit." value="pixel"/>
    <style name="Row" mode="Transparent" fontName="Calibri" pdfFontName="Times-Roman">
        <conditionalStyle>
            <conditionExpression><![CDATA[$V{REPORT_COUNT}%2 == 0]]></conditionExpression>
            <style mode="Opaque" backcolor="#F0EFEF"/>
        </conditionalStyle>
    </style>
    <style name="Table 1_TH" mode="Opaque" backcolor="#D0EBF7">
        <box>
            <pen lineWidth="0.5" lineColor="#FFFFFF"/>
            <topPen lineWidth="0.5" lineColor="#FFFFFF"/>
            <leftPen lineWidth="0.5" lineColor="#FFFFFF"/>
            <bottomPen lineWidth="0.5" lineColor="#FFFFFF"/>
            <rightPen lineWidth="0.5" lineColor="#FFFFFF"/>
        </box>
    </style>
    <style name="Table 1_CH" mode="Opaque" backcolor="#FAFCFE">
        <box>
            <pen lineWidth="0.5" lineColor="#FFFFFF"/>
            <topPen lineWidth="0.5" lineColor="#FFFFFF"/>
            <leftPen lineWidth="0.5" lineColor="#FFFFFF"/>
            <bottomPen lineWidth="0.5" lineColor="#FFFFFF"/>
            <rightPen lineWidth="0.5" lineColor="#FFFFFF"/>
        </box>
    </style>
    <style name="Table 1_TD" mode="Opaque" backcolor="#FAFCFE">
        <box>
            <pen lineWidth="0.5" lineColor="#FFFFFF"/>
            <topPen lineWidth="0.5" lineColor="#FFFFFF"/>
            <leftPen lineWidth="0.5" lineColor="#FFFFFF"/>
            <bottomPen lineWidth="0.5" lineColor="#FFFFFF"/>
            <rightPen lineWidth="0.5" lineColor="#FFFFFF"/>
        </box>
        <conditionalStyle>
            <conditionExpression><![CDATA[new Boolean($V{REPORT_COUNT}.intValue()%2==0)]]></conditionExpression>
            <style backcolor="#D5E3E2"/>
        </conditionalStyle>
    </style>
    <subDataset name="Dataset1" uuid="7a7c32a6-b47a-4839-afad-3aeaed61363e">
        <queryString>
            <![CDATA[]]>
        </queryString>
        <field name="subject" class="java.lang.String"/>
        <field name="marks" class="java.lang.Integer"/>
    </subDataset>
    <parameter name="ItemDataSource" class="net.sf.jasperreports.engine.data.JRBeanCollectionDataSource"/>
    <field name="subject" class="java.lang.String"/>
    <field name="marks" class="java.lang.Integer"/>
    <group name="Group1">
        <groupExpression><![CDATA[(int)($V{REPORT_COUNT}/15)]]></groupExpression>
    </group>
    <group name="Group2">
        <groupExpression><![CDATA[(int)($V{REPORT_COUNT}/5)]]></groupExpression>
    </group>
    <pageHeader>
        <band splitType="Stretch"/>
    </pageHeader>
    <detail>
        <band height="120" splitType="Stretch">
            <property name="com.jaspersoft.studio.layout" value="com.jaspersoft.studio.editor.layout.FreeLayout"/>
            <componentElement>
                <reportElement stretchType="RelativeToTallestObject" mode="Transparent" x="0" y="0" width="800" height="120" forecolor="#FFFFFF" backcolor="#424242" uuid="7786bb05-503a-4b6a-991a-a7bcf3abad07">
                    <property name="com.jaspersoft.studio.layout" value="com.jaspersoft.studio.editor.layout.grid.JSSGridBagLayout"/>
                    <property name="com.jaspersoft.studio.table.style.table_header" value="Table 1_TH"/>
                    <property name="com.jaspersoft.studio.table.style.column_header" value="Table 1_CH"/>
                    <property name="com.jaspersoft.studio.table.style.detail" value="Table 1_TD"/>
                    <property name="net.sf.jasperreports.export.headertoolbar.table.name" value=""/>
                    <property name="com.jaspersoft.studio.components.autoresize.proportional" value="true"/>
                    <property name="com.jaspersoft.studio.components.autoresize.next" 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">
                    <datasetRun subDataset="Dataset1" uuid="d3e1e03a-2c83-4436-9e50-79518bc3d337">
                        <dataSourceExpression><![CDATA[$P{ItemDataSource}]]></dataSourceExpression>
                    </datasetRun>
                    <jr:column width="52" uuid="dca8961f-ce2d-47ac-879c-b15847d170a9">
                        <property name="com.jaspersoft.studio.components.table.model.column.name" value="Column1"/>
                        <property name="com.jaspersoft.studio.unit.height" value="pixel"/>
                        <property name="com.jaspersoft.studio.unit.width" value="pixel"/>
                        <jr:tableHeader style="Table 1_TH" height="70">
                            <property name="com.jaspersoft.studio.layout" value="com.jaspersoft.studio.editor.layout.VerticalRowLayout"/>
                            <property name="com.jaspersoft.studio.unit.height" value="px"/>
                            <property name="com.jaspersoft.studio.unit.width" value="px"/>
                            <staticText>
                                <reportElement x="0" y="0" width="52" height="70" uuid="f60d1675-6fb6-4569-93ca-de32b3a8e861"/>
                                <box leftPadding="3"/>
                                <textElement textAlignment="Left" verticalAlignment="Middle" markup="html">
                                    <font fontName="Verdana" size="9"/>
                                </textElement>
                                <text><![CDATA[Subject]]></text>
                            </staticText>
                        </jr:tableHeader>
                        <jr:detailCell style="Table 1_TD" height="50">
                            <property name="com.jaspersoft.studio.layout" value="com.jaspersoft.studio.editor.layout.VerticalRowLayout"/>
                            <property name="com.jaspersoft.studio.unit.height" value="px"/>
                            <property name="com.jaspersoft.studio.unit.width" value="px"/>
                            <textField>
                                <reportElement x="0" y="0" width="52" height="50" uuid="f1de366a-b36f-4200-9b1e-7a0009be5373"/>
                                <box leftPadding="6"/>
                                <textElement textAlignment="Left" verticalAlignment="Middle">
                                    <font fontName="Verdana"/>
                                </textElement>
                                <textFieldExpression><![CDATA[$F{subject}]]></textFieldExpression>
                            </textField>
                        </jr:detailCell>
                    </jr:column>

                    <jr:column width="53" uuid="dca8961f-ce2d-47ac-879c-b15847d170a9">
                        <property name="com.jaspersoft.studio.components.table.model.column.name" value="Column1"/>
                        <jr:tableHeader style="Table 1_TH" height="70">
                            <property name="com.jaspersoft.studio.layout" value="com.jaspersoft.studio.editor.layout.FreeLayout"/>
                            <property name="com.jaspersoft.studio.unit.height" value="px"/>
                            <property name="com.jaspersoft.studio.unit.width" value="px"/>
                            <staticText>
                                <reportElement x="0" y="0" width="53" height="70" uuid="f60d1675-6fb6-4569-93ca-de32b3a8e861"/>
                                <box leftPadding="3"/>
                                <textElement textAlignment="Left" verticalAlignment="Middle" markup="html">
                                    <font fontName="Verdana" size="9"/>
                                </textElement>
                                <text><![CDATA[Marks]]></text>
                            </staticText>
                        </jr:tableHeader>
                        <jr:detailCell style="Table 1_TD" height="50">
                            <property name="com.jaspersoft.studio.layout" value="com.jaspersoft.studio.editor.layout.VerticalRowLayout"/>
                            <property name="com.jaspersoft.studio.unit.height" value="px"/>
                            <property name="com.jaspersoft.studio.unit.width" value="px"/>
                            <textField>
                                <reportElement x="0" y="0" width="53" height="50" uuid="f1de366a-b36f-4200-9b1e-7a0009be5373"/>
                                <textElement textAlignment="Center" verticalAlignment="Middle"/>
                                <textFieldExpression><![CDATA[$F{marks}]]></textFieldExpression>
                            </textField>
                        </jr:detailCell>
                    </jr:column>

                </jr:table>
            </componentElement>
        </band>
    </detail>
    <summary>
        <band height="440" splitType="Stretch">
            <pieChart>
                <chart evaluationTime="Report">
                    <reportElement x="10" y="40" width="270" height="300" uuid="08e2ac0f-0059-4037-b77e-521d78434987"/>
                    <chartTitle>
                        <titleExpression><![CDATA["My First JR Pie Chart"]]></titleExpression>
                    </chartTitle>
                    <chartSubtitle/>
                    <chartLegend/>
                </chart>
                <pieDataset>
                    <keyExpression><![CDATA[$F{subject}]]></keyExpression>
                    <valueExpression><![CDATA[$F{marks}]]></valueExpression>
                </pieDataset>
                <piePlot>
                    <plot/>
                    <itemLabel/>
                </piePlot>
            </pieChart>
        </band>
    </summary>
</jasperReport>

Using these code chart is created with data but report (table) is blank does not show data.

What should I do ? Is something wrong in the code.


Answer:

There is a problem of datasource, you are using same datasource for both the entity like table and chart.

So, create two different datasource.

JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(selectedDataList);
      parameters.put("ItemDataSource", beanColDataSource);

JRBeanCollectionDataSource chartColDataSource = new JRBeanCollectionDataSource(selectedDataList);

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

This how you can pass the values to jrmxl. Now both have the data access properly i.e. chart and table.

Question:

In main datasource I have a field "List someDto". And I need to add this field to subreport datasource. Maybe I can use some expression, that will return JRDataSource type?

report.addDetail(subreport(report()
                .addDetail(text(field("text", String.class)))
                .addDetail(image(fieldExpression("image")))
                .setDataSource(----*here i need to add field from main datasource*----)

Answer:

Omg, I just use subDatasourceBeanCollection and replace .setDataSource from the report().setDataSource to subreport(...).setDataSource():

report.addDetail(subreport(report() .addDetail(text(field("text", String.class))) .addDetail(image(fieldExpression("image")))) .setDataSource(subDatasourceBeanCollection("*here my field from main datasource")));