1 /*
2 * Copyright 2004 the original author or authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package com.nordija.tapestry.bayeux.stream.jfreechart;
17
18 import com.nordija.tapestry.bayeux.stream.StreamResource;
19 import org.jfree.chart.ChartUtilities;
20 import org.jfree.chart.JFreeChart;
21 import org.jfree.chart.encoders.ImageFormat;
22
23 import java.io.ByteArrayOutputStream;
24 import java.io.IOException;
25 import java.io.OutputStream;
26
27 /**
28 * This abstract class implements the {@link #writeTo(java.io.OutputStream)} method so you don't have to concentrate
29 * on how to stream the actual chart.
30 * Use this if you are about to stream a JFreeChart.
31 * @author Jacob von Eyben - Nordija A/S
32 */
33 public abstract class JFreeChartResource implements StreamResource {
34
35 private JFreeChart chart;
36
37 public JFreeChartResource(JFreeChart chart) {
38 this.chart = chart;
39 }
40
41 /**
42 * <p>The image format of the chart. Can be one of the following:<br />
43 * {@link ImageFormat#JPEG} or {@link ImageFormat#PNG}</p>
44 *
45 * @return a image format for the chart
46 */
47 public abstract String getImageFormat();
48
49
50 /**
51 * The width of the streamed chart
52 *
53 * @return the width
54 */
55 public abstract int getWidth();
56
57 /**
58 * The height of the streamed chart
59 *
60 * @return the height
61 */
62 public abstract int getHeight();
63
64 public void writeTo(OutputStream out) throws IOException {
65 ByteArrayOutputStream stream = new ByteArrayOutputStream();
66 if (ImageFormat.PNG.equalsIgnoreCase(getImageFormat())) {
67 ChartUtilities.writeChartAsPNG(stream, chart, getWidth(), getHeight());
68 } else if (ImageFormat.JPEG.equalsIgnoreCase(getImageFormat())) {
69
70 ChartUtilities.writeChartAsJPEG(stream, chart, getWidth(), getHeight());
71 }
72 out.write(stream.toByteArray());
73 }
74
75 /**
76 * Returns the content type matching the defined image format returned by {@link #getImageFormat()}
77 *
78 * @return the content type for the jfree chart
79 */
80 public String getContentType() {
81 return "image/" + getImageFormat();
82 }
83 }