skip to content

Using a JSP to write out binary data

June 7, 2006

I’ve downloaded this Java charting package called jFreeChart, which I want to use to generate some custom charts in Oracle Portal. Yes I know there’s supposed to be some cool Oracle BI charts built right in, but when I went thru the wizard it apparently requires an OLAP data source. We’re not working with an OLAP cube so I struck out with the Oracle BI components.

The “right” way to do this would probably be to create a servlet using jFreeChart, but I’m having a hellish time getting jDeveloper and Portal to play nice when building and deploying WAR files. So I figured I’d use Portal’s nice and easy custom JSP feature, which lets you load a JSP and then call it thru a standard Portal url with standard security applied.

I know, a JSP is supposed to be all about spitting out text–HTML, XML, maybe even a CSV file or something like that. But desperate times call for desperate measures, so for now I’m going to use the JSP and see what happens.

The first problem is of course that the standard “out” object in a JSP is a JspWriter, it’s not an OutputStream. It only knows how to spit out chars, not bytes. So there’s no way to stream back the JPEG’s I’m creating.

Turns out you can access the original response.out object. You just need to make sure and do it before your JSP has a chance to spit out any HTML because at that point the out has become a JspWriter and you’re toast.

So here’s the code I ended up with for my little “Hello, World” chart JSP:

< %@ page contentType="image/jpeg"
import="java.io.*,
org.jfree.data.general.*,
org.jfree.chart.*"
%>< %
OutputStream o = response.getOutputStream();

DefaultPieDataset pieDataset = new DefaultPieDataset();
pieDataset.setValue("Love it", new Integer(40));
pieDataset.setValue("Hate it", new Integer(40));
pieDataset.setValue("Websphere Rules", new Integer(20));

JFreeChart chart = ChartFactory.createPieChart
("Oracle Portal Poll", // Title
pieDataset, // Dataset
true, // Show legend
true, // tooltips
false
);

ChartUtilities.writeChartAsJPEG( o, (float) .9, chart, 300, 200);
%>

Leave a comment