Using Jasper Reports with Icefaces and Visual Web

Ok here’s how to do it.

Firstly you’ll need a Jasper Reports Engine Class.

Create a new class in your project.

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package PHJ;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.sql.ResultSet;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.FacesException;
import javax.faces.context.ExternalContext;
import net.sf.jasperreports.engine.JRExporter;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JRResultSetDataSource;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.export.JRPdfExporter;

/**
 *
 * @author paulc
 */
public class PHJJasperReportEngine {

        private databasesettings MyDB=new databasesettings();

    // private static final String PREFIX = "/WEB-INF/reports/";
    private static final String PREFIX = "";///faces/";
    /**
     * <p>Suffix to the resource name for compiled reports.</p>
     */
    private static final String SUFFIX = ".jasper";
    /**
     * <p>Valid content types for reports that we can produce.</p>
     */
    private static final String[] VALID_TYPES = {"text/html", // Standard HTML representation
        "application/pdf", // Adobe Portable Document Format
        "application/rtf"};

     public byte[] iceFacesjasperReport(String sBaseURL,String sSQL,String name, String type, Map params) throws IOException {
        URL url=null;
        ByteArrayOutputStream returnStream=new ByteArrayOutputStream();

        System.out.println(sBaseURL);
        try {
            url = new URI(sBaseURL+"/"+name+SUFFIX).toURL();
        } catch (URISyntaxException ex) {
            Logger.getLogger(PHJJasperReportEngine.class.getName()).log(Level.SEVERE, null, ex);
        }

             ResultSet data=null;
        try {
            data = MyDB.getDataFromMYSQL(sSQL);
        } catch (ClassNotFoundException ex) {
            System.out.println("Class not found "+ex);
        }
             if (data==null) {
                 System.out.println("Error in SQL "+sSQL);
                 return null;
             }

        // Validate that we recognize the report type
        // before potentially wasting time filling the
        // report with data

        boolean found = false;
        for (int i = 0; i < VALID_TYPES.length; i++) {
            if (VALID_TYPES[i].equals(type)) {
                found = true;
                break;
            }
        }
        if (!found) {
            throw new IllegalArgumentException("Invalid report type '" + type + "' requested");
        }

        // Look up the compiled report design resource
        InputStream stream = url.openStream();

        if (stream == null) {
            throw new IllegalArgumentException("Unknown report name '" + name + "' requested");
        }

        try {
            data.beforeFirst();
        } catch (Exception e) {
            throw new FacesException(e);
        }

        // Fill the requested report with the specified data
        JRResultSetDataSource ds = new JRResultSetDataSource(data);
        JasperPrint jasperPrint = null;
        try {

            jasperPrint = JasperFillManager.fillReport(
                    stream, params, ds);

        } catch (RuntimeException e) {
            System.out.println(e);
            throw e;
        } catch (Exception e) {
            System.out.println(e);
            throw new FacesException(e);
        } finally {
            try {

                stream.close();
            } catch (IOException e) {
            }
        }

        // Configure the exporter to be used, along with the custom
        // parameters specific to the exporter type
        JRExporter exporter = null;

         // PersistentFacesState response=(PersistentFacesState)econtext.getResponse();
        //FacesContext fcontext = FacesContext.getCurrentInstance();
        try {
          //  response.setContentType(type);
            if ("application/pdf".equals(type)) {
                exporter = new JRPdfExporter();

            //    response.setHeader("Content-Type", "application/download");
              //  response.setHeader("Content-Disposition", "attachment; filename=" + name + ".pdf");

                exporter.setParameter(JRExporterParameter.JASPER_PRINT,
                        jasperPrint);
                exporter.setParameter(JRExporterParameter.OUTPUT_STREAM,
                        returnStream);

            }
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new FacesException(e);
        }

        // Enough with the preliminaries ...
        // export the report already
        try {
            exporter.exportReport();
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new FacesException(e);
        }

        // Tell JavaServer Faces that no output is required
        return returnStream.toByteArray();

    }

        public static byte[] toByteArray(InputStream input) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buf = new byte[4096];
        int len = 0;
        while ((len = input.read(buf)) > -1) output.write(buf, 0, len);
        return output.toByteArray();
    }

}

Then create a new page. You then need to add an OUTPUT RESOURCE component. I do this in the JSP tab because it doesn’t have any properties.

  <ice:outputResource attachment="true" fileName="subcontractorsummary.pdf" id="pdf-button" label="Output to PDF" mimeType="application/pdf"
                            resource="#{FRIMICESUBCONTRACTORSUMMARY.pdfResource}" 
style="height: 24px; left: 24px; top: 168px; position: absolute; width: 119px" type="button"/>

In this case the page is called FRIMICESUBCONTRACTORSUMMARY so you’ll need to change that to match.

Now in the Java backing bean.

    private Resource pdfResource;

    public Resource getPdfResource() {
        return pdfResource;
    }

    public void setPdfResource(Resource pdfResource) {
        this.pdfResource = pdfResource;
    }

    class MyResource implements Resource, Serializable {
        public String sURL;
        private String resourceName;
        private final Date lastModified;
        private ExternalContext extContext;
        private PHJJasperReportEngine thisEngine = new PHJJasperReportEngine();

        public MyResource(ExternalContext ec, String resourceName) {
            this.extContext = ec;
            this.resourceName = resourceName;
            this.lastModified = new Date();

        }

        /**
         * This intermediate step of reading in the files from the JAR, into a
         * byte array, and then serving the Resource from the ByteArrayInputStream,
         * is not strictly necessary, but serves to illustrate that the Resource
         * content need not come from an actual file, but can come from any source,
         * and also be dynamically generated. In most cases, applications need not
         * provide their own concrete implementations of Resource, but can instead
         * simply make use of com.icesoft.faces.context.ByteArrayResource,
         * com.icesoft.faces.context.FileResource, com.icesoft.faces.context.JarResource.
         */
        public InputStream open() throws IOException {
            try {
                // getrequestservletpath retruns the page url
                // getRequestContextPath=/CourierSystem

                HttpServletRequest thisRequest=(HttpServletRequest) extContext.getRequest();
                sURL="http://"+thisRequest.getServerName()+":"+thisRequest.getServerPort()+extContext.getRequestContextPath();
                Map param = new HashMap();

                /***********************************************/
                /* THIS IS THE BIT YOU NEED TO CHANGE FOR YOUR */
                /* REPORT - Make sure the filename.jasper is in*/
                /* the same place as your icefaces pages       */
                /* lastly, make sure the SQL matches           */
                /***********************************************/

                String sReportFileName="RPTCUSTOMERJOBSUMMARY";
                String sSQL = "SELECT * FROM TBLCUSTOMERS";

                /************************************************/
                return new ByteArrayInputStream(thisEngine.iceFacesjasperReport(sURL, sSQL, sReportFileName, "application/pdf", param));

            } catch (Exception e) {

                System.out.println("Error " + e);
            }

            return null;
        }

        public String calculateDigest() {
            return resourceName;
        }

        public Date lastModified() {
            return lastModified;
        }

        public void withOptions(Options arg0) throws IOException {
        }

    }

And then add to the init()  phase of the page.

 try {
            FacesContext fc = FacesContext.getCurrentInstance();
            ExternalContext ec = fc.getExternalContext();
            pdfResource = new MyResource(ec, "report.pdf");

        } catch (Exception e) {
            e.printStackTrace();
        }

Bingo!

Advertisements

About Paul C

I am a Senior Java programmer/Web Technologies, Play in a band called Mandolin Monday, I have a cat and I live on a boat.

Posted on April 20, 2009, in Uncategorized. Bookmark the permalink. 12 Comments.

  1. Hi,

    great post and very well explained, it did the job for me

    thanx again

  2. great post and very well explained,i have a problem
    how make to refresh the report

  3. Great post! Is it possible to do for NON Visual Web Project?
    I need to call it from a button and not from the init

    Thanks

  4. Francisco Piragibe

    I’ve just run into a similar problem (rendering a JASPERREPORT from an ice:commandButton). Placing a in the navigation rule, inside faces-config.xml, did the trick for me. There’s an issue remaining, though: the page with the button continues to be displayed, although no control is really there. If the user presses any button, or tries any action, the blank page behind the report gets shown. For me, this is a minor issue, once the application menu is always there and working, but it can be a real hindrance to others. So, it’s still work in progress.

  5. Francisco Piragibe

    The redirect tag has been removed from my previous comment. So, please read “Placing a redirect tag in the navigation rule” instead of “Placing a in the navigation rule”, ok?

  6. Yogaraj Khanal

    I am try to follow your approach but I am not sure where i am doing wrong.Do you have any suggestions looking at my code?

    The code works fine without custom handler but i am not able to lazily load the resource.Any feedback is appreciated.

    /*
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    */
    package gov.fda.oim.ccm.ui;

    import gov.fda.oim.ccm.common.backing.BaseBackingBean;
    import gov.fda.oim.ccm.domain.Communication;
    import java.io.InputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import net.sf.jasperreports.engine.JRException;
    import javax.faces.context.FacesContext;
    import net.sf.jasperreports.engine.JREmptyDataSource;
    import net.sf.jasperreports.engine.JRExporterParameter;
    import net.sf.jasperreports.engine.JasperFillManager;
    import net.sf.jasperreports.engine.JasperPrint;
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import com.icesoft.faces.context.ByteArrayResource;
    import com.icesoft.faces.context.Resource;
    import gov.fda.oim.ccm.domain.Amendment;
    import gov.fda.oim.ccm.domain.Category;
    import gov.fda.oim.ccm.domain.Participant;
    import gov.fda.oim.ccm.domain.Telecon;
    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.Serializable;
    import java.text.Format;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import javax.faces.context.ExternalContext;
    import net.sf.jasperreports.engine.export.JRTextExporter;
    import net.sf.jasperreports.engine.export.JRTextExporterParameter;

    /**
    *
    * @author xuey
    */
    public class IRATemplateBackingBean {

    private final Log logger = LogFactory.getLog(this.getClass());
    public static final String RESOURCE_PATH = “/WEB-INF/report/”;
    private Resource wordResourceForIra;

    public Resource getWordResourceForIra() {
    return wordResourceForIra;
    }

    public IRATemplateBackingBean() {

    try {
    FacesContext fc = FacesContext.getCurrentInstance();
    ExternalContext ec = fc.getExternalContext();
    wordResourceForIra = new CcmIraTemplateResource(ec, ” “);

    } catch (Exception e) {
    e.printStackTrace();
    }
    }

    public static byte[] toByteArray(InputStream input) throws IOException {

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    byte[] buf = new byte[4096];
    int len = 0;
    while ((len = input.read(buf)) > -1) {
    output.write(buf, 0, len);
    }
    return output.toByteArray();
    }
    }

    class CcmIraTemplateResource extends BaseBackingBean implements Resource, Serializable {

    private final Log logger = LogFactory.getLog(this.getClass());
    private String resourceName = “ccmtest.jasper”;
    private InputStream inputStream;
    private final Date lastModified;
    private ExternalContext extContext;
    private IRACommunicationBackingBean iraCommunicationBackingBean;

    public IRACommunicationBackingBean getIraCommunicationBackingBean() {
    return iraCommunicationBackingBean;
    }

    public void setIraCommunicationBackingBean(IRACommunicationBackingBean iraCommunicationBackingBean) {
    this.iraCommunicationBackingBean = iraCommunicationBackingBean;
    }

    public CcmIraTemplateResource(ExternalContext ec, String resourceName) {
    this.extContext = ec;
    this.resourceName = resourceName;
    this.lastModified = new Date();
    }

    public InputStream open() throws IOException {
    if (inputStream == null) {
    InputStream stream = extContext.getResourceAsStream(IRATemplateBackingBean.RESOURCE_PATH + resourceName);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    HashMap parameters = new HashMap();
    parameters.put(“SubType”, “SubType”);
    parameters.put(“SubId”, “SubId”);
    try {
    JasperPrint jasperPrint = JasperFillManager.fillReport(stream, parameters, new JREmptyDataSource());
    JRTextExporter exporter = new JRTextExporter();
    exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
    exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);
    exporter.exportReport();
    } catch (JRException ex) {
    Logger.getLogger(CcmIraTemplateResource.class.getName()).log(Level.SEVERE, null, ex);
    }
    byte[] byteArray = IRATemplateBackingBean.toByteArray(stream);
    inputStream = new ByteArrayInputStream(byteArray);
    }
    return null;
    }

    public Resource getWordResourceForIra() throws JRException, FileNotFoundException, IOException {
    logger.debug(“IRATemplateBackingBean->getDownloadRtfForIra”);
    System.out.println(“IRATemplateBackingBean->getDownloadRtfForIra”);
    FacesContext context = FacesContext.getCurrentInstance();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    try {
    InputStream reportStream = context.getExternalContext().getResourceAsStream(“/WEB-INF/report/CCM_IRA_TEMP.jasper”);
    this.iraCommunicationBackingBean = (IRACommunicationBackingBean) this.getManagedBean(“iraCommunicationBackingBean”);
    Communication comm = iraCommunicationBackingBean.getCommDetails();
    Telecon tel = (Telecon) comm;
    String submissionType = comm.getSubmission().getSubmissionType();
    String submissionID = comm.getSubmission().getSubmissionID();
    String reviewOffice = comm.getSubmission().getReviewOffice();
    logger.debug(“$$$$$IRATemplateBackingBean->getDownloadRtfForIra->reviewOffice:\t” + reviewOffice);
    String iraTitle = comm.getSubmission().getProduct().getTitle();
    String sponsorNameFirstPart = comm.getSubmission().getSponsor().getName();
    String sponsorNameSecondIndiTitle = comm.getSubmission().getSponsor().getIndividualtitle();
    String sponsorNameThirdPart = comm.getSubmission().getSponsor().getName2();
    String sponsorName = null;
    if (sponsorNameFirstPart != null) {
    sponsorName = sponsorNameFirstPart;
    } else if (sponsorNameFirstPart != null && sponsorNameSecondIndiTitle != null) {
    sponsorName = sponsorNameFirstPart + ” – ” + sponsorNameSecondIndiTitle;
    } else if (sponsorNameFirstPart != null && sponsorNameSecondIndiTitle != null && sponsorNameThirdPart != null) {
    sponsorName = sponsorNameFirstPart + ” – ” + sponsorNameSecondIndiTitle + ” ” + sponsorNameThirdPart;
    }
    logger.debug(“$$$$$IRATemplateBackingBean->getDownloadRtfForIra->sponsorName:\t” + sponsorName);
    Date teleconDateTime = tel.getTeleconDateTime();
    Format formatter;
    formatter = new SimpleDateFormat(“dd-MMM-yyyy HH:mm a”);
    String formatedDate = formatter.format(teleconDateTime);
    logger.debug(“***Format Date using simple date fomat***********” + formatedDate);
    String fdaInitiated = tel.getFdaOriginated();
    String telNo = comm.getSubmission().getSponsor().getContactPhone();
    String author = comm.getAuthor().getFirstName() + ” ” + comm.getAuthor().getLastName();
    String teleconSummary = comm.getSummary();
    String fdapart = null;
    List fdaParticipants = new ArrayList();
    List listFdaPart = tel.getFdaParticipants();
    for (Participant participant : listFdaPart) {
    String tmpString = null;
    tmpString = participant.getFirstName() + ” ” + participant.getLastName();
    logger.debug(“IRATemplateBackingBean->getDownloadRtfForIra->fda participant:\t” + tmpString);
    fdaParticipants.add(tmpString);
    StringBuilder sb = new StringBuilder();
    for (String tmpStr : fdaParticipants) {
    sb.append(“\n” + tmpStr);
    }
    fdapart = sb.toString();
    }

    String nonfdapart = null;
    List nonFda = new ArrayList();
    List listNonFdaPart = tel.getNonFdaParticipants();
    for (Participant participant : listNonFdaPart) {
    String tmpString = null;
    tmpString = participant.getFirstName() + ” ” + participant.getLastName();
    logger.debug(“IRATemplateBackingBean->getDownloadRtfForIra->non fda participant:\t” + tmpString);
    nonFda.add(tmpString);
    StringBuilder sb = new StringBuilder();
    for (String tmpStr : nonFda) {
    sb.append(“\n” + tmpStr);
    }
    nonfdapart = sb.toString();
    }
    logger.debug(“*********Final String********:\t” + nonfdapart);
    String categoryComm = null;
    List commCat = new ArrayList();
    List listCat = comm.getCommunicationCategories();
    int i = 1;
    for (Category category : listCat) {
    logger.debug(“IRATemplateBackingBean->getDownloadRtfForIra->cat desc:\t” + category.getDesc());
    String tmpString = null;
    tmpString = (i + “. “) + category.getDesc();
    if (category.getCd().equalsIgnoreCase(“OT”) || category.getCd().equalsIgnoreCase(“UO”)) {
    tmpString = tmpString + ” – ” + category.getOtherComments();
    }
    commCat.add(tmpString);
    StringBuilder sb = new StringBuilder();
    for (String tmpStr : commCat) {
    sb.append(“\n” + tmpStr);
    }
    categoryComm = sb.toString();
    i++;
    }
    logger.debug(“*********Final String********:\t” + categoryComm);

    String amendmentRef = null;
    List refAmend = new ArrayList();
    List amendList = comm.getSubmission().getAmendments();

    for (Amendment amendment : amendList) {
    String tmpString = null;
    tmpString = amendment.getAmendmentNbr() + “-” + amendment.getDescription();
    logger.debug(“IRATemplateBackingBean->getDownloadRtfForIra->amendment no and desc:\t” + tmpString);
    refAmend.add(tmpString);
    StringBuilder sb = new StringBuilder();
    for (String tmpStr : refAmend) {
    sb.append(“\n” + tmpStr);
    }
    amendmentRef = sb.toString();
    }
    logger.debug(“*********Final String********:\t” + amendmentRef);
    HashMap parameters = new HashMap();
    parameters.put(“CCM_IRA_TEMP”, “RECORD OF TELEPHONE CONVERSATION”);
    parameters.put(“submissionType”, submissionType);
    parameters.put(“submissionID”, submissionID);
    parameters.put(“reviewOffice”, reviewOffice);
    parameters.put(“iraTitle”, iraTitle);
    parameters.put(“sponsorName”, sponsorName);
    parameters.put(“teleconDateTime”, formatedDate);
    parameters.put(“fdaInitiated”, fdaInitiated);
    parameters.put(“telNo”, telNo);
    parameters.put(“commCat”, categoryComm);
    parameters.put(“author”, author);
    parameters.put(“teleconSummary”, teleconSummary);
    parameters.put(“fdaParticipants”, fdapart);
    parameters.put(“nonFda”, nonfdapart);
    parameters.put(“refAmend”, amendmentRef);
    JasperPrint jasperPrint = JasperFillManager.fillReport(reportStream, parameters, new JREmptyDataSource());
    JRTextExporter exporter = new JRTextExporter();
    exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
    exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);
    exporter.setParameter(JRTextExporterParameter.PAGE_HEIGHT, new Integer(55));
    exporter.setParameter(JRTextExporterParameter.PAGE_WIDTH, new Integer(80));
    exporter.setParameter(JRTextExporterParameter.CHARACTER_WIDTH, new Integer(8));
    exporter.setParameter(JRTextExporterParameter.CHARACTER_HEIGHT, new Integer(19));
    exporter.exportReport();
    } catch (Exception ex) {
    ex.printStackTrace();
    }
    return new ByteArrayResource(baos.toByteArray());
    }

    public String calculateDigest() {
    return resourceName;
    }

    public Date lastModified() {
    return lastModified;
    }

    public void withOptions(Options arg0) throws IOException {
    throw new UnsupportedOperationException(“Not supported yet.”);
    }
    }

  7. Hi Great post! but not work in my project when push button generate this error
    javax.servlet.ServletException: PWC1244: La ejecución del servlet desencadenó una excepción

    Causa principal
    java.lang.NoClassDefFoundError: org/springframework/core/io/Resource

    I have Netbeans 6.5, Icefase 1.8 and Ireport 3.0.1

  8. Thanks for the post. Please is it possible to use this tutorial with the woodstock visual web jsf component or is still the same . please if different what part of the code needs to be changed? thanks in advance…

  9. Great post, thank you very much!!

  10. Wow thanks finally it worked for me.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: