Click here to close now.




















Welcome!

Java IoT Authors: Carmen Gonzalez, Liz McMillan, Elizabeth White, Cloud Best Practices Network, Dana Gardner

Related Topics: Java IoT, IoT User Interface

Java IoT: 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
All major researchers estimate there will be tens of billions devices - computers, smartphones, tablets, and sensors - connected to the Internet by 2020. This number will continue to grow at a rapid pace for the next several decades. With major technology companies and startups seriously embracing IoT strategies, now is the perfect time to attend @ThingsExpo, November 3-5, 2015, at the Santa Clara Convention Center in Santa Clara, CA. Learn what is going on, contribute to the discussions, and ensure that your enterprise is as "IoT-Ready" as it can be.
With the Apple Watch making its way onto wrists all over the world, it’s only a matter of time before it becomes a staple in the workplace. In fact, Forrester reported that 68 percent of technology and business decision-makers characterize wearables as a top priority for 2015. Recognizing their business value early on, FinancialForce.com was the first to bring ERP to wearables, helping streamline communication across front and back office functions. In his session at @ThingsExpo, Kevin Roberts, GM of Platform at FinancialForce.com, will discuss the value of business applications on wearable ...
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.
Containers are not new, but renewed commitments to performance, flexibility, and agility have propelled them to the top of the agenda today. By working without the need for virtualization and its overhead, containers are seen as the perfect way to deploy apps and services across multiple clouds. Containers can handle anything from file types to operating systems and services, including microservices. What are microservices? Unlike what the name implies, microservices are not necessarily small, but are focused on specific tasks. The ability for developers to deploy multiple containers – thous...
SYS-CON Events announced today that Micron Technology, Inc., a global leader in advanced semiconductor systems, will exhibit at the 17th International Cloud Expo®, which will take place on November 3–5, 2015, at the Santa Clara Convention Center in Santa Clara, CA. Micron’s broad portfolio of high-performance memory technologies – including DRAM, NAND and NOR Flash – is the basis for solid state drives, modules, multichip packages and other system solutions. Backed by more than 35 years of technology leadership, Micron's memory solutions enable the world's most innovative computing, consumer,...
As more intelligent IoT applications shift into gear, they’re merging into the ever-increasing traffic flow of the Internet. It won’t be long before we experience bottlenecks, as IoT traffic peaks during rush hours. Organizations that are unprepared will find themselves by the side of the road unable to cross back into the fast lane. As billions of new devices begin to communicate and exchange data – will your infrastructure be scalable enough to handle this new interconnected world?
While many app developers are comfortable building apps for the smartphone, there is a whole new world out there. In his session at @ThingsExpo, Narayan Sainaney, Co-founder and CTO of Mojio, will discuss how the business case for connected car apps is growing and, with open platform companies having already done the heavy lifting, there really is no barrier to entry.
SYS-CON Events announced today that the "Second Containers & Microservices Expo" will take place November 3-5, 2015, at the Santa Clara Convention Center in Santa Clara, CA. Containers and microservices have become topics of intense interest throughout the cloud developer and enterprise IT communities.
Consumer IoT applications provide data about the user that just doesn’t exist in traditional PC or mobile web applications. This rich data, or “context,” enables the highly personalized consumer experiences that characterize many consumer IoT apps. This same data is also providing brands with unprecedented insight into how their connected products are being used, while, at the same time, powering highly targeted engagement and marketing opportunities. In his session at @ThingsExpo, Nathan Treloar, President and COO of Bebaio, will explore examples of brands transforming their businesses by t...
WebRTC services have already permeated corporate communications in the form of videoconferencing solutions. However, WebRTC has the potential of going beyond and catalyzing a new class of services providing more than calls with capabilities such as mass-scale real-time media broadcasting, enriched and augmented video, person-to-machine and machine-to-machine communications. In his session at @ThingsExpo, Luis Lopez, CEO of Kurento, will introduce the technologies required for implementing these ideas and some early experiments performed in the Kurento open source software community in areas ...
Akana has announced the availability of the new Akana Healthcare Solution. The API-driven solution helps healthcare organizations accelerate their transition to being secure, digitally interoperable businesses. It leverages the Health Level Seven International Fast Healthcare Interoperability Resources (HL7 FHIR) standard to enable broader business use of medical data. Akana developed the Healthcare Solution in response to healthcare businesses that want to increase electronic, multi-device access to health records while reducing operating costs and complying with government regulations.
The Internet of Things is in the early stages of mainstream deployment but it promises to unlock value and rapidly transform how organizations manage, operationalize, and monetize their assets. IoT is a complex structure of hardware, sensors, applications, analytics and devices that need to be able to communicate geographically and across all functions. Once the data is collected from numerous endpoints, the challenge then becomes converting it into actionable insight.
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...
WebRTC has had a real tough three or four years, and so have those working with it. Only a few short years ago, the development world were excited about WebRTC and proclaiming how awesome it was. You might have played with the technology a couple of years ago, only to find the extra infrastructure requirements were painful to implement and poorly documented. This probably left a bitter taste in your mouth, especially when things went wrong.
The 3rd International WebRTC Summit, to be held Nov. 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA, announces that its Call for Papers is now open. Topics include all aspects of improving IT delivery by eliminating waste through automated business models leveraging cloud technologies. WebRTC Summit is co-located with 15th International Cloud Expo, 6th International Big Data Expo, 3rd International DevOps Summit and 2nd Internet of @ThingsExpo. WebRTC (Web-based Real-Time Communication) is an open source project supported by Google, Mozilla and Opera that aims to enable bro...
Through WebRTC, audio and video communications are being embedded more easily than ever into applications, helping carriers, enterprises and independent software vendors deliver greater functionality to their end users. With today’s business world increasingly focused on outcomes, users’ growing calls for ease of use, and businesses craving smarter, tighter integration, what’s the next step in delivering a richer, more immersive experience? That richer, more fully integrated experience comes about through a Communications Platform as a Service which allows for messaging, screen sharing, video...
The 17th International Cloud Expo has announced that its Call for Papers is open. 17th International Cloud Expo, to be held November 3-5, 2015, at the Santa Clara Convention Center in Santa Clara, CA, brings together Cloud Computing, APM, APIs, Microservices, Security, Big Data, Internet of Things, DevOps and WebRTC to one location. With cloud computing driving a higher percentage of enterprise IT budgets every year, it becomes increasingly important to plant your flag in this fast-expanding business opportunity. Submit your speaking proposal today!
In his session at @ThingsExpo, Lee Williams, a producer of the first smartphones and tablets, will talk about how he is now applying his experience in mobile technology to the design and development of the next generation of Environmental and Sustainability Services at ETwater. He will explain how M2M controllers work through wirelessly connected remote controls; and specifically delve into a retrofit option that reverse-engineers control codes of existing conventional controller systems so they don't have to be replaced and are instantly converted to become smart, connected devices.
SYS-CON Events announced today that IceWarp will exhibit at the 17th International Cloud Expo®, which will take place on November 3–5, 2015, at the Santa Clara Convention Center in Santa Clara, CA. IceWarp, the leader of cloud and on-premise messaging, delivers secured email, chat, documents, conferencing and collaboration to today's mobile workforce, all in one unified interface
SYS-CON Events announced today the Containers & Microservices Bootcamp, being held November 3-4, 2015, in conjunction with 17th Cloud Expo, @ThingsExpo, and @DevOpsSummit at the Santa Clara Convention Center in Santa Clara, CA. This is your chance to get started with the latest technology in the industry. Combined with real-world scenarios and use cases, the Containers and Microservices Bootcamp, led by Janakiram MSV, a Microsoft Regional Director, will include presentations as well as hands-on demos and comprehensive walkthroughs.