8 Replies Latest reply on Apr 28, 2008 11:37 PM by yuval valim

    jasperreports integration with seam

    yuval valim Newbie

      Hello everybody am a newbie to seam i m working on a project that would heavily use jasperreports for exporting to excel and pdf is it possible to make a use of a seam component much the same way we use jsf backing beans for integration with jasperreports
      (using a JasperRunManager.runReportToPdfStream(reportStream, ervletOutputStream,parameter,connection); reportStream is here an input stream from a compiled report for example)
      i notice a luck of documentation on this issue is there any article or code example that would explicite this particular point and thanks in advance.

        • 1. Re: jasperreports integration with seam
          Krunoslav Samardzic Newbie

          This is the bean that we use to print reports to pdf, maybe this will help you. It is a bit messy, and some object names are in Croatian, so if you have problem understanding it ask I will explain it.


          package orka.core;
          
          import java.awt.Image;
          import java.io.ByteArrayInputStream;
          import java.io.ByteArrayOutputStream;
          import java.io.File;
          import java.io.IOException;
          import java.util.Collection;
          import java.util.HashMap;
          import java.util.Map;
          
          import javax.ejb.Stateless;
          import javax.faces.context.FacesContext;
          import javax.imageio.ImageIO;
          import javax.servlet.ServletContext;
          import javax.servlet.ServletOutputStream;
          import javax.servlet.http.HttpServletResponse;
          
          import net.sf.jasperreports.engine.JRException;
          import net.sf.jasperreports.engine.JRExporterParameter;
          import net.sf.jasperreports.engine.JasperFillManager;
          import net.sf.jasperreports.engine.JasperPrint;
          import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
          import net.sf.jasperreports.engine.export.FontKey;
          import net.sf.jasperreports.engine.export.JRPdfExporter;
          import net.sf.jasperreports.engine.export.PdfFont;
          
          import org.apache.log4j.Logger;
          import org.jboss.seam.ScopeType;
          import org.jboss.seam.annotations.In;
          import org.jboss.seam.annotations.Name;
          import org.jboss.seam.core.ResourceBundle;
          
          import orka.core.maticni.operater.Operater;
          
          import com.lowagie.text.pdf.BaseFont;
          
          @Stateless
          @Name("printer")
          public class PrinterBean implements Printer {
          
               private static final Logger log = Logger.getLogger(PrinterBean.class);
               
               @In(required = true, value = "operKonv", scope = ScopeType.CONVERSATION)
               public Operater oper;
               
          
               public void print(String imePdf, String opisniFile, Object model,
                         Collection<?> stavke, Map<String, Object> parameters) {
                    log.debug(imePdf + ", " + opisniFile + ", " + model + " , " + stavke);
                    FacesContext fc = FacesContext.getCurrentInstance();
                    ByteArrayInputStream reportFile = (ByteArrayInputStream) fc
                              .getExternalContext().getResourceAsStream(
                                        fc.getExternalContext().getInitParameter("jasperDir")
                                                  + opisniFile + ".jasper");
                    if (parameters == null) {
                         parameters = new HashMap<String, Object>();
                    }
                    if (reportFile == null) {
                         reportFile = (ByteArrayInputStream) fc.getExternalContext()
                                   .getResourceAsStream(
                                             fc.getExternalContext().getInitParameter(
                                                       "jasperDir")
                                                       + "nePostoji.jasper");
                         parameters.put("opisniFile", fc.getExternalContext()
                                   .getInitParameter("jasperDir")
                                   + opisniFile + ".jasper");
                    }
                    ServletContext s = (ServletContext) fc.getExternalContext()
                              .getContext();
                    String path = s.getRealPath(fc.getExternalContext().getInitParameter(
                              "jasperDir"));
                    parameters.put("SUBREPORT_DIR", path + File.separator);
          
                    log.debug("reportFile: " + reportFile);
          
                    if (model != null) {
                         parameters.put("model", model);
                    }
                    parameters.put("korisnik", oper.getKorisnik());
                    parameters.put("oper", oper);
                    parameters.put("REPORT_RESOURCE_BUNDLE", ResourceBundle.instance());
                    Image logoKorisnik = null;
                    ServletContext sc = (ServletContext) fc.getExternalContext()
                              .getContext();
                    try {
                         String putanjaSlikaKors = new String("/slike/ikone/" + ""
                                   + oper.getKorisnik().getNaziv().trim() + ".jpg");
                         File file = new File(sc.getRealPath(putanjaSlikaKors));
                         if (file.exists()) {
                              logoKorisnik = ImageIO.read(file);
                         } else {
                              logoKorisnik = ImageIO.read(new File(sc
                                        .getRealPath("/slike/ikone/orkaBackup.gif")));
                         }
                    } catch (IOException e1) {
                         log.error("GRESKA", e1);
                         throw new RuntimeException(e1);
                    }
                    parameters.put("logoKorisnik", logoKorisnik);
          
                    // dodao tjakopec
                    try {
                         String putanjaSlikaKors = new String(System
                                   .getProperty("user.home")
                                   + File.separator
                                   + FacesContext.getCurrentInstance().getExternalContext()
                                             .getInitParameter("slike")
                                   + File.separator
                                   + "zaglavlje" + oper.getKorisnik().getNaziv() + ".jpg");
                         File file = new File(putanjaSlikaKors);
                         if (file.exists()) {
                              logoKorisnik = ImageIO.read(file);
                         } else {
                              logoKorisnik = ImageIO.read(new File(sc
                                        .getRealPath("/slike/entitet/orkaZaglavlje.jpg")));
                         }
                    } catch (IOException e1) {
                         log.error("GRESKA", e1);
                         throw new RuntimeException(e1);
                    }
                    parameters.put("zaglavljeKorisnik", logoKorisnik);
                    // zavrsio tjakopec
          
                    Image ikonaCheckTrue = null;
                    try {
                         String putanja = new String("/slike/ikone/" + "checkBlack.gif");
                         ikonaCheckTrue = ImageIO.read(new File(sc.getRealPath(putanja)));
                    } catch (IOException e1) {
                         log.error("GRESKA", e1);
                         throw new RuntimeException(e1);
                    }
          
                    parameters.put("ikonaCheckTrue", ikonaCheckTrue);
          
                    Image ikonaCheckFalse = null;
                    try {
                         String putanja = new String("/slike/ikone/" + "checkBlackF.gif");
                         ikonaCheckFalse = ImageIO.read(new File(sc.getRealPath(putanja)));
                    } catch (IOException e1) {
                         log.error("GRESKA", e1);
                         throw new RuntimeException(e1);
                    }
                    JRBeanCollectionDataSource ds = null;
                    if (stavke != null) {
                         ds = new JRBeanCollectionDataSource(stavke);
                    }
          
                    parameters.put("ikonaCheckFalse", ikonaCheckFalse);
          
                    JasperPrint report;
                    try {
                         if (ds != null) {
                              report = JasperFillManager.fillReport(reportFile, parameters,
                                        ds);
                         } else {
                              report = JasperFillManager.fillReport(reportFile, parameters);
                         }
                    } catch (JRException e) {
                         throw new RuntimeException(e);
                    }
          
                    HttpServletResponse response = (HttpServletResponse) fc
                              .getExternalContext().getResponse();
                    response.setContentType("application/pdf");
                    response.setHeader("Content-disposition", "attachment; " + "filename="
                              + imePdf + ".pdf");
                    JRPdfExporter exporter = new JRPdfExporter();
                    ByteArrayOutputStream Report = new ByteArrayOutputStream();
                    // ovako ce u buducnosti izgledati printanje knjige
                    // List<JasperPrint> lista = new Vector<JasperPrint>();
                    // lista.add(report);
                    // lista.add(report);
                    // exporter.setParameter(JRExporterParameter.JASPER_PRINT_LIST, lista);
                    exporter.setParameter(JRExporterParameter.JASPER_PRINT, report);
                    exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, Report);
                    fontEmbeding(exporter);
                    try {
                         exporter.exportReport();
                         byte[] bytes = Report.toByteArray();
                         response.setContentLength(bytes.length);
                         ServletOutputStream out = response.getOutputStream();
                         out.write(bytes, 0, bytes.length);
                         out.flush();
                         out.close();
                    } catch (JRException e) {
                         new RuntimeException(e);
                    } catch (IOException e) {
                         new RuntimeException(e);
                    }
                    fc.responseComplete();
          
               }
          
               /**
                * Embedira arial font u ispis
                * 
                * @param exporter
                */
               protected void fontEmbeding(JRPdfExporter exporter) {
                    FacesContext fc = FacesContext.getCurrentInstance();
                    String putanja = fc.getExternalContext().getInitParameter("fontsDir")
                              + "arial.ttf";
                    // obicni
                    HashMap<FontKey, PdfFont> fontMap = new HashMap<FontKey, PdfFont>();
                    FontKey key = new FontKey("Arial", false, false); // (String fontName,
                    // Boolean bold,
                    // Boolean italic)
                    PdfFont font = new PdfFont(putanja, BaseFont.CP1250, true);
                    fontMap.put(key, font);
          
                    // bold
                    putanja = fc.getExternalContext().getInitParameter("fontsDir")
                              + "arialbd.ttf";
                    FontKey keyB = new FontKey("Arial", true, false); // (String fontName,
                    // Boolean bold,
                    // Boolean italic)
                    PdfFont fontB = new PdfFont(putanja, BaseFont.CP1250, true);
                    fontMap.put(keyB, fontB);
          
                    // italic
                    putanja = fc.getExternalContext().getInitParameter("fontsDir")
                              + "ariali.ttf";
                    FontKey keyC = new FontKey("Arial", false, true); // (String fontName,
                    // Boolean bold,
                    // Boolean italic)
                    PdfFont fontC = new PdfFont(putanja, BaseFont.CP1250, true);
                    fontMap.put(keyC, fontC);
          
                    exporter.setParameter(JRExporterParameter.FONT_MAP, fontMap);
          
               }
               
               
               
               
          }
          


          • 2. Re: jasperreports integration with seam
            yuval valim Newbie

            thank you very much sir for your reply right now i m trying to run the classical example of a .xhtml page containing a unique generate pdf button . I created a new action in my seam project
            then i tried to use a stateless session bean to get the report generated here is my code


            • 3. Re: jasperreports integration with seam
              yuval valim Newbie
              
              package org.domain.projectJasper.session;
              
              
              import java.io.FileInputStream;
              
              import java.io.InputStream;
              
              import java.util.HashMap;
              
              
              import javax.ejb.Stateless;
              
              import javax.servlet.ServletOutputStream;
              
              import javax.servlet.http.HttpServletResponse;
              
              
              import net.sf.jasperreports.engine.JREmptyDataSource;
              
              import net.sf.jasperreports.engine.JasperRunManager;
              
              
              import org.jboss.seam.annotations.Name;
              
              import org.jboss.seam.annotations.In;
              
              import org.jboss.seam.annotations.Logger;
              
              import org.jboss.seam.log.Log;
              
              import org.jboss.seam.faces.FacesContext;
              
              
              @Stateless
              
              @Name("generateReport")
              
              public class GenerateReportBean implements GenerateReport {
              
                      
              
                      
              
                  public void generateReport()throws Exception
              
                  {
              
                     
              
                      FacesContext seamContext=new FacesContext(); 
              
                      HttpServletResponse response=(HttpServletResponse)seamContext.getContext().getExternalContext().getResponse();
              
                     
              
                      InputStream reportStream=new FileInputStream(""); 
              
                      if(reportStream==null){
              
                              System.out.println("reportStream is null");
              
                      }
              
                      System.out.println("report stream is not null");
              
                      ServletOutputStream os=response.getOutputStream();
              
                      HashMap parameter=new HashMap();
              
                      JasperRunManager.runReportToPdfStream(reportStream, os, parameter,new JREmptyDataSource());
              
                      response.setContentType("application/pdf");
              
                      seamContext.getContext().responseComplete();
              
                      os.flush();
              
                      os.close();
              
                      
              
                          }
              
                  
              
                  //add additional action methods
              
                  
              
              }
              
              


              the hole project failes to deploy in jboss 4.2 ,i m using jboss tools plugins with eclipse europa fallen (i m also using seam 2) and really thanks for the particular interest shown upon my request. 

              • 4. Re: jasperreports integration with seam
                Jason Long Novice

                I use a servlet.



                public class JRPDFServlet extends HttpServlet {
                   
                    byte[] bytes;
                    Pipetracker pt = new Pipetracker();
                    public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
                        byte[] bytes = (byte[]) request.getSession().getAttribute("bytesPDF");
                        String documentId = request.getParameter("documentId");
                     
                       
                        if(documentId!=null) 
                        {
                            //DocumentBytesDAO documentBytesDAO = (DocumentBytesDAO) Component.getInstance("documentBytesDAO");        
                            DocumentBytesDAO documentBytesDAO = pt.getDocumentBytesDAO();     
                             bytes = documentBytesDAO.findById((Long.parseLong(documentId)))
                                                                   .getDocument();
                        }        
                        if (bytes == null) {
                            throw new ServletException("No PDF found.");
                        }
                        response.setContentType("application/pdf");
                        OutputStream ouputStream = response.getOutputStream();
                        if (ouputStream != null) {
                            try {
                                ouputStream.write(bytes, 0, bytes.length);
                                ouputStream.flush();
                                ouputStream.close();
                            } catch (IOException ex) {
                                ex.printStackTrace();
                            }
                        }
                    }
                }


                • 5. Re: jasperreports integration with seam
                  Jason Long Novice

                  I use



                  public String generate() {
                       try {
                            Contexts.getSessionContext().set("bytesPDF", releaseDAO.fax(releasePipe.getId()));
                            return null;
                       } catch (Exception e) {
                            e.printStackTrace();
                            return null;
                       }
                  }



                  To place the bytes in the session.


                  I call it from the following button



                        <a4j:commandButton rendered="#{releasePipe.id!=null}"
                                          value="Generate"
                                         action="#{releasePipeForm.generate}"
                                         oncomplete="openNewWindow('/#{releasePipe.trackingNum}.pdf','printable','status=yes,resizable=yes,toolbar=no,scrollbars=yes' + winCenterCoordinates(1024,768));"
                                          styleClass="butt_std main_out"/>



                  This opens the pdf in a new window and since the url contains my release number I can use acrobats built in functionality to print, email or fax the document.  The attachment will be named myreleasenumber.pdf if email is used.


                  • 6. Re: jasperreports integration with seam
                    yuval valim Newbie

                    thanks for the reply actually i m deeling with deployement issues i adopted the aproach of Kruno Samardzic but i have a systematic
                    org.jboss.xb.binding.JBossXBRuntimeException: Failed to create a new SAX parser error and i searched throughout the forums for similar issues i found http://www.seamframework.org/Community/UnableToDeploySeamOnJBoss422GA  even if i have the correct configuration i still have the same deployement error is there any uncompatiblity between the jaspereports distribution jar files(i tried with different versions 2,1.3..).And if it is the case what are the minimal jar files needed for excel and pdf generation to avoid getting this error,i really don t know if there is a specific configuration or workaround.and thanks in advance

                    • 7. Re: jasperreports integration with seam
                      yuval valim Newbie

                      i apologize for my previous post it was only a problem due to duplicated jar files in my classpath but even thought i still have an exception while generating the report with my previous code and the stack trace is as following:
                      java.lang.IllegalStateException: Servlet response already use stream, Writer not possible
                           at org.ajax4jsf.webapp.FilterServletResponseWrapper.getWriter(FilterServletResponseWrapper.java:226)
                           at javax.servlet.ServletResponseWrapper.getWriter(ServletResponseWrapper.java:112)
                           at com.sun.facelets.FaceletViewHandler.createResponseWriter(FaceletViewHandler.java:414)
                           at com.sun.facelets.FaceletViewHandler.renderView(FaceletViewHandler.java:571)
                           at org.ajax4jsf.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:108)
                           at org.ajax4jsf.application.AjaxViewHandler.renderView(AjaxViewHandler.java:216)
                           at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:106)
                           at com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:251)
                           at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:144)
                           at javax.faces.webapp.FacesServlet.service(FacesServlet.java:245)
                           at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
                           at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
                           at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:83)
                           at org.jboss.seam.web.MultipartFilter.doFilter(MultipartFilter.java:85)
                           at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69)
                           at org.jboss.seam.web.ExceptionFilter.doFilter(ExceptionFilter.java:64)
                           at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69)
                           at org.jboss.seam.web.RedirectFilter.doFilter(RedirectFilter.java:44)
                           at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69)
                           at org.ajax4jsf.webapp.BaseXMLFilter.doXmlFilter(BaseXMLFilter.java:141)
                           at org.ajax4jsf.webapp.BaseFilter.doFilter(BaseFilter.java:281)
                           at org.jboss.seam.web.Ajax4jsfFilter.doFilter(Ajax4jsfFilter.java:60)
                           at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69)
                           at org.jboss.seam.web.LoggingFilter.doFilter(LoggingFilter.java:58)
                           at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69)
                           at org.jboss.seam.debug.hot.HotDeployFilter.doFilter(HotDeployFilter.java:68)
                           at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69)
                           at org.jboss.seam.servlet.SeamFilter.doFilter(SeamFilter.java:158)
                           at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
                           at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
                           at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
                           at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
                           at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
                           at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230)
                           at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
                           at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:179)
                           at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:432)
                           at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:84)
                           at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
                           at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
                           at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:157)
                           at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
                           at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:262)
                           at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
                           at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
                           at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:446)
                           at java.lang.Thread.run(Unknown Source)
                      sorry if my questions are  too basic but i m really a newbie to this technology and many thanks

                      • 8. Re: jasperreports integration with seam
                        yuval valim Newbie

                        Dear samardzic i followed exactly your code but it throws the writer not possible exception plz how did you do to avoid this and thanks