Jasper + JSF- java.lang.NullPointerException

1

I need to generate a report here with Jasper but it is giving error, I did this:

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.fatec.escolar.relatorio.RelatorioNotas.getRelatorioNotas (ReportNotes.java:63)          at        br.fatec.escolar.bean.NotasBean.getReport (NotesBean.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.catalina.core.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.catalina.core.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)

    
asked by anonymous 06.06.2017 / 01:24

1 answer

0

I've simulated the same error in my environment by passing a wrong string from the .jasper file.

And when I did not compile the file .jrxml , then the file .jasper did not exist. And the reason a blank PDF page is generated is because the report is compiled ( .jasper ) by passing% empty%.

In the context of the question here: for whatever reason the parameter JRDataSource dataSource (of signature lista ) is being passed empty ([ " Guillaume - 2013 ]).

 JRBeanCollectionDataSource datasrc = new JRBeanCollectionDataSource(lista);

But I took the path as below:

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

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

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

  • Create a database: public void getRelatorioNotas(List < T > lista) ;
  • Creating a Report in iReport;
  • Compiling the report stackoverflow ;
  • Create an EE java project
  • 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 ('https://pt.stackoverflow.com/questions/262662/inserir-valores-de-upload-num-array-com-outro-nome'),
            ('https://pt.stackoverflow.com/questions/579/por-que-n%C3%A3o-devemos-usar-fun%C3%A7%C3%B5es-do-tipo-mysql'),
            ('https://pt.stackoverflow.com/questions/262661/implementa%C3%A7%C3%A3o-do-jogo-mastermind'),
            ('https://pt.stackoverflow.com/questions/262653/erro-ao-importar-xls-para-o-postgres'),
            ('https://pt.stackoverflow.com/questions/262650/recuo-ap%C3%B3s-focus-em-input-com-jquery'),
            ('https://pt.stackoverflow.com/questions/262648/para-que-serve-o-seletor-media-no-css'),
            ('https://pt.stackoverflow.com/questions/262647/script-busca-python');
    

    2) My file StackOverflowGenerateReport :

    In the project structure the stackoverflow_report.jrxml files are in the folder: .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="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 WebContent/reports/ using the .jasper library.

    3) Example jasperreports.engine.JasperCompileManager :

    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: StackOverflowGenerateReport :

    <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 WEB-INF/web.xml :

    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 the link: DbStackOverflowServlet should have a result similar to the one shown below:

    NOTE-1:Whengeneratingthehttp://localhost:8080/seu_projeto/DbStackOverflowServletfilefromiReport,thereweresomeerrorswhencompiling.jrxmlfromlibrary.jasper.SoIhadtoadaptthejasperreports.engine.JasperCompileManagerfile.Usethetemplateabove.

    NOTE-2:Icouldnotrender.jrxmlcompiledbyiReportusing.jasperlibrarian.Then,discardthejasperreports.engine.JasperFillManagerofiReport.Use.jaspercompiledbyclass.jasperabove.Thereasondoesnotfithereinthecontextofthequestion.

    Reference:

    DavidR.Heffelfinger-2009],Copyright©2009PacktPublishing,# : Create, design, format, and export reports with the world's most popular Java reporting library. [ Gonçalves, Antonio - 2013 ], Apress, © 2013,
    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 on: 12 Dec. 2017
    [ Guillaume - 2013 ], Stack Overflow, Jasper creates empty PDF [duplicate] : Answer. Accessed on: 12 Dec. 2017.

        
    14.12.2017 / 03:27