Monday, February 22, 2010

BIRT and Struts 2

BIRT offers several ways reports can be deployed. The AJAX based BIRT viewer can be deployed to your application server, the BIRT tag libraries can be used or you can deploy the Report Engine in your application. You can also modify any of the above options, given that the source is available for download. Several commercial options are also available. This post explains deploying the BIRT engine as an Action component within Struts2. It also discusses using Actuate’s JSAPI with Struts 2’s Bean tag.

BIRT Engine Deployed to Struts 2

The BIRT report engine can be deployed as a Servlet and the process for doing this is described in the BIRT wiki.

If you happen to be using Struts 2 as your application framework you can deploy the Report Engine as an Action component. The process for doing this is not much different than the Servlet approach described in the above link. First you have to implement the ActionSupport class.



package org.birt.struts2;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import org.apache.struts2.util.ServletContextAware;
import org.apache.struts2.interceptor.ServletRequestAware;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import com.opensymphony.xwork2.ActionSupport;
public class BirtStruts2 extends ActionSupport implements ServletContextAware, ServletRequestAware {

private ByteArrayInputStream inputStream;

public ByteArrayInputStream getInputStream() {
return inputStream;
}
private HttpServletRequest request;
public void setServletRequest(HttpServletRequest request) {
this.request = request;
}
private ServletContext context;
public void setServletContext(ServletContext context) {
this.context = context;
}
public String execute() throws Exception {

RunBirt rb = new RunBirt();
inputStream = new ByteArrayInputStream(rb.runReport(this.context, this.request));

return SUCCESS;
}

}


In this example we are going to create a RunBirt class that will return the report in a byte array. The above BirtStruts2 class extends the ActionSupport class and implements ServletContextAware and ServletRequestAware. The reason we implement the two extra interfaces is that the RunBirt class will need the ServletContext and the Request object. The BirtStruts2 class also has an inputStream member that is used by the Struts 2 framework to handle the returned report. The struts.config file is as follows:

<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="BirtStruts2" extends="struts-default">
<action name="BirtStruts2" class="org.birt.struts2.BirtStruts2">
<result type="stream">
<param name="contentType">text/html</param>
<param name="inputName">inputStream</param>
</result>
</action>
</package>
</struts>

The result for the BirtStruts2 action is set to stream, the content type is set to html, and the inputStream variable from our BirtStruts2 class is set as the inputName stream result parameter. You will need to change the contentType if you plan on altering the example to return PDF, XLS, or Word.

The RunBirt class is similar to the WebReport class described in the Wiki example.



public byte[] runReport(ServletContext sc, HttpServletRequest req) throws ServletException{

this.birtReportEngine = BirtEngine.getBirtEngine(sc);

IReportRunnable design;
try
{
//Open report design
design = birtReportEngine.openReportDesign( sc.getRealPath("/Reports/TopNPercent.rptdesign") );
//create task to run and render report
IRunAndRenderTask task = birtReportEngine.createRunAndRenderTask( design );
task.getAppContext().put(EngineConstants.APPCONTEXT_CLASSLOADER_KEY, RunBirt.class.getClassLoader());
//task.getAppContext().put("BIRT_VIEWER_HTTPSERVLET_REQUEST", req );
if( req.getParameter("TopCount") != null ){
task.setParameterValue("Top Count", Integer.valueOf(req.getParameter("TopCount")));
}
if( req.getParameter("TopPercentage") != null ){
task.setParameterValue("Top Percentage", Float.valueOf(req.getParameter("TopPercentage")));
}
//set output options
HTMLRenderOption options = new HTMLRenderOption();
options.setOutputFormat(HTMLRenderOption.OUTPUT_FORMAT_HTML);
ByteArrayOutputStream oStream = new ByteArrayOutputStream();
options.setOutputStream(oStream);
options.setImageHandler(new HTMLServerImageHandler());
options.setBaseImageURL(req.getContextPath()+"/images");
options.setImageDirectory(sc.getRealPath("/images"));
task.setRenderOption(options);


//run report
task.run();
task.close();
return oStream.toByteArray();

}catch (Exception e){

e.printStackTrace();
throw new ServletException( e );
}
}
}





If you have used the BIRT Report Engine API there is nothing unique in this example for Struts 2. The report name is hard-coded but could easily be changed to be set as a parameter. The HTML render options are setup to write to a ByteArrayOutputStream which is then converted to a byte array and returned the BirtStruts2 class.


HTMLRenderOption options = new HTMLRenderOption();
options.setOutputFormat(HTMLRenderOption.OUTPUT_FORMAT_HTML);
ByteArrayOutputStream oStream = new ByteArrayOutputStream();
options.setOutputStream(oStream);
options.setImageHandler(new HTMLServerImageHandler());
options.setBaseImageURL(req.getContextPath()+"/images");
options.setImageDirectory(sc.getRealPath("/images"));
task.setRenderOption(options);


The images directory and base URL (pre-pended to the img src tag in the output) are also set based on the passed in ServletContext and Request objects. The only other class is the BirtEngine class which is desribed in the Wiki example but is shown here for completeness. This class provides static synchronized method to return the ReportEngine.



package org.birt.struts2;
import javax.servlet.ServletContext;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.birt.report.engine.api.EngineConstants;
import org.eclipse.birt.report.engine.api.HTMLRenderOption;
import org.eclipse.birt.report.engine.api.IReportRunnable;
import org.eclipse.birt.report.engine.api.IRunAndRenderTask;
import org.eclipse.birt.report.engine.api.IReportEngine;
import org.eclipse.birt.report.engine.api.HTMLServerImageHandler;
import org.eclipse.birt.report.engine.api.PDFRenderOption;
import org.eclipse.birt.report.engine.api.RenderOption;
import java.io.ByteArrayOutputStream;

public class RunBirt{
private IReportEngine birtReportEngine = null;

package org.birt.struts2;

import java.io.InputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;

import org.eclipse.birt.report.engine.api.EngineConfig;
import org.eclipse.birt.report.engine.api.IReportEngine;
import javax.servlet.*;
import org.eclipse.birt.core.framework.PlatformServletContext;
import org.eclipse.birt.core.framework.IPlatformContext;
import org.eclipse.birt.core.framework.Platform;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.report.engine.api.IReportEngineFactory;
import org.eclipse.birt.report.engine.api.ReportEngine;
import javax.servlet.http.HttpServletRequest;

public class BirtEngine {

private static IReportEngine birtEngine = null;

private static Properties configProps = new Properties();

private final static String configFile = "BirtConfig.properties";

public static synchronized void initBirtConfig() {
loadEngineProps();
}

public static synchronized IReportEngine getBirtEngine(ServletContext sc) {
if (birtEngine == null)
{
EngineConfig config = new EngineConfig();
if( configProps != null){
String logLevel = configProps.getProperty("logLevel");
Level level = Level.OFF;
if ("SEVERE".equalsIgnoreCase(logLevel))
{
level = Level.SEVERE;
} else if ("WARNING".equalsIgnoreCase(logLevel))
{
level = Level.WARNING;
} else if ("INFO".equalsIgnoreCase(logLevel))
{
level = Level.INFO;
} else if ("CONFIG".equalsIgnoreCase(logLevel))
{
level = Level.CONFIG;
} else if ("FINE".equalsIgnoreCase(logLevel))
{
level = Level.FINE;
} else if ("FINER".equalsIgnoreCase(logLevel))
{
level = Level.FINER;
} else if ("FINEST".equalsIgnoreCase(logLevel))
{
level = Level.FINEST;
} else if ("OFF".equalsIgnoreCase(logLevel))
{
level = Level.OFF;
}

config.setLogConfig(configProps.getProperty("logDirectory"), level);
}
config.getAppContext().put(EngineConstants.APPCONTEXT_CLASSLOADER_KEY, BirtEngine.class.getClassLoader());
config.setEngineHome("");

IPlatformContext context = new PlatformServletContext( sc );
config.setPlatformContext( context );

try
{
Platform.startup( config );
}
catch ( BirtException e )
{
e.printStackTrace( );
}

IReportEngineFactory factory = (IReportEngineFactory) Platform
.createFactoryObject( IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY );
birtEngine = factory.createReportEngine( config );


}
return birtEngine;
}

public static synchronized void destroyBirtEngine() {
if (birtEngine == null) {
return;
}
birtEngine.destroy();
Platform.shutdown();
birtEngine = null;
}




To call this code you can implement a page similar to the following:

<html>
<head>
</head>
<body>
<s:form action="/BirtStruts2.action" method="POST">
<s:textfield name="TopCount" label="Top Count"/><br>
<s:textfield name="TopPercentage" label="Top Percentage"/><br>
<s:submit value="Run Report" align="center"/>
</s:form>
</body>
</html>

This example has very little error checking for brevity. Also note that the report engine should be shutdown using a context listener, but should not be shutdown while the context is up and running as starting the engine is resource intensive. Finally no code is provided in the example to remove image files that are generated by the engine in the images directory.

The complete example with ant build and a readme that describes where to put the BIRT plugins and libs is available at Birt-Exchange.

Example Output:



Using Actuate’s JSAPI with Struts 2
If you are using Actuate’s JSAPI, integration with Struts 2 is very easy as the API is AJAX based and can be included in virtually any front-end. One interesting way the two technologies can be deployed together is to use the Struts 2 Bean tag to pass parameters to the JSAPI. For example assume we have the following bean class.



package com.actuate.jsapi.struts2;

public class MyRegionBean {

private String region;
private String rep;

public String getRegion(){
//expecting rep passed in and region lookup in db
//based on the rep. Hard coded for example purposes
this.region = "EMEA";
return region;
}
public void setRegion(String nRegion ){
this.region = nRegion;
}
public String getRep(){
return rep;
}
public void setRep(String nRep ){
this.rep = nRep;
}
}




This bean can be used in conjunction with the JSAPI to pass report parameters to the Report Engine.

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JSAPI Struts 2</title>
</head>
<body>

<div id="acviewer" />
<div id="jsapi_example_container">
<script type="text/javascript"
src="http://localhost:8080/ActuateJavaComponent/jsapi">
</script>

<script type="text/javascript">
actuate.load("viewer");
actuate.initialize("http://localhost:8080/ActuateJavaComponent/",
null,
null,
null,
initViewer);
var viewer;
function initViewer()
{
viewer = new actuate.Viewer("acviewer");
var viewerwidth = 800;
var viewerheight = 620;
viewer.setWidth(viewerwidth);
viewer.setHeight(viewerheight);
runInitial();
}
function runInitial()
{
<s:bean name="com.actuate.jsapi.struts2.MyRegionBean">
<s:param name="rep" value="John Smith" />
viewer.setParameters({"Territory":"<s:property value="region" />"});
</s:bean>
viewer.setReportName("/Public/BIRT and BIRT Report Studio Examples/Sales by Territory.rptdesign");
viewer.submit();

}
</script>
</div>

</body>
</html>

In the runInitial JavaScript function the viewer components setParameters method is called passing the value of the bean’s region member variable as the value for the Territory report parameter.

More information is available on the JSAPI here.

The example is available at Birt-Exchange.

Output for this example is as follows:

6 comments:

Bubbly's World said...

hello all...
i hav developed application by the instructions given in this post..
but m getting error..

INFO: Detected AnnotationActionValidatorManager, initializing it...
org.eclipse.birt.core.exception.BirtException: Cant startup the OSGI framework
at org.eclipse.birt.core.framework.Platform.startup(Platform.java:91)
at org.birt.struts2.BirtEngine.getBirtEngine(BirtEngine.java:78)
at org.birt.struts2.RunBirt.runReport(RunBirt.java:26)
at org.birt.struts2.BirtStruts2.execute(BirtStruts2.java:31)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at
plz help in this..


Thanx in advance..

Jason Weathersby said...

Does the generated
birtstruts2.war contain the WEB-INF/Platform/plugins folder? Does this folder have any plugins? The error you are getting implies that it does not exist or is empty.

Jason

Amit said...

Hi Jason

I mention contentType as PDF in struts.xml ...


but it could not generate PDF file

plz help in this

Jason Weathersby said...

What version are you using?
BTW did you setup a PDFRenderOption ?

Jason

Unknown said...

Hii , i implement this tutorial in my project . i have getting error in build.xml . Please give me Idea/Suggestion of this error how to solve it .

Raj Sharma said...

Struts Interview Questions Answers