Hot questions for Using JasperReports in eclipse

Question:

so I have developed this program in Java using Eclipse (jdk 1.8.0_74) on Windows 7 which the user can at some point generate a report with data coming from database.

To create this report I have used TIBCO Jaspersoft Studio-6.3.0 which generates these .jrxml and .jasper. In order to my program recognize these files, I copied them into a report package.

When I run on Eclipse, everything works absolutely fine; the report is generated, able to print, everything.

Now the problem: When I export into runnable JAR (Export > Runnable JAR File > Extract required libraries into generated JAR) it doesn't generate at all; shows me a compile error.

There goes the following code:

public final void gerarRelatorio() {
    if (dateChooser.getDate() == null) {
        JOptionPane.showMessageDialog(null, "Preencha o campo de data!");
    } else {
        try {
            JOptionPane.showMessageDialog(null, "Seu relatório será gerado...");

            JasperReport report = JasperCompileManager
                    .compileReport(getClass().getResourceAsStream("RelatorioAttr.jrxml"));

            if (new DAORelatorioImpl().preencherRelatorioATratar(dateChooser.getCalendar())
                    .isEmpty()) {
                JOptionPane.showMessageDialog(null,
                        "Nenhum dado foi encontrado para essa data!");
            } else {
                JasperPrint print = JasperFillManager.fillReport(report, null,
                        new JRBeanCollectionDataSource(new DAORelatorioImpl()
                                .preencherRelatorioATratar(dateChooser.getCalendar())));

                JOptionPane.showMessageDialog(null, "Relatório Gerado com Sucesso!");

                JasperViewer jv = new JasperViewer(print, false);
                jv.setVisible(true);
                jv.toFront();
            }

        } catch (HeadlessException | JRException e) {
            JOptionPane.showMessageDialog(rootPane, "Erro 1: " + e);
            e.printStackTrace();
        } catch (ConexaoException | DAOException ex) {
            JOptionPane.showMessageDialog(rootPane, "Erro 2: " + ex);
        }
    }
}

Again when running on Eclipse it works just fine, but this exception happens when I try to use on compiled JAR:

net.sf.jasperreports.engine.JRException: Error compiling report java source files: C:\Users\guilherme.brandao\workspace\RelatorioAttr_1472481426930_73428.java

I have no clue how to solve this mostly because I don't even know what this file is or where it is created.

I would be grateful for any help you are able to provide.


Answer:

Solved by changing to load the .jasper which is already compiled instead of the .jrxml by the following code:

JasperReport report = JasperCompileManager
            .compileReport(getClass().getResourceAsStream("RelatorioAttr.jrxml"));

to

InputStream jasperStream = getClass().getResourceAsStream("RelatorioAttr.jasper");
JasperReport report = (JasperReport) JRLoader.loadObject(jasperStream); 

Question:

I created a Java program which creates a report with JasperReports. In one of my JasperReports I use the theme="eye.candy.sixties".

when I run the project from Eclipse in the gui, all is fine, see

However when I build the same project with Maven and run it from the commandline I get the error:

Maven: clean compile assembly:single
Command line: java -jar chartTheme-0.0.1-SNAPSHOT-jar-with-dependencies.jar

Exception in thread "main" net.sf.jasperreports.engine.JRRuntimeException: Chart theme "eye.candy.sixties" not found.

What am I missing, what should I change? Any help welcome!

Source code can be found on Github: ChartTheme

I did include the chart theme dependency in Maven, see the "Maven dependencies list in Eclipse:

and in the code below (pom.xml)

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.lightroomstatistics.samples</groupId>
    <artifactId>chartTheme</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>chartTheme</name>
    <description>chartTheme</description>

    <url>www.lightroomstatistics.com</url>
    <organization>
        <name>LightroomStatistics</name>
        <url>www.lightroomstatistics.com</url>
    </organization>

    <parent>
        <groupId>com.lightroomstatistics.maven</groupId>
        <artifactId>lightroomstatistics-parent-pom</artifactId>
        <version>1.0.0</version>
    </parent>

    <properties>
        <java.version>1.8</java.version>
        <jasperreports.version>6.4.0</jasperreports.version>
        <jasperreportsfonts.version>4.0.0</jasperreportsfonts.version>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.source>1.8</maven.compiler.source>
    </properties>

    <repositories>
        <!-- Needed for Jasperreports chart-themes -->
        <repository>
            <id>jr-ce-releases</id>
            <name>JasperReports CE Releases</name>
            <url>http://jaspersoft.jfrog.io/jaspersoft/jr-ce-releases</url>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>net.sf.jasperreports</groupId>
            <artifactId>jasperreports</artifactId>
            <version>${jasperreports.version}</version>
        </dependency>
        <dependency>
            <groupId>net.sf.jasperreports</groupId>
            <artifactId>jasperreports-fonts</artifactId>
            <version>${jasperreportsfonts.version}</version>
        </dependency>
        <!-- jasperreports-chart-themes -->
        <dependency>
            <groupId>net.sf.jasperreports</groupId>
            <artifactId>jasperreports-chart-themes</artifactId>
            <version>${jasperreports.version}</version>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>reports</directory>
                <includes>
                    <include>**/*.*</include>
                </includes>
            </resource>
            <resource>
                <directory>data</directory>
                <includes>
                    <include>**/*.*</include>
                </includes>
            </resource>
        </resources>

        <plugins>
            <plugin>
                <artifactId>maven-resources-plugin</artifactId>
                <version>3.0.2</version>
                <executions>
                    <execution>
                        <id>copy-report-resources</id>
                        <!-- here the phase you need -->
                        <phase>validate</phase>
                        <goals>
                            <goal>copy-resources</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${basedir}/target/reports</outputDirectory>
                            <resources>
                                <resource>
                                    <directory>reports</directory>
                                    <filtering>true</filtering>
                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                    <execution>
                        <id>copy-data-resources</id>
                        <!-- here the phase you need -->
                        <phase>validate</phase>
                        <goals>
                            <goal>copy-resources</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${basedir}/target/data</outputDirectory>
                            <resources>
                                <resource>
                                    <directory>data</directory>
                                    <filtering>true</filtering>
                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>chartTheme.ChartThemesApp</mainClass>
                        </manifest>
                    </archive>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

Answer:

If you open your built joint-library chartTheme-0.0.1-SNAPSHOT-jar-with-dependencies.jar, you'll realize that the contents of file jasperreports-char-themes-6.4.0.jar/jasperreports_extension.properties are misssing, because they were overriden with the contents of some other jasperreports_extension.properties file also present in your dependencies.

In fact, if you search in the output console after running mvn assembly, you'll find these traces:

[INFO] jasperreports_extension.properties already added, skipping

... which, by the way, is not the only one file skipped at assembly.

So, definitely it's not a good idea to assembly all of these dependencies together, because of the overlaps. At least, not in this way.

I think the first thing you should try is to parametrize the assembly descriptor file to exclude the undesired files priorizing the desired ones, which I presume will be the ones in jasperreports-chart-themes.jar (by the traces in the log you posted).

Question:

I have little problem. In previous version of Eclipse (2019-06) I created many reports with JasperSoft (plug-in in eclipse). Yesterday I updated to new version (big mistake?) and I can not create reports. I do everything as always and this is my result:

Exception in thread "main" java.lang.NullPointerException
at net.sf.jasperreports.components.table.fill.TableReport.createCell(TableReport.java:1600)
at net.sf.jasperreports.components.table.fill.TableReport$ReportBandCreator.createColumnCell(TableReport.java:497)
at net.sf.jasperreports.components.table.fill.TableReport$ColumnHeaderCreator.createColumnCell(TableReport.java:709)
at net.sf.jasperreports.components.table.fill.TableReport$ColumnHeaderCreator.createColumnCell(TableReport.java:686)
at net.sf.jasperreports.components.table.fill.TableReport$ReportBandCreator.visitColumn(TableReport.java:476)
at net.sf.jasperreports.components.table.fill.TableReport$ReportBandCreator.visitColumn(TableReport.java:442)
at net.sf.jasperreports.components.table.StandardColumn.visitColumn(StandardColumn.java:74)
at net.sf.jasperreports.components.table.fill.TableReport$ReportBandCreator.visit(TableReport.java:555)
at net.sf.jasperreports.components.table.fill.TableReport.createColumnHeader(TableReport.java:1112)
at net.sf.jasperreports.components.table.fill.TableReport.<init>(TableReport.java:300)
at net.sf.jasperreports.components.table.fill.FillTable.createFillTableSubreportFactory(FillTable.java:335)
at net.sf.jasperreports.components.table.fill.FillTable.createFillSubreport(FillTable.java:309)
at net.sf.jasperreports.components.table.fill.FillTable.evaluate(FillTable.java:131)
at net.sf.jasperreports.engine.fill.JRFillComponentElement.evaluate(JRFillComponentElement.java:110)
at net.sf.jasperreports.engine.fill.JRFillElementContainer.evaluate(JRFillElementContainer.java:381)
at net.sf.jasperreports.engine.fill.JRFillBand.evaluate(JRFillBand.java:500)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillColumnBand(JRVerticalFiller.java:2022)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillDetail(JRVerticalFiller.java:748)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReportStart(JRVerticalFiller.java:255)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReport(JRVerticalFiller.java:115)
at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:580)
at net.sf.jasperreports.engine.fill.BaseReportFiller.fill(BaseReportFiller.java:414)
at net.sf.jasperreports.engine.fill.JRFiller.fill(JRFiller.java:121)
at net.sf.jasperreports.engine.JasperFillManager.fill(JasperFillManager.java:583)
at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:929)
at com.baeldung.jasperreports.Main.main(Main.java:242)

This is my code (shorter version):

String outputFile = File.separatorChar + "D:\\eclipse\\JasperTableExample2.pdf";

Collection<Person> osoba = new ArrayList<Person>();

Person john = new Person();
john.setName("John");
john.setSurname("Doe");
john.setEmail("john@gmail.com");
john.setAge(22);
john.setX(5);
john.setY(5);
john.setZ(1);
john.setDateTime(LocalDateTime.of(2019,12,12,9,25));
osoba.add(john);

JRBeanCollectionDataSource personJRBean = new JRBeanCollectionDataSource(osoba);
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("ItemDataSource", personJRBean);
JasperPrint jasperPrint = JasperFillManager.fillReport("D://path//NewReport.jasper", parameters, new JREmptyDataSource()); // this is #242 line at Main.java
OutputStream outputStream = new FileOutputStream(new File(outputFile));
JasperExportManager.exportReportToPdfStream(jasperPrint, outputStream);

I do not put here a Person class. Java code works well.

In JasperStudio I create new report, new parameter (name as in code - ItemDataSource, set class to net.sf.jasperreports.engine.data.JRBeanCollectionDataSource). Then I create a table with the new dataset and choose this:

Then I just launched Main and the report was generated.

Before update, this process worked perfectly, but after "update step" I am getting this error.


Answer:

I had the exact same problem with the same stacktrace. It was not about eclipse but about the Jaspersoft Studio version.

I was using Jaspersoft Studio 6.11.0 in eclipse and version 6.4.3 of jasperreports.jar at runtime. I had to upgrade my pom.xml (I'm using maven) to both 6.11.0 and it fixed it.

Question:

How do i make a dynamic staked bar graph using jaspersoft. Currently the value column is not accepting list of values but instead it requires an integer. i am expecting the graph to loop through the list that i pass.

public class TeamPerformance {
    public List<TeamData> getReport(String reportId) {
        List<ContractionsPartogramData> result = new ArrayList<>();
        ContractionsPartogramData data = new ContractionsPartogramData();

        List<String> cat = new ArrayList<>();
        cat.add("11:00");
        cat.add("12:00");
        cat.add("13:00");

        List<Integer> teamOneScore = new ArrayList<>();
        teamOneScore.add(1);
        teamOneScore.add(11);
        teamOneScore.add(13);

        List<Integer> teamTwo = new ArrayList<>();
        teamTwo.add(4);
        teamTwo.add(14);
        teamTwo.add(5);

        data.setTeamOne(teamOneScore);
        data.setTeamTwo(teamTwo);
        data.setTeamOneSeries("Team One");
        data.setTeamTwoSeries("Team Two");
        data.setCategories(cat);

        result.add(data);
        return result;
    }
}

The 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="mbp_baby" pageWidth="1684" pageHeight="1190" orientation="Landscape" columnWidth="1150" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="8f9fcfe4-de3f-44f2-a894-dd075a99d88e">
    <property name="com.jaspersoft.studio.data.defaultdataadapter" value="One Empty Record"/>
    <subDataset name="BabyVisitsDataset" uuid="397116d3-884b-412b-aac0-f71201d3be28">
        <property name="com.jaspersoft.studio.data.defaultdataadapter" value="One Empty Record"/>
    </subDataset>
    <detail>
        <band height="343" splitType="Stretch">
            <staticText>
                <reportElement x="79" y="59" width="99" height="20" uuid="af169a41-c5d0-49b5-87fb-b820c543167f"/>
                <textElement textAlignment="Left" verticalAlignment="Middle">
                    <font isBold="true"/>
                    <paragraph leftIndent="5"/>
                </textElement>
                <text><![CDATA[Teams]]></text>
            </staticText>
            <stackedBarChart>
                <chart evaluationTime="Report">
                    <reportElement x="43" y="78" width="200" height="200" uuid="ff603b1a-74f7-4c48-95a3-bbd94f9a2811"/>
                    <chartTitle/>
                    <chartSubtitle/>
                    <chartLegend/>
                </chart>
                <categoryDataset>
                    <categorySeries>
                        <seriesExpression><![CDATA[$F{teamOne}]]></seriesExpression>
                        <categoryExpression><![CDATA[$F{categoryArray}]]></categoryExpression>
                        <valueExpression><![CDATA[$F{arrayTeamOneValues}]]></valueExpression>
                        <labelExpression><![CDATA[]]></labelExpression>
                    </categorySeries>
                    <categorySeries>
                        <seriesExpression><![CDATA[$F{teamTwo}]]></seriesExpression>
                        <categoryExpression><![CDATA[$F{categoryArray}]]></categoryExpression>
                        <valueExpression><![CDATA[$F{arrayTeamOneValues}]]></valueExpression>
                        <labelExpression><![CDATA[]]></labelExpression>
                    </categorySeries>

                </categoryDataset>
                <barPlot>
                    <plot/>
                    <itemLabel/>
                    <categoryAxisFormat>
                        <axisFormat labelColor="#000000" tickLabelColor="#000000" axisLineColor="#000000"/>
                    </categoryAxisFormat>
                    <valueAxisFormat>
                        <axisFormat labelColor="#000000" tickLabelColor="#000000" axisLineColor="#000000"/>
                    </valueAxisFormat>
                </barPlot>
            </stackedBarChart>
        </band>
    </detail>
</jasperReport>

Error stacktrace:

java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.lang.Number
at net.sf.jasperreports.charts.fill.JRFillCategorySeries.evaluate(JRFillCategorySeries.java:141)
at net.sf.jasperreports.charts.fill.JRFillCategoryDataset.customEvaluate(JRFillCategoryDataset.java:110)
at net.sf.jasperreports.engine.fill.JRFillElementDataset.evaluate(JRFillElementDataset.java:160)
at net.sf.jasperreports.engine.fill.JRCalculator.calculateVariables(JRCalculator.java:187)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillDetail(JRVerticalFiller.java:735)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReportStart(JRVerticalFiller.java:255)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReport(JRVerticalFiller.java:115)
at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:580)
at net.sf.jasperreports.engine.fill.BaseReportFiller.fill(BaseReportFiller.java:414)
at net.sf.jasperreports.engine.fill.JRFillSubreport.fillSubreport(JRFillSubreport.java:736)
at net.sf.jasperreports.engine.fill.JRSubreportRunnable.run(JRSubreportRunnable.java:59)
at net.sf.jasperreports.engine.fill.AbstractThreadSubreportRunner.run(AbstractThreadSubreportRunner.java:221)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)

Answer:

I have finally figured it out why the chart was not able to plot. The structure of the data i was sending was in wrong format it was expecting. I created a list which consist of three parameters namely values, category, and series and everything worked perfect. Lastly i added another dataset to contain the actual field names from the created list and attached it to the jrxml chart dataset.

Question:

I'm trying to fix a bug that show up when trying to export a jasper report as a pdf, but when loading a .jrxml file using the JRXmlLoader, the code throws this exception:

Caused by: java.lang.IllegalAccessException: Class org.openide.util.WeakListenerImpl$ProxyListener can not access a member of class org.openide.filesystems.$Proxy0 with modifiers "public"
    at sun.reflect.Reflection.ensureMemberAccess(Unknown Source)
    at java.lang.reflect.AccessibleObject.slowCheckMemberAccess(Unknown Source)
    at java.lang.reflect.AccessibleObject.checkAccess(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.openide.util.WeakListenerImpl$ProxyListener.<init>(WeakListenerImpl.java:413)
    ... 100 more

This is the code that seems to cause that execption :

    JasperDesign jasperDesign = JRXmlLoader.load("C:/jrxmls/myreport.jrxml"); //< this line
    JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
    jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, resultSetDataSource);

Since it is not my code, and since I don't really know how to work using jasper, I apologize in advance for not being able to provide more context to this issue.

I've added multiple org.openide- to my buildpath, because I had a a ton of "ClassNotFoundException", maybe this is where the problem came from ?

I've read somewhere that the problem might come from jasperreport compatibility issues with the JDK 8, but the weird thing is that the code works when running from Eclipse, the exception is only thrown when running as a runnable jar file. This program is not young, it might have 2 years, and until now, the program ran perfectly (as I heard).

EDIT : Okay, so, I tried to run the program using version 1.7 of the jre. Unfortunatly, since it depends on other programs running on 1.8, I can't test this solution.


Answer:

Ok so, I found out what the problem was. I thought it was some missing jars problems, but it was actually a completely different error. The first exception we got was this one :

org.xml.sax.SAXParseException; lineNumber: 12; columnNumber: 16; Error at line 12 char 16: null

when looking at the stacktrace, it showed this :

Caused by: java.lang.ClassNotFoundException: org.openide.util.Lookup
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 74 more

That's why I thought that the program was missing some dependencies.

But the problem was that in the .jrxml file, we added a <queryString>...</queryString> that was used ONLY when testing the document, and within the code, we wanted to replace this query by another one, which led to this exception being thrown.

By removing the whole <queryString>...</queryString>, we were able to solve to problem.

Thanks for the input, I appreciate.