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:

Thursday, February 18, 2010

BIRT Controls and Functions - Update

We have updated the BIRT Functions and BIRT Controls libraries today to support versions 2.3.2 and 2.5.1.  Turns out that there were some minor changes that needed to be addressed.  In addition, we did a bit of work to make the naming and version numbering more consistent.

The biggest question I faced was how to do the version numbering for these plugins.  As they stand, they are sub components to BIRT, which as a very specific version scheme.  We thought about using version numbers that did not track BIRT versions at all.  But then I started writing the documentation.

If you are using BIRT 2.3.2 then you should use 1.0.1 of the BIRT Controls...
Started to feel more like "you put your left foot in, ...".  I think that there is a lot of value in making developers write the documentation.  When you write your own docs, you quickly figure out when things that you have come to accept are really more difficult then they should be.

Rather than write a bunch of hokey pokey build instructions, we decided to generate the components one more time using version numbers that will be easy for the component consumers.  So it may not follow the Eclipse version number guidelines, but it is easy for our clients.

And easy for our clients is my number one goal.
BIRT Controls and BIRT Functions version guidelines.
If you are using BIRT 2.3.2, then use version 2.3.2.X of our components.
If you are using BIRT 2.5.1, then use version 2.5.1.X of our components.  

Also along the easy = good theme.  I wanted to share how much I enjoy working with Google Code.  I know that the Eclipse foundation is talking about doing some form of easy to use Eclipse Foundry type site, but in the absence of details on what is going on there, I went with Google.  It has been very easy to create a project, with all the trappings a small project needs.

  • Home Page check
  • Wiki check
  • Issue Tracking check
  • Version Control (SVN or Hg) check
  • Downloads check
  • Update Site check (right out of the the SVN repository)
  • Administration and Security check
Makes me wonder if the foundation really needs to create our own infrastructure to manage a foundry. Perhaps there is a way to leverage an existing code foundry and focus on creating a great migration path from the foundry to the Eclipse infrastructure.

The other thing that I really love are the market places that I can use to get the word out about these controls. As a small company, we don't have a huge marketing staff (any marketing).  So having not one but two great outlets that help us get the word out about our component is super helpful.  Thanks again to


Enough rambling, I have to go write some docs...

Thursday, February 11, 2010

BIRT Crosstab scripting

BIRT supplies scripting hooks for just about every report element in the palette. You can generally implement an onPrepare, onCreate, and onRender event handler for each of these report items. The onPrepare event fires before data is retrieved and allows you to change the design for a specific report item. The onCreate event fires when the report item is being created by the report engine’s generation task. The onRender event fires when the report item is being rendered by the report engine’s render task. These events and example are described on the BIRT website.

Some report items offer more event hooks. For example a chart item actually has over thirty event hooks that allow total customization of the chart generation and presentation phases. As a side note, all chart scripts fire during the report engine’s render task. This does not mean the database is hit at render time though. The report engine will cache the data for a chart in memory or in a report document, depending on what task type is being used to run and render the report.

The BIRT crosstab element offers onPrepare, onCreate and onRender hooks as well. These events are fired both for the crosstab as a whole and for each individual cell in the crosstab. When firing events for cells, these are processed top to bottom and left to right. Handlers can be written using the script tab at the bottom of the report design view. BIRT also supplies an event adapter to allow you to write these events in Java as well.



As an example script, you can modify the crosstab in the onPrepare like:



function onPrepareCrosstab( crosstab, reportContext )
{
var coldim = crosstab.getColumnLevels().get(0);
coldim.removeAllFilterConditions();
crosstab.getStyle().setFontFamily("Arial");
crosstab.getStyle().setFontSize("8");

}



This script removes filters from the first column level and sets some font information. Some of the more interesting capabilities are available when using the onCreateCell event hook. For example consider the following script.



function onCreateCell( cellInst, reportContext )
{

//Can reference cells by type or id - valid types "header" or "aggregation"
if( cellInst.getCellType() == "header" ) {
//Get data values see binding tab on crosstab
//if( cellInst.getDataValue("PRODUCTLINE") == "Planes" ){
if( reportContext.evaluate("dimension['ProductGroup']['PRODUCTLINE']") == "Planes" ){
cellInst.getStyle().setBackgroundColor("#FF0000");
cellInst.getStyle().setFontSize("12");
}else{
//Set the rest to yellow
cellInst.getStyle().setBackgroundColor("#FFFF00");
cellInst.getStyle().setFontSize("12");
}

}
//refer to crosstab header
if( cellInst.getCellID() == 167){
cellInst.getStyle().setBackgroundColor("Orange");
}
if( cellInst.getCellType() == "aggregation"){
//Can refernce value using getDataValue or
if( cellInst.getDataValue("PRODUCTLINE") == "Planes" ){
//set color to bluegray
cellInst.getStyle().setBackgroundColor("RGB(169,170,226)");
}
//by using reportContext.evaluate
//if( reportContext.evaluate("measure['amount']") > 50000 ){
if( cellInst.getDataValue("amount_DateGroup/quarter_ProductGroup/PRODUCTLINE") > 50000 ){
cellInst.getStyle().setBackgroundColor("Green");
cellInst.getStyle().setColor("White");
}
}
}



The onCreateCell script is passed the reportContext and an instance of the cell. The cellInst object has several methods that can be used to determine which cell is currently being processed. You can call getCellType() which will return header or aggregation. In the following image all cells in the red box will return aggregation and all others will return header.



You can also call getCellID() which will return the specific element id that your crosstab uses for that cell.



In this example the getCellID call will return 160 every time this cell is created. This can be useful when you are trying to determine if you have a new row or column in your crosstab. If this is the innermost header element then this cell will be created for every new row/column. The only drawback to this approach is that if the crosstab is in a library or you copy and paste it, the cell ids will change.

Once you know the cell you are currently processing you generally want to access the data, to make some script decision. To do this you have a couple of choices. You can call the getDataValue method on the cell instance or use the reportContext.evaluate method. When using the getDataValue method, the value you need to refer to is the data binding column name set on the crosstab item. For example:


cellInst.getDataValue("PRODUCTLINE") == "Planes"


refers to the PRODUCTLINE data binding. Also note that this is the value of the column as this particular cell is being processed.



You can also use the reportContext.evaluate method, which allows you to build an expression and bypass the binding. For example:


if( reportContext.evaluate("dimension['ProductGroup']['PRODUCTLINE']") == "Planes" )

Essentially returns the same value as the previous getDataValue(“PRODUCTLINE”) method. This is because the PRODUCTLINE data binding has:

dimension['ProductGroup']['PRODUCTLINE']


As it’s expression. This example references a particular dimension of the cube. You can reference cube measures as well.

reportContext.evaluate("measure['amount']")


As with the column binding this will return the value for the specific cell you are currently processing.

In the script posted at the top of this post, we use the cell instance object to set specific styling based on the values of various column bindings. This is done using the getStyle method.


cellInst.getStyle().setBackgroundColor("Green");
cellInst.getStyle().setColor("White");


Using this method is no different than other BIRT report items.

Using these methods and the reportContext you can write some very sophisticated scripts. For example you can store all the quantities ordered where the product line is ships to a global variable using a script similar to this:



if( cellInst.getCellType() == "aggregation" && cellInst.getCellID() == 151){
if( cellInst.getDataValue("PRODUCTLINE") == "Ships" ){
importPackage(Packages.java.lang );
var cur = cellInst.getDataValue("amount_DateGroup/quarter_ProductGroup/PRODUCTLINE");
if( reportContext.getGlobalVariable("totalplanes")==null){
reportContext.setGlobalVariable("totalplanes", new Double(Double.parseDouble(cur)) );
}else{
var oldcnt = reportContext.getGlobalVariable("totalplanes");
reportContext.setGlobalVariable("totalplanes", new Double(Double.parseDouble(oldcnt) + Double.parseDouble(cur)));
}
}
}



This value can then be referenced within the same crosstab or later in the report. For example the following expression for a text item can be used.

<VALUE-OF format="#,##0.00">reportContext.getGlobalVariable("totalplanes");</VALUE-OF>

This example can also be implemented in Java. In the attached link the report will contain two crosstabs. One where the code is done in JavaScript and the other uses an event handler written in Java, which is also attached.

The example report output is presented below.



The examples are available at Birt-Exchange.

Tuesday, February 02, 2010

Remus Uses BIRT

I read about the Remus project on Planet Eclipse today and was intrigued.   Looking at the draft project proposal:

With today's information technologies, the amount of information we consume daily is enormous. Efficient management and fast access to frequently used information has become more important than ever. The fact that we use a wide range of applications and digital mediums makes the aggregation of information, search and retrieval even more difficult. Managing a huge amount of information successfully requires an intelligent tool that enables users to file, categorize and visualize such diverse types of data as information units in a single application.
And now I am very intrigued, my company Innovent Solutions works in this very space.  Naturally, I wondered about how BIRT could interact with Remus.  Turns out that they have created an ODA for BIRT and have bundled some reports.  

Looks like another nice use of BIRT.