Java

Deploying BIRT Report Engine API with Jakarta Struts

After reading the great article Deploying BIRT from Jason Weathersby I decide to create a little example on how to use BIRT RE API with Jakarta Struts framework.

To do so I’ve followed Jason steps:

  1. Create a WebReport/WEB-INF/lib directory underneath the Tomcat webapps directory.
  2. Copy all the jars in the birt-runtime-2_1_0/ReportEngine/lib directory from the Report Engine download into your WebReport/WEB-INF/lib directory.
  3. Next, create a directory named platform in your WEB-INF folder.
  4. Copy the birt-runtime-2_1_0/Report Engine/plugins and birt-runtime-2_1_0/ReportEngine/configuration directories to the platform directory you just created. In this example the context is WebReport, so the folder structure is /webapps/WebReport/platform/plugins and webapps/WebReport/platform/configuration.
  5. Additionally, create directories below WebReport for image location and report location.

and used the same directory structure:

WebReport directory structure

The example allows you to generate reports in HTML, PDF, and XLS formats. For the last one I’ve used Tribix XLS Emitter.

To get more information about how to use XLS emitter with BIRT Report Engine API please read the README file that comes with in the binary distribution.

The following files are mean to replace the WebReportServlet class from Jason example.
Go to the Resources section to get the instructions on how to get this example source code.
The source code has been updated so you can easily embed the report’s HTML in your JSP pages and correctly render your images and charts in your HTML.

BirtInitializationPlugin.java

Struts Plugin to BIRT Report Engine initialization and shutdown.


/*
 * $Id$
 *
 * Last changed on : $Date$
 * Last changed by : $Author$
 */
package com.samaxes.webreport.plugin;

import javax.servlet.ServletException;

import org.apache.struts.action.ActionServlet;
import org.apache.struts.action.PlugIn;
import org.apache.struts.config.ModuleConfig;

import com.samaxes.webreport.birt.BirtEngine;

/**
 * BIRT Report Engine initialization and shutdown Plugin.
 *
 * @author : samaxes
 * @version : $Revision$
 */
public class BirtInitializationPlugin implements PlugIn {

    /**
     * Initialization of the servlet. <br />
     *
     * @param servlet ActionServlet
     * @param conf ModuleConfig
     * @throws ServletException if an error occure
     */
    public void init(ActionServlet servlet, ModuleConfig conf) throws ServletException {
        BirtEngine.initBirtConfig();
    }

    /**
     * Destruction of the servlet.
     */
    public void destroy() {
        BirtEngine.destroyBirtEngine();
    }

}

WebReportAction.java

Actions related to the reports generation.


/*
 * $Id$
 *
 * Last changed on : $Date$
 * Last changed by : $Author$
 */
package com.samaxes.webreport.action;

import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.MappingDispatchAction;
import org.eclipse.birt.report.engine.api.EngineConstants;
import org.eclipse.birt.report.engine.api.HTMLRenderContext;
import org.eclipse.birt.report.engine.api.HTMLRenderOption;
import org.eclipse.birt.report.engine.api.IReportEngine;
import org.eclipse.birt.report.engine.api.IReportRunnable;
import org.eclipse.birt.report.engine.api.IRunAndRenderTask;

import com.samaxes.webreport.birt.BirtEngine;
import com.samaxes.webreport.common.Constants;

/**
 * Actions related to the reports generation.
 *
 * @author : samaxes
 * @version : $Revision$
 */
public class WebReportAction extends MappingDispatchAction {

    private IReportEngine birtReportEngine = null;

    protected static Logger logger = Logger.getLogger("org.eclipse.birt");

    /**
     * The html report action. <br />
     * Gets the report's html output stream.
     *
     * @param actionMapping ActionMapping
     * @param actionForm ActionForm
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @return ActionForward
     */
    public ActionForward htmlReportAction(ActionMapping actionMapping, ActionForm actionForm,
            HttpServletRequest request, HttpServletResponse response) {

        ByteArrayOutputStream out = new ByteArrayOutputStream();

        try {
            out = renderReportPage(request);
        } catch (ServletException e) {
            logger.log(Level.SEVERE, e.getMessage(), e);
        }

        request.setAttribute("reportHTML", out);

        return actionMapping.findForward(Constants.FORWARD_SUCCESS);
    }

    /**
     * Generates the html report.
     *
     * @param request HttpServletRequest
     * @return ByteArrayOutputStreamwith the report generated
     * @throws ServletException
     */
    private ByteArrayOutputStream renderReportPage(HttpServletRequest request) throws ServletException {

        // get report name and launch the engine
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        String reportName = request.getParameter("ReportName");
        ServletContext sc = request.getSession().getServletContext();
        this.birtReportEngine = BirtEngine.getBirtEngine(sc);

        // setup image directory
        HTMLRenderContext renderContext = new HTMLRenderContext();
        renderContext.setBaseImageURL(request.getContextPath() + "/images");
        renderContext.setImageDirectory(sc.getRealPath("/images"));

        logger.log(Level.FINE, "image directory " + sc.getRealPath("/images"));

        HashMap<string, HTMLRenderContext> contextMap = new HashMap<string, HTMLRenderContext>();
        contextMap.put(EngineConstants.APPCONTEXT_HTML_RENDER_CONTEXT, renderContext);

        IReportRunnable design;
        try {
            // Open report design
            design = birtReportEngine.openReportDesign(sc.getRealPath("/reports") + "/" + reportName);
            // create task to run and render report
            IRunAndRenderTask task = birtReportEngine.createRunAndRenderTask(design);
            task.setAppContext(contextMap);

            // set output options
            HTMLRenderOption options = new HTMLRenderOption();
            options.setOutputFormat(HTMLRenderOption.OUTPUT_FORMAT_HTML);
            options.setEmbeddable(true);
            options.setOutputStream(out);
            task.setRenderOption(options);

            // run report
            task.run();
            task.close();
        } catch (Exception e) {
            logger.log(Level.SEVERE, e.getMessage(), e);
            throw new ServletException(e);
        }
        return out;
    }

    /**
     * The pdf report action. <br />
     * Generates the pdf report.
     *
     * @param actionMapping ActionMapping
     * @param actionForm ActionForm
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @throws ServletException
     */
    public void pdfReportAction(ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest request,
            HttpServletResponse response) throws ServletException {

        // get report name and launch the engine
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "inline; filename=WebReport.pdf"); // inline, attachment
        String reportName = request.getParameter("ReportName");
        ServletContext sc = request.getSession().getServletContext();
        this.birtReportEngine = BirtEngine.getBirtEngine(sc);

        // setup image directory
        HTMLRenderContext renderContext = new HTMLRenderContext();
        renderContext.setBaseImageURL(request.getContextPath() + "/images");
        renderContext.setImageDirectory(sc.getRealPath("/images"));

        logger.log(Level.FINE, "image directory " + sc.getRealPath("/images"));

        HashMap<string, HTMLRenderContext> contextMap = new HashMap<string, HTMLRenderContext>();
        contextMap.put(EngineConstants.APPCONTEXT_HTML_RENDER_CONTEXT, renderContext);

        IReportRunnable design;
        try {
            // Open report design
            design = birtReportEngine.openReportDesign(sc.getRealPath("/reports") + "/" + reportName);
            // create task to run and render report
            IRunAndRenderTask task = birtReportEngine.createRunAndRenderTask(design);
            task.setAppContext(contextMap);

            // set output options
            HTMLRenderOption options = new HTMLRenderOption();
            options.setOutputFormat(HTMLRenderOption.OUTPUT_FORMAT_PDF);
            options.setOutputStream(response.getOutputStream());
            task.setRenderOption(options);

            // run report
            task.run();
            task.close();
        } catch (Exception e) {
            logger.log(Level.SEVERE, e.getMessage(), e);
            throw new ServletException(e);
        }
    }

    /**
     * The excel report action. <br />
     * Generates the excel report.
     *
     * @param actionMapping ActionMapping
     * @param actionForm ActionForm
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @throws ServletException
     */
    public void xlsReportAction(ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest request,
            HttpServletResponse response) throws ServletException {

        // get report name and launch the engine
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "inline; filename=WebReport.xls"); // inline, attachment
        String reportName = request.getParameter("ReportName");
        ServletContext sc = request.getSession().getServletContext();
        this.birtReportEngine = BirtEngine.getBirtEngine(sc);

        // setup image directory
        HTMLRenderContext renderContext = new HTMLRenderContext();
        renderContext.setBaseImageURL(request.getContextPath() + "/images");
        renderContext.setImageDirectory(sc.getRealPath("/images"));

        logger.log(Level.FINE, "image directory " + sc.getRealPath("/images"));

        HashMap<string, HTMLRenderContext> contextMap = new HashMap<string, HTMLRenderContext>();
        contextMap.put(EngineConstants.APPCONTEXT_HTML_RENDER_CONTEXT, renderContext);

        IReportRunnable design;
        try {
            // Open report design
            design = birtReportEngine.openReportDesign(sc.getRealPath("/reports") + "/" + reportName);
            // create task to run and render report
            IRunAndRenderTask task = birtReportEngine.createRunAndRenderTask(design);
            task.setAppContext(contextMap);

            // set output options
            HTMLRenderOption options = new HTMLRenderOption();
            options.setOutputFormat(Constants.XLS_FORMAT);
            options.setOutputStream(response.getOutputStream());
            task.setRenderOption(options);

            // run report
            task.run();
            task.close();
        } catch (Exception e) {
            logger.log(Level.SEVERE, e.getMessage(), e);
            throw new ServletException(e);
        }
    }

}

All you need to get this sample running is to copy the WAR file to your server deploy dir and configure the BIRT Report Engine logging in BirtConfig.properties file.


logDirectory=e:/Work/logs/birt
logLevel=CONFIG

If you are building the application from the source code you must also configure the application server deployment directory, rename the file build.properties-example to build.properties and edit the following line.


deploy.dir=E:/Work/jboss/server/default/deploy

Designing the report is out of the scoope of this article, you can found a lot of tutorials on the Web and BIRT Website.

Resources

Related Posts

22 Comments

speak up

Add your comment below, or trackback from your own site.

Subscribe to these comments.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*Required Fields