Why/when do you need a Scripted data set in a BIRT report?
Existing tables in your database will not provide data in the way you need them in a report. You might have to query more than one table to get all the data, or you may want to do some computation which requires going through one table data more than once.
What scripting language can be used?
Javascript is the primary language to be used in BIRT. BIRT also uses the
Mozilla Rhino JavaScript engine which provides excellent integration with Java, hence you can use Java libraries as well but with a Javascript like syntax.
How to do it?
-
Create a global variable: declare the variable in the initialize event of the report
For example:
importPackage(Packages.java.util.*);
globalVarMap = new java.util.HashMap();
globalVarList = new java.util.ArrayList();
-
Populate this variable with required data: Typically you would read a simple dataset and dump all the data in this global map with the primary key (or maybe some other value) of the table being the key of the hashmap. The necessary code goes in
'onFetch' event (method) of the dataset, and a table column is referred to as
'row["CUSTOMER_ID"]'. The onFetch event is called once per each table record, hence you get access to table data one record at a time.
For example:
var list = globalVarMap.get(row["CUSTOMER_ID"]);;
if(list == null) {
list = new java.util.ArrayList();
}
var data={};
data.customer_name = row["CUSTOMER_NAME"];
data.product_bought = row["PRODUCT_BOUGHT"];
data.price = row["PRICE"];
list.add(data);
globalVarMap.put(row["CUSTOMER_ID"], list);
Here the CUSTOMER_ID is not the primary key, and we are just sorting of various items bought by each customer.
-
Create a scripted data set: The final step is to create a scripted data set with the required columns and use global variables like the one above to populate this data set. Since you have the necessary data in a bunch of global variables, you can do pretty much what you want. The necessary code goes in
'fetch' event (method) of the dataset.
if(customerCount < globalVarList.size()){
var data = globalVarList.get(customerCount);
row["CUSTOMER_ID"] = data.customer_id;
row["CUSTOMER_NAME"] = data.customer_name;
row["PRODUCT_ID"] =data.product_id;
row["TOTAL_PURCHASE"] = data.total_purchase;
row["QUARTER"] = data.quarter;
row["COUNTRY"] = data.country;
customerCount++;
return true;
}
return false;
Here, we have the necessary data in a global list variable and we just have to populate the scripted data set. In the fetch method we return true to indicate that there is more data coming, and false to indicate that we are done.
Additional Info
BIRT/FAQ/Scripting
BIRT Java Reporting