01: /*
02: * Copyright (c) 2002-2003 by OpenSymphony
03: * All rights reserved.
04: */
05: /*
06: * Created on Sep 20, 2003
07: *
08: * To change the template for this generated file go to
09: * Window - Preferences - Java - Code Generation - Code and Comments
10: */
11: package com.opensymphony.webwork.dispatcher;
12:
13: import com.opensymphony.webwork.ServletActionContext;
14: import com.opensymphony.xwork.ActionInvocation;
15: import com.opensymphony.xwork.Result;
16: import org.jfree.chart.ChartUtilities;
17: import org.jfree.chart.JFreeChart;
18:
19: import javax.servlet.http.HttpServletResponse;
20: import java.io.OutputStream;
21:
22: /**
23: * A custom Result type for chart data. Built on top of
24: * <a href="http://www.jfree.org/jfreechart/" target="_blank">JFreeChart</a>. When executed
25: * this Result will write the given chart as a PNG to the servlet output stream.
26: *
27: * @author Bernard Choi
28: */
29: public class ChartResult implements Result {
30:
31: JFreeChart chart;
32: boolean chartSet = false;
33: private int height;
34: private int width;
35:
36: /**
37: * Sets the JFreeChart to use.
38: *
39: * @param chart a JFreeChart object.
40: */
41: public void setChart(JFreeChart chart) {
42: this .chart = chart;
43: chartSet = true;
44: }
45:
46: /**
47: * Sets the chart height.
48: *
49: * @param height the height of the chart in pixels.
50: */
51: public void setHeight(int height) {
52: this .height = height;
53: }
54:
55: /**
56: * Sets the chart width.
57: *
58: * @param width the width of the chart in pixels.
59: */
60: public void setWidth(int width) {
61: this .width = width;
62: }
63:
64: /**
65: * Executes the result. Writes the given chart as a PNG to the servlet output stream.
66: *
67: * @param invocation an encapsulation of the action execution state.
68: * @throws Exception if an error occurs when creating or writing the chart to the servlet output stream.
69: */
70: public void execute(ActionInvocation invocation) throws Exception {
71: JFreeChart chart = null;
72:
73: if (chartSet) {
74: chart = this .chart;
75: } else {
76: chart = (JFreeChart) invocation.getStack().findValue(
77: "chart");
78: }
79:
80: if (chart == null) {
81: throw new NullPointerException("No chart found");
82: }
83:
84: HttpServletResponse response = ServletActionContext
85: .getResponse();
86: OutputStream os = response.getOutputStream();
87: ChartUtilities.writeChartAsPNG(os, chart, width, height);
88: os.flush();
89: }
90: }
|