BIRT is an eclipse based reporting tool which produces a .rptdesign file. To view this .rptdesign file as a HTML file, it must be run through the BIRT engine.

There are two ways of doing this, one is through the BIRT viewer engine and the other is through the BIRT runtime engine. Both these methods can be integrated into a web application but both have their pros and cons.

BIRT Viewer Engine – This method generates the report with relative ease and less programming and can print the report in multiple formats such as PDF, JPG, EXCEL, CSV, etc. But, the interface is fixed and may not merge seamlessly with the web applications interface.

BIRT Runtime Engine – This method requires a lot more coding for setting up and giving print functionality (apart from PDF and HTML), but this can be integrated perfectly as a part of the web application and look and feel as a part of the application itself.

Downloads:

1. Download the BIRT runtime engine from Eclipse download page : http://www.eclipse.org/downloads/download.php?file=/birt/downloads/drops/R-R1-4_5_0-201506092134/birt-runtime-4.5.0-20150609.zip

2. Postgres driver jar (for example)(**Download the driver for your database)) : http://www.java2s.com/Code/Jar/p/Downloadpostgres340jar.htm

3. Java Sevlet API jar: http://www.java2s.com/Code/Jar/s/Downloadservletjar.htm

Setup:

1. Unzip the Birt Runtime engine and place it in some easily accessible location.

2. Open eclipse and set up a ‘Dynamic Web Project’.

3. Add all jars from ‘\birt-runtime\birt-runtime-4_5_0\ReportEngine\lib’ into ‘WEB-INF\lib’ of your eclipse project.

4. Add servlet.jar and postgresql.jar in ‘WEB-INF\lib’ of your eclipse project.

Code:

BirtFunctions.java : (java class)

These are all the functions used by the main controller

importjava.io.File;

import java.io.IOException;

import java.util.HashMap;

import java.util.Iterator;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.eclipse.birt.report.engine.api.EngineConfig;

import org.eclipse.birt.report.engine.api.EngineConstants;

importorg.eclipse.birt.report.engine.api.HTMLRenderContext;

import org.eclipse.birt.report.engine.api.HTMLRenderOption;

import org.eclipse.birt.report.engine.api.HTMLServerImageHandler;

import org.eclipse.birt.report.engine.api.IRenderOption;

import org.eclipse.birt.report.engine.api.IReportRunnable;

import org.eclipse.birt.report.engine.api.IRunAndRenderTask;

import org.eclipse.birt.report.engine.api.PDFRenderOption;

import org.eclipse.birt.report.engine.api.RenderOption;

import org.eclipse.birt.report.engine.api.ReportEngine;

import org.json.JSONException;

import org.json.JSONObject;

import com.helical.efw.export.TempDirectoryCleaner;

import com.helical.efw.singleton.ApplicationProperties;

import com.sun.research.ws.wadl.Request;

import net.sf.json.JSONSerializer;

publicclass BirtFuntions {

// Convert the String of parameters to a HashMap of parameters

// by sending the String to BirtFunctions.Str2Map()

publicstatic Map<String, Object> getInput(String parameters) throws JSONException {

Map<String, Object> paramMap = Str2Map(parameters);

returnparamMap;

}

// Str2Map(String), Accepts a String as the parameters.

// If String is null, returns an empty HashMap,

// Else Converts the string to JSONObject and puts the

// JSONObject in the map and returns this HashMap.

publicstatic Map<String, Object> Str2Map(String parameters) throws JSONException {

Map<String, Object> paramMap = null;

// Check if parameters(String) is empty

if ((“null”.equals(parameters)) || (parameters == null) || (“”.equals(parameters))) {

// Create a new empty HashMap

paramMap = new HashMap();

}

// If parameters(String) contains data

else {

// Convert String to JSONObject

JSONObject jsonParameters = new JSONObject(parameters);

// Convert JSONObject to Map

paramMap = BirtJsonFunctions.jsonToMap(jsonParameters);

}

// Return the hashMap.

returnparamMap;

}

// Set response Header

publicstatic HttpServletResponse setResponseHeader(HttpServletResponse response, String type, String headerValue,

Map<String, String> contentTypesMap) {

Iterator<Map.Entry<String, String>> iterator = contentTypesMap.entrySet().iterator();

while (iterator.hasNext()) {

Map.Entry<String, String> entry = (Map.Entry) iterator.next();

if ((!“html”.equals(type)) && (((String) entry.getKey()).equals(type))) {

response.setContentType((String) entry.getValue());

response.setHeader(“Content-Disposition”, headerValue);

}

iterator.remove();

}

returnresponse;

}

// Report Rendering

publicstaticvoid renderReport(String birtSource, Map<String, Object> paramMap, HttpServletRequest request, HttpServletResponse response,

String type) throws IOException {

EngineConfig conf = null;

ReportEngine eng = null;

IReportRunnable design = null;

IRunAndRenderTask task = null;

HTMLRenderContext renderContext = null;

HashMap<String, HTMLRenderContext> contextMap = null;

IRenderOption options = null;

// Now, setup the BIRT engine configuration. The Engine Home is

// hardcoded

// here, this is probably better set in an environment variable or in

// a configuration file. No other options need to be set

conf = new EngineConfig();

conf.setEngineHome(“D:/birt-runtime/birt-runtime-4_5_0/ReportEngine”);

//conf.setEngineHome(System.getenv(“BIRT_HOME”));

// Create new Report engine based off of the configuration

eng = new ReportEngine(conf);

// With our new engine, lets try to open the report design

try {

design = eng.openReportDesign(birtSource);

} catch (Exception e) {

System.err.println(“An error occured during the opening of the report file!”);

e.printStackTrace();

System.exit(-1);

}

// With the file open, create the Run and Render task to run the report

task = eng.createRunAndRenderTask(design);

//set Image Directory

String imgDirectory = TempDirectoryCleaner.getTempDirectory().getAbsolutePath();

String url = request.getRequestURL().toString();

String baseURL = url.substring(0, url.length() – request.getRequestURI().length()) + request.getContextPath();

// Set Render context to handle url and image locations, and apply to

// the task

renderContext = newHTMLRenderContext();

renderContext.setImageDirectory(imgDirectory);

renderContext.setBaseImageURL(baseURL+<path to your temp directory>);

contextMap = new HashMap();

contextMap.put(EngineConstants.APPCONTEXT_HTML_RENDER_CONTEXT, renderContext);

task.setAppContext(contextMap);

// Set parameter values and validate

task.setParameterValues(paramMap);

// This will set the output file location, the format to render to, and

// apply to the task

options = BirtFuntions.selectRenderer(type);

options.setOutputStream(response.getOutputStream());

if(“pdf”.equalsIgnoreCase(type)){

options.setOutputFormat(“pdf”);

response.setContentType(“application/pdf”);

}

elseif(“html”.equalsIgnoreCase(type)){

options.setImageHandle(new HTMLServerImageHandler());

response.setContentType(“text/html”);

options.setOutputFormat(“html”);

}

task.setRenderOption(options);

// Cross our fingers and hope everything is set

try {

task.run();

} catch (Exception e) {

System.err.println(“An error occured while running the report!”);

e.printStackTrace();

System.exit(-1);

}

// Yeah, we finished. Now destroy the engine and let the garbage

// collector do its thing

System.out.println(“All went well. Closing program!”);

eng.destroy();

}

publicstatic IRenderOption selectRenderer(String type) {

IRenderOption options = null;

if (“pdf”.equalsIgnoreCase(type)) {

options = new PDFRenderOption();

} elseif (“html”.equalsIgnoreCase(type))

options = new HTMLRenderOption();

returnoptions;

}

}

BirtJsonFunctions.java: (java class)

This is used for converting JSON string (parameters) input into a Hashmap for the BIRT runtime engine.

import java.util.ArrayList;

import java.util.HashMap;

import java.util.Iterator;

import java.util.List;

import java.util.Map;

import org.json.JSONArray;

import org.json.JSONException;

import org.json.JSONObject;

publicclassBirtJsonFunctions {

publicstatic Map<String, Object> jsonToMap(JSONObject json) throws JSONException {

Map<String, Object> retMap = new HashMap<String, Object>();

if(json != JSONObject.NULL) {

retMap = toMap(json);

}

returnretMap;

}

publicstatic Map<String, Object> toMap(JSONObject object) throws JSONException {

Map<String, Object> map = new HashMap<String, Object>();

Iterator<String> keysItr = object.keys();

Object[] values = null;

while(keysItr.hasNext()) {

String key = keysItr.next();

Object value = object.get(key);

if(valueinstanceof JSONArray) {

value = toList((JSONArray) value);

}

elseif(valueinstanceof JSONObject) {

value = toMap((JSONObject) value);

}

//In case of multi-select, the value

//should be Object[].

//NOT ArrayList

if (valueinstanceof ArrayList){

values = ((List<Object>) value).toArray(new Object[((List<Object>) value).size()]);

map.put(key,values);

}

else

map.put(key, value);

}

returnmap;

}

publicstatic List<Object> toList(JSONArray array) throws JSONException {

List<Object> list = new ArrayList<Object>();

for(inti = 0; i < array.length(); i++) {

Object value = array.get(i);

if(valueinstanceof JSONArray) {

value = toList((JSONArray) value);

}

elseif(valueinstanceof JSONObject) {

value = toMap((JSONObject) value);

}

list.add(value);

}

returnlist;

}

}

BirtPluginController: (servlet)

This is the main controller to initiate the report visualization. It accepts 3 main parameters from the calling function(form) – “type”: html or pdf ; “file”: the location of the .rptdesign file; “parameters”: JSON string containing the parameters.

import java.io.File;

import java.io.IOException;

import java.util.Map;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RequestParam;

import com.helical.efw.singleton.ApplicationProperties;

import com.helical.efw.utility.PropertiesFileReader;

/**

* Servlet implementation class BirtServlet

*/

@Controller

publicclass BirtPluginController extends HttpServlet {

privatestaticfinallongserialVersionUID = 1L;

@RequestMapping(value = { “/birtReports” }, method = { RequestMethod.POST, RequestMethod.GET })

publicvoid generateReport(@RequestParam(“type”) String type, @RequestParam(“file”) String birtSource,

@RequestParam(“parameters”) String birtParameters, HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException, JSONException {

// Create a Hash Map of Parameters For BirtRuntime

Map<String, Object> paramMap = BirtFuntions.getInput(birtParameters);

// Create the Path of source file

ApplicationProperties applicationProperties = ApplicationProperties.getInstance();

birtSource = applicationProperties.getSolutionDirectory() + \ + birtSource;

String headerValue = String.format(“attachment; filename=\”%s\””,

new Object[] { System.currentTimeMillis() + “.” + type });

PropertiesFileReader reader = new PropertiesFileReader();

Map<String, String> contentTypesMap = reader.read(“reports.properties”);

// Set Response Header Based on Type

response = BirtFuntions.setResponseHeader(response, type, headerValue, contentTypesMap);

// Open Report

BirtFuntions.renderReport(birtSource, paramMap, request, response, type);

}

}

Hope this helpful to you. If there are any issues being faced, please drop a message.

Leave a Reply