1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 package org.apache.struts2.dispatcher;
22
23 import org.apache.struts2.ServletActionContext;
24 import com.opensymphony.xwork2.ActionInvocation;
25 import com.opensymphony.xwork2.Result;
26 import org.jfree.chart.ChartUtilities;
27 import org.jfree.chart.JFreeChart;
28
29 import javax.servlet.http.HttpServletResponse;
30 import java.io.OutputStream;
31
32
33 /***
34 * A custom Result type for chart data. Built on top of
35 * <a href="http://www.jfree.org/jfreechart/" target="_blank">JFreeChart</a>. When executed
36 * this Result will write the given chart as a PNG to the servlet output stream.
37 *
38 */
39 public class ChartResult implements Result {
40
41 private static final long serialVersionUID = -6484761870055986612L;
42
43 JFreeChart chart;
44 boolean chartSet = false;
45 private int height;
46 private int width;
47
48 public ChartResult() {
49 super();
50 }
51
52 public ChartResult(JFreeChart chart, int height, int width) {
53 setChart(chart);
54 this.height = height;
55 this.width = width;
56 }
57
58 /***
59 * Sets the JFreeChart to use.
60 *
61 * @param chart a JFreeChart object.
62 */
63 public ChartResult setChart(JFreeChart chart) {
64 this.chart = chart;
65 chartSet = true;
66 return this;
67 }
68
69 /***
70 * Sets the chart height.
71 *
72 * @param height the height of the chart in pixels.
73 */
74 public ChartResult setHeight(int height) {
75 this.height = height;
76 return this;
77 }
78
79 /***
80 * Sets the chart width.
81 *
82 * @param width the width of the chart in pixels.
83 */
84 public ChartResult setWidth(int width) {
85 this.width = width;
86 return this;
87 }
88
89 /***
90 * Executes the result. Writes the given chart as a PNG to the servlet output stream.
91 *
92 * @param invocation an encapsulation of the action execution state.
93 * @throws Exception if an error occurs when creating or writing the chart to the servlet output stream.
94 */
95 public void execute(ActionInvocation invocation) throws Exception {
96 JFreeChart chart = null;
97
98 if (chartSet) {
99 chart = this.chart;
100 } else {
101 chart = (JFreeChart) invocation.getStack().findValue("chart");
102 }
103
104 if (chart == null) {
105 throw new NullPointerException("No chart found");
106 }
107
108 HttpServletResponse response = ServletActionContext.getResponse();
109 OutputStream os = response.getOutputStream();
110 ChartUtilities.writeChartAsPNG(os, chart, width, height);
111 os.flush();
112 }
113 }