Jasper + JSF-java.lang.Nullpointerexception

Asked

Viewed 712 times

1

I really need to generate a report here with the Jasper but it’s making a mistake, I did it:

Java:

public void getRelatorioNotas(List < T > lista) {
    try {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext();
        String path = servletContext.getRealPath("/WEB-INF/report/Notas.jasper");

        System.out.println(path);
        InputStream stream = this.getClass().getResourceAsStream(path);

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

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        JRBeanCollectionDataSource datasrc = new JRBeanCollectionDataSource(lista);

        JasperReport jasper = (JasperReport) JRLoader.loadObject(stream);

        // para usar JavaBeanDataSource define 'datasrc' como datasource
        JasperPrint print = JasperFillManager.fillReport(jasper, params, getConexao());

        JasperExportManager.exportReportToPdfStream(print, baos);

        response.reset();

        response.setContentType("application/pdf");

        response.setContentLength(baos.size());

        response.setHeader("Content-disposition", "inline; filename=relatorioNotas.pdf");

        response.getOutputStream().write(baos.toByteArray());

        response.getOutputStream().flush();

        response.getOutputStream().close();

        context.responseComplete();

        closeConnection();

    } catch (Exception e) {
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Erro ao gerar o relatorio!"));
        e.printStackTrace();
    }
}

@MB
public void getRelatorio() {
    RelatorioNotas < Notas > report = new RelatorioNotas < Notas > ();
    if (notas.size() > 0) {
        report.getRelatorioNotas(notas);
    } else {
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Não há registros!"));
    }
}

Html:

"<p:commandButton value="Relatório"
    actionListener="#{notasBean.getRelatorio()}" ajax="false"
    onclick="this.form.target='_blank' "></p:commandButton>"

Error:

java.lang.Nullpointerexception at java.io.Objectinputstream$Peekinputstream.read(Objectinputstream.java:2338) at java.io.Objectinputstream$Peekinputstream.readFully(Objectinputstream.java:2351) at java.io.Objectinputstream$Blockdatainputstream.readShort(Objectinputstream.java:2822) at java.io.Objectinputstream.readStreamHeader(Objectinputstream.java:804) at java.io.Objectinputstream.(Objectinputstream.java:301) at net.sf.jasperreports.engine.util.ContextClassLoaderObjectInputStream.(Contextclassloaderobjectinputstream.java:58) at net.sf.jasperreports.engine.util.JRLoader.loadObject(Jrloader.java:248) at net.sf.jasperreports.engine.util.JRLoader.loadObject(Jrloader.java:233) at br.com.fatec.escolar.relatorio.RelatorioNotas.getRelatorioNotas(Reportersnotes.java:63) at br.com.fatec.escolar.bean.NotasBean.getRelatorio(Notasbean.java:77) at sun.reflect..Nativemethodaccessorimpl.invoke0(Native Method) at sun.reflect.Nativemethodaccessorimpl.invoke(Nativemethodaccessorimpl.java:62) at sun.reflect.Delegatingmethodaccessorimpl.invoke(Delegatingmethodaccessorimpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.apache.el.parser.Astvalue.invoke(Astvalue.java:247) at org.apache.el.MethodExpressionImpl.invoke(Methodexpressionimpl.java:267) at com.sun.faces.facelets.el.TagMethodExpression.invoke(Tagmethodexpression.java:105) at javax.faces.Event.MethodExpressionActionListener.processAction(Methodexpressionactionlistener.java:147) at javax.faces.Event.ActionEvent.processListener(Actionevent.java:88) at javax.faces.Component.UIComponentBase.broadcast(Uicomponentbase.java:814) at javax.faces.Component.UICommand.broadcast(Uicommand.java:300) at javax.faces.Component.UIData.broadcast(Uidata.java:1108) at javax.faces.Component.UIViewRoot.broadcastEvents(Uiviewroot.java:790) at javax.faces.Component.UIViewRoot.processApplication(Uiviewroot.java:1282) at com.sun.faces.lifecycle.Invokeapplicationphase.execute(Invokeapplicationphase.java:81) at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) at com.sun.faces.lifecycle.Lifecycleimpl.execute(Lifecycleimpl.java:198) at javax.faces.webapp.FacesServlet.service(Facesservlet.java:658) at org.apache.Applicationfilterchain.internalDoFilter(Applicationfilterchain.java:292) at org.apache.Catalina.core.Applicationfilterchain.doFilter(Applicationfilterchain.java:207) at org.apache.Tomcat.websocket.server.WsFilter.doFilter(Wsfilter.java:52) at org.apache.Applicationfilterchain.internalDoFilter(Applicationfilterchain.java:240) at org.apache.Catalina.core.Applicationfilterchain.doFilter(Applicationfilterchain.java:207) at org.apache.Catalina.core.Standardwrappervalve.invoke(Standardwrappervalve.java:212) at org.apache.Catalina.core.Standardcontextvalve.invoke(Standardcontextvalve.java:106) at org.apache.Catalina.authenticator.Authenticatorbase.invoke(Authenticatorbase.java:502) at org.apache.Catalina.core.Standardhostvalve.invoke(Standardhostvalve.java:141) at org.apache.Catalina.valves.Errorreportvalve.invoke(Errorreportvalve.java:79) at org.apache.Catalina.valves.Abstractaccesslogvalve.invoke(Abstractaccesslogvalve.java:616) at org.apache.Catalina.core.Standardenginevalve.invoke(Standardenginevalve.java:88) at org.apache.Catalina.connector.Coyoteadapter.service(Coyoteadapter.java:509) at org.apache.Coyote.http11.Abstracthttp11processor.process(Abstracthttp11processor.java:1104) at org.apache.Coyote.Abstractprotocol$Abstractconnectionhandler.process(Abstractprotocol.java:684) at org.apache.Tomcat.util.net.Nioendpoint$Socketprocessor.doRun(Nioendpoint.java:1520) at org.apache.Tomcat.util.net.Nioendpoint$Socketprocessor.run(Nioendpoint.java:1476) at java.util.Concurrent.ThreadPoolExecutor.runWorker(Threadpoolexecutor.java:1142) at java.util.Concurrent.Threadpoolexecutor$Worker.run(Threadpoolexecutor.java:617) at org.apache.Tomcat.util.threads.Taskthread$Wrappingrunnable.run(Taskthread.java:61) at java.lang.Thread.run(Thread.java:745)

  • the variable stream is null (this.getClass().getResourceAsStream(path) returned null). In which directory structure is your file ?

  • it is within the WEB-INF (/WEB-INF/report/Notes.Jasper)

  • now that I’ve seen it, change this.getClass(). getResourceAsStream(path); by servletContext.getResourceAsStream("WEB-INF/report/Notes.Jasper"); (no bar at the very beginning) it should work.

  • Still giving java.lang.Nullpointerexception... I don’t know pqq

  • takes a print of your expanded file structure and attaches to the question, it should work.

  • I managed to find the way... now he opens the whole blank report page

  • If it’s opening in blank, somehow the objects aren’t getting into Jeremiah. Note this command of yours: Jasperfillmanager.fillReport(Jasper, params, getConexao()), the third parameter should be the datasrc variable if you are using java objects as source.

  • @Juniorabreu, see what was answered here: Jasper creates Empty PDF. In my environment, I put the title and it worked! Appeared the title band of iReport appeared, but the gang of detail, no!

Show 3 more comments

1 answer

0

I made the same mistake in my environment by passing a string wrong file .jasper.

And when I didn’t compile the file .jrxml, then the file .jasper did not exist. And the reason a page is generated PDF blank, it is because the report is compiled (.jasper) passing a JRDataSource dataSource vázio.

In the context of the question here: for any reason the parameter lista (of signature public void getRelatorioNotas(List < T > lista)) is being passed empty ([Guillaume - 2013]).

 JRBeanCollectionDataSource datasrc = new JRBeanCollectionDataSource(lista);

But I took the path as down:

String strJasper =  getServletContext()
       .getRealPath("/reports/stackoverflow_report.jasper");

System.out.println("strJasper = " + strJasper);

To simulate and test in my environment I did the following:

  1. Create a database: stackoverflow;
  2. Creating a report in iReport;
  3. Compiling the report StackOverflowGenerateReport;
  4. Create a java EE project;
  5. Create a Dbstackoverflowservlet Servlet;

1) My database for the report:

CREATE SCHEMA `stackoverflow` ;

CREATE TABLE `Pages` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `url` varchar(500) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1;

INSERT INTO `stackoverflow`.`Pages` (`url`) 
VALUES ('/questions/262662/inserir-valores-de-upload-num-array-com-outro-nome'),
        ('/questions/579/por-que-n%C3%A3o-devemos-usar-fun%C3%A7%C3%B5es-do-tipo-mysql'),
        ('/questions/262661/implementa%C3%A7%C3%A3o-do-jogo-mastermind'),
        ('/questions/262653/erro-ao-importar-xls-para-o-postgres'),
        ('/questions/262650/recuo-ap%C3%B3s-focus-em-input-com-jquery'),
        ('/questions/262648/para-que-serve-o-seletor-media-no-css'),
        ('/questions/262647/script-busca-python');

2) My archive stackoverflow_report.jrxml:

In the project structure the files .jrxml is in the folder: WebContent/reports/.

<?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="stackoverflow_report" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" >
    <property name="ireport.zoom" value="1.0"/>
    <property name="ireport.x" value="0"/>
    <property name="ireport.y" value="0"/>
    <parameter name="GENERATED_BY" class="java.lang.String">
        <defaultValueExpression><![CDATA["SEU NOME VEM AQUI"]]></defaultValueExpression>
    </parameter>
    <parameter name="PATH_IMG" class="java.lang.String">
        <defaultValueExpression><![CDATA["/path/to/WebContent/img"]]></defaultValueExpression>
    </parameter>
    <queryString>
        <![CDATA[SELECT
     Pages.`id`,
     Pages.`url`
        FROM
     `stackoverflow_260791`.`Pages` Pages]]>
    </queryString>
    <field name="id" class="java.lang.Long">
        <fieldDescription><![CDATA[]]></fieldDescription>
    </field>
    <field name="url" class="java.lang.String">
        <fieldDescription><![CDATA[]]></fieldDescription>
    </field>
    <background>
        <band splitType="Stretch"/>
    </background>
    <pageHeader>
        <band height="94" splitType="Stretch">
            <textField pattern="EEEEE dd MMMMM yyyy">
                <reportElement x="364" y="57" width="188" height="14" />
                <textElement textAlignment="Right">
                    <font isBold="true"/>
                </textElement>
                <textFieldExpression class="java.util.Date" ><![CDATA[new java.util.Date()]]></textFieldExpression>
            </textField>
            <staticText>
                <reportElement x="182" y="19" width="346" height="27" />
                <textElement textAlignment="Center">
                    <font size="20" isBold="true"/>
                </textElement>
                <text><![CDATA[Stack Overflow | Relatório URLs]]></text>
            </staticText>
            <textField>
                <reportElement x="-1" y="71" width="553" height="18" />
                <textElement textAlignment="Right" verticalAlignment="Middle">
                    <font isBold="true"/>
                </textElement>
                <textFieldExpression><![CDATA["Gerado por  " + $P{GENERATED_BY}]]></textFieldExpression>
            </textField>
            <image scaleImage="FillFrame">
                <reportElement mode="Transparent" x="2" y="1" width="161" height="70" />
                <imageExpression><![CDATA[$P{PATH_IMG}+"/stackoverflow_logo.png"]]></imageExpression>
            </image>
        </band>
    </pageHeader>
    <columnHeader>
        <band height="25" splitType="Stretch">
            <staticText>
                <reportElement x="0" y="2" width="100" height="20" />
                <textElement textAlignment="Center" verticalAlignment="Middle">
                    <font size="12" isBold="true"/>
                </textElement>
                <text><![CDATA[ID]]></text>
            </staticText>
            <staticText>
                <reportElement x="100" y="2" width="100" height="20" />
                <textElement textAlignment="Left" verticalAlignment="Middle">
                    <font size="12" isBold="true"/>
                </textElement>
                <text><![CDATA[URL]]></text>
            </staticText>
            <line>
                <reportElement x="2" y="24" width="550" height="1" />
            </line>
        </band>
    </columnHeader>
    <detail>
        <band height="23" splitType="Stretch">
            <textField>
                <reportElement x="0" y="0" width="100" height="20" />
                <textElement textAlignment="Center" verticalAlignment="Middle">
                    <font size="10" isBold="false"/>
                </textElement>
                <textFieldExpression class="java.lang.Long" ><![CDATA[$F{id}]]></textFieldExpression>
            </textField>
            <textField isStretchWithOverflow="true">
                <reportElement x="100" y="0" width="455" height="20" />
                <textElement verticalAlignment="Middle"/>
                <textFieldExpression class="java.lang.String" ><![CDATA[$F{url}]]></textFieldExpression>
            </textField>
        </band>
    </detail>
    <pageFooter>
        <band height="36" splitType="Stretch"/>
    </pageFooter>
</jasperReport>

First we have to compile the file .jasper using the library jasperreports.engine.JasperCompileManager.

3) Example StackOverflowGenerateReport:

public class StackOverflowGenerateReport
{
    Connection connection;
    private static final String strPathReportJrxml = "/WebContent/reports/stackoverflow_report.jrxml";
    private static final String dBName = "stackoverflow";
    private static final String pw = "sua_senha_mysql";

  public void generateReport()
  {
    try
    {
        HashMap<String, String> parameterMap = new HashMap<String, String>();
        parameterMap.put("GENERATED_BY", "Seu nome aqui");
        parameterMap.put("PATH_IMG", "/path/to/WebContent/img");

        Class.forName("com.mysql.jdbc.Driver");
        connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/"+dBName+"?user=root&password="+pw);

        String path = new File(".").getCanonicalPath() + strPathReportJrxml;
        System.out.println("Filling report...");
        String jasperReport = JasperCompileManager.compileReportToFile(path);

        System.out.println("jasperReport = " + jasperReport);
        JasperFillManager.fillReportToFile(
            jasperReport,
            parameterMap, 
            connection
        );
        System.out.println("Done!");
        connection.close();
    }
    catch (JRException e)
    {
      e.printStackTrace();
    }
    catch (ClassNotFoundException e)
    {
      e.printStackTrace();
    }
    catch (SQLException e)
    {
      e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
  }

  public static void main(String[] args)
  {
    new StackOverflowGenerateReport().generateReport();
  }

4) Creating a Java EE project. Edit the deployment descriptor, that is, edit the file: WEB-INF/web.xml:

<servlet>
    <display-name>DbStackOverflowServlet</display-name>
    <servlet-name>DbStackOverflowServlet</servlet-name>
    <!-- <servlet-class>net.ensode.jasperbook.FirstReportSendToBrowserServlet</servlet-class> -->
    <servlet-class>net.ensode.jasperbook.DbStackOverflowServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>DbStackOverflowServlet</servlet-name>
    <url-pattern>/DbStackOverflowServlet</url-pattern>
</servlet-mapping>

5) The class DbStackOverflowServlet:

public class DbStackOverflowServlet extends HttpServlet {

     /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private static final String strPathReportStream = "/reports/stackoverflow_report.jasper";
    private static final String dBName = "stackoverflow";
    private static final String pw = "senha_bando_mysql";

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Connection connection;
        ServletOutputStream servletOutputStream = response.getOutputStream();
        InputStream reportStream = getServletConfig()
            .getServletContext()
            .getResourceAsStream(strPathReportStream);
        HashMap<String, String> parameterMap = new HashMap<String, String>();
        parameterMap.put("GENERATED_BY", "Seu nome aqui");
        parameterMap.put("PATH_IMG", "/PATH_DO_SEU_PROJETO_AQUI/WebContent/img");

        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/"+dBName+"?user=root&password="+pw);
            JasperRunManager.runReportToPdfStream(
                reportStream, 
                servletOutputStream,
                parameterMap, 
                connection
            );
            connection.close();
            servletOutputStream.flush();
            servletOutputStream.close();
        } catch (Exception e) {
            // display stack trace in the browser
            StringWriter stringWriter = new StringWriter();
            PrintWriter printWriter = new PrintWriter(stringWriter);
            e.printStackTrace(printWriter);
            response.setContentType("text/plain");
            response.getOutputStream().print(stringWriter.toString());
        }
    }
}

Accessing to the link: http://localhost:8080/seu_projeto/DbStackOverflowServlet we should have a result similar to the one shown below:

printscreen com um exemplo do relatório


NOTE 1: When generating the file .jrxml by iReport, some errors occurred when compiling the .jasper by the library jasperreports.engine.JasperCompileManager. So I had to adapt the file .jrxml. Use the model above.

NOTE 2: I couldn’t render .jasper compiled by iReport using bibliotéca jasperreports.engine.JasperFillManager. Then discard the .jasper iReport. Use the .jasper compiled by the class StackOverflowGenerateReport above. The reason does not fit here in the context of the question.


Reference:

[David R. Heffelfinger - 2009], Copyright 2009 Packt Publishing, Jasperreports 3.5 for Java Developers: Create, design, format, and export Reports with the world’s Most popular Java Reporting library.
[Gonçalves, Antonio - 2013], Apress, 2013, Beginning Java EE 7 (Expert Voice in Java).
[Juneau, Josh - 2013], Apress, 2013, Java EE 7 Recipes: A problem-Solution Approach - Proven Solutions for Java Enterprise Edition 7 Developement .
[Michal Cmil et al - 2014], Copyright 2014 Packt Publishing, Java EE 7 Development with Wildfly: Leverage the power of the Wildfly application server from Jboss to develop Modern Java EE 7 Applications..
[SG Ganesh et al - 2015], Apress; 2nd ed., OCP Java SE 8 Programmer: A Comprehensive OCPJP 8 Certification Guide. Accessed: 12 Dec. 2017.
[Guillaume - 2013], Stack Overflow, Jasper creates Empty PDF [Uplicate]: Answer. Accessed in: 12 Dec. 2017.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.