Click here to close now.

Welcome!

Java Authors: Carmen Gonzalez, Liz McMillan, Pat Romanski, Elizabeth White, AppDynamics Blog

Related Topics: Java, AJAX & REA

Java: Blog Feed Post

BIRT and Struts 2

BIRT offers several ways reports can be deployed

Java Developer Magazine on Ultizer

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:

Read the original blog entry...

More Stories By Jason Weathersby

Jason Weathersby is a member of the extended BIRT development team at Actuate Corporation and has backgrounds in both computer science and technical writing. He has many years experience in technical consulting, training, writing, and publishing about reporting, business intelligence tools, and database technologies.

@ThingsExpo Stories
Sensor-enabled things are becoming more commonplace, precursors to a larger and more complex framework that most consider the ultimate promise of the IoT: things connecting, interacting, sharing, storing, and over time perhaps learning and predicting based on habits, behaviors, location, preferences, purchases and more. In his session at @ThingsExpo, Tom Wesselman, Director of Communications Ecosystem Architecture at Plantronics, will examine the still nascent IoT as it is coalescing, including what it is today, what it might ultimately be, the role of wearable tech, and technology gaps stil...
The explosion of connected devices / sensors is creating an ever-expanding set of new and valuable data. In parallel the emerging capability of Big Data technologies to store, access, analyze, and react to this data is producing changes in business models under the umbrella of the Internet of Things (IoT). In particular within the Insurance industry, IoT appears positioned to enable deep changes by altering relationships between insurers, distributors, and the insured. In his session at @ThingsExpo, Michael Sick, a Senior Manager and Big Data Architect within Ernst and Young's Financial Servi...
17th Cloud Expo, taking place Nov 3-5, 2015, at the Santa Clara Convention Center in Santa Clara, CA, will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud strategy. Meanwhile, 94% of enterprises are using some form of XaaS – software, platform, and infrastructure as a service.
The Workspace-as-a-Service (WaaS) market will grow to $6.4B by 2018. In his session at 16th Cloud Expo, Seth Bostock, CEO of IndependenceIT, will begin by walking the audience through the evolution of Workspace as-a-Service, where it is now vs. where it going. To look beyond the desktop we must understand exactly what WaaS is, who the users are, and where it is going in the future. IT departments, ISVs and service providers must look to workflow and automation capabilities to adapt to growing demand and the rapidly changing workspace model.
Since 2008 and for the first time in history, more than half of humans live in urban areas, urging cities to become “smart.” Today, cities can leverage the wide availability of smartphones combined with new technologies such as Beacons or NFC to connect their urban furniture and environment to create citizen-first services that improve transportation, way-finding and information delivery. In her session at @ThingsExpo, Laetitia Gazel-Anthoine, CEO of Connecthings, will focus on successful use cases.
One of the biggest impacts of the Internet of Things is and will continue to be on data; specifically data volume, management and usage. Companies are scrambling to adapt to this new and unpredictable data reality with legacy infrastructure that cannot handle the speed and volume of data. In his session at @ThingsExpo, Don DeLoach, CEO and president of Infobright, will discuss how companies need to rethink their data infrastructure to participate in the IoT, including: Data storage: Understanding the kinds of data: structured, unstructured, big/small? Analytics: What kinds and how responsiv...
Building low-cost wearable devices can enhance the quality of our lives. In his session at Internet of @ThingsExpo, Sai Yamanoor, Embedded Software Engineer at Altschool, provided an example of putting together a small keychain within a $50 budget that educates the user about the air quality in their surroundings. He also provided examples such as building a wearable device that provides transit or recreational information. He then reviewed the resources available to build wearable devices at home including open source hardware, the raw materials required and the options available to power s...
With major technology companies and startups seriously embracing IoT strategies, now is the perfect time to attend @ThingsExpo in Silicon Valley. Learn what is going on, contribute to the discussions, and ensure that your enterprise is as "IoT-Ready" as it can be! Internet of @ThingsExpo, taking place Nov 3-5, 2015, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 17th Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The Internet of Things (IoT) is the most profound change in personal an...
DevOps tends to focus on the relationship between Dev and Ops, putting an emphasis on the ops and application infrastructure. But that’s changing with microservices architectures. In her session at DevOps Summit, Lori MacVittie, Evangelist for F5 Networks, will focus on how microservices are changing the underlying architectures needed to scale, secure and deliver applications based on highly distributed (micro) services and why that means an expansion into “the network” for DevOps.
How do APIs and IoT relate? The answer is not as simple as merely adding an API on top of a dumb device, but rather about understanding the architectural patterns for implementing an IoT fabric. There are typically two or three trends: Exposing the device to a management framework Exposing that management framework to a business centric logic Exposing that business layer and data to end users. This last trend is the IoT stack, which involves a new shift in the separation of what stuff happens, where data lives and where the interface lies. For instance, it's a mix of architectural styles ...
The 3rd International @ThingsExpo, co-located with the 16th International Cloud Expo – to be held June 9-11, 2015, at the Javits Center in New York City, NY – is now accepting Hackathon proposals. Hackathon sponsorship benefits include general brand exposure and increasing engagement with the developer ecosystem. At Cloud Expo 2014 Silicon Valley, IBM held the Bluemix Developer Playground on November 5 and ElasticBox held the DevOps Hackathon on November 6. Both events took place on the expo floor. The Bluemix Developer Playground, for developers of all levels, highlighted the ease of use of...
We’re no longer looking to the future for the IoT wave. It’s no longer a distant dream but a reality that has arrived. It’s now time to make sure the industry is in alignment to meet the IoT growing pains – cooperate and collaborate as well as innovate. In his session at @ThingsExpo, Jim Hunter, Chief Scientist & Technology Evangelist at Greenwave Systems, will examine the key ingredients to IoT success and identify solutions to challenges the industry is facing. The deep industry expertise behind this presentation will provide attendees with a leading edge view of rapidly emerging IoT oppor...
Connected devices and the Internet of Things are getting significant momentum in 2014. In his session at Internet of @ThingsExpo, Jim Hunter, Chief Scientist & Technology Evangelist at Greenwave Systems, examined three key elements that together will drive mass adoption of the IoT before the end of 2015. The first element is the recent advent of robust open source protocols (like AllJoyn and WebRTC) that facilitate M2M communication. The second is broad availability of flexible, cost-effective storage designed to handle the massive surge in back-end data in a world where timely analytics is e...
We certainly live in interesting technological times. And no more interesting than the current competing IoT standards for connectivity. Various standards bodies, approaches, and ecosystems are vying for mindshare and positioning for a competitive edge. It is clear that when the dust settles, we will have new protocols, evolved protocols, that will change the way we interact with devices and infrastructure. We will also have evolved web protocols, like HTTP/2, that will be changing the very core of our infrastructures. At the same time, we have old approaches made new again like micro-services...
SYS-CON Events announced today that Gridstore™, the leader in hyper-converged infrastructure purpose-built to optimize Microsoft workloads, will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. Gridstore™ is the leader in hyper-converged infrastructure purpose-built for Microsoft workloads and designed to accelerate applications in virtualized environments. Gridstore’s hyper-converged infrastructure is the industry’s first all flash version of HyperConverged Appliances that include both compute and storag...
For years, we’ve relied too heavily on individual network functions or simplistic cloud controllers. However, they are no longer enough for today’s modern cloud data center. Businesses need a comprehensive platform architecture in order to deliver a complete networking suite for IoT environment based on OpenStack. In his session at @ThingsExpo, Dhiraj Sehgal from PLUMgrid will discuss what a holistic networking solution should really entail, and how to build a complete platform that is scalable, secure, agile and automated.
The industrial software market has treated data with the mentality of “collect everything now, worry about how to use it later.” We now find ourselves buried in data, with the pervasive connectivity of the (Industrial) Internet of Things only piling on more numbers. There’s too much data and not enough information. In his session at @ThingsExpo, Bob Gates, Global Marketing Director, GE’s Intelligent Platforms business, to discuss how realizing the power of IoT, software developers are now focused on understanding how industrial data can create intelligence for industrial operations. Imagine ...
Hadoop as a Service (as offered by handful of niche vendors now) is a cloud computing solution that makes medium and large-scale data processing accessible, easy, fast and inexpensive. In his session at Big Data Expo, Kumar Ramamurthy, Vice President and Chief Technologist, EIM & Big Data, at Virtusa, will discuss how this is achieved by eliminating the operational challenges of running Hadoop, so one can focus on business growth. The fragmented Hadoop distribution world and various PaaS solutions that provide a Hadoop flavor either make choices for customers very flexible in the name of opti...
In the consumer IoT, everything is new, and the IT world of bits and bytes holds sway. But industrial and commercial realms encompass operational technology (OT) that has been around for 25 or 50 years. This grittier, pre-IP, more hands-on world has much to gain from Industrial IoT (IIoT) applications and principles. But adding sensors and wireless connectivity won’t work in environments that demand unwavering reliability and performance. In his session at @ThingsExpo, Ron Sege, CEO of Echelon, will discuss how as enterprise IT embraces other IoT-related technology trends, enterprises with i...
Wearable devices have come of age. The primary applications of wearables so far have been "the Quantified Self" or the tracking of one's fitness and health status. We propose the evolution of wearables into social and emotional communication devices. Our BE(tm) sensor uses light to visualize the skin conductance response. Our sensors are very inexpensive and can be massively distributed to audiences or groups of any size, in order to gauge reactions to performances, video, or any kind of presentation. In her session at @ThingsExpo, Jocelyn Scheirer, CEO & Founder of Bionolux, will discuss ho...