KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > pentaho > plugin > jfreechart > ChartComponent


1 /*
2  * Copyright 2006 Pentaho Corporation. All rights reserved.
3  * This software was developed by Pentaho Corporation and is provided under the terms
4  * of the Mozilla Public License, Version 1.1, or any later version. You may not use
5  * this file except in compliance with the license. If you need a copy of the license,
6  * please go to http://www.mozilla.org/MPL/MPL-1.1.txt. The Original Code is the Pentaho
7  * BI Platform. The Initial Developer is Pentaho Corporation.
8  *
9  * Software distributed under the Mozilla Public License is distributed on an "AS IS"
10  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to
11  * the license for the specific language governing your rights and limitations.
12  *
13  * @created Nov 17, 2005
14  * @author William Seyler
15  */

16 package org.pentaho.plugin.jfreechart;
17
18 import java.io.BufferedWriter JavaDoc;
19 import java.io.File JavaDoc;
20 import java.io.FileWriter JavaDoc;
21 import java.io.IOException JavaDoc;
22 import java.io.InputStream JavaDoc;
23 import java.io.PrintWriter JavaDoc;
24 import java.io.StringWriter JavaDoc;
25 import java.util.Iterator JavaDoc;
26 import java.util.Set JavaDoc;
27
28 import org.apache.commons.logging.Log;
29 import org.apache.commons.logging.LogFactory;
30 import org.dom4j.Element;
31 import org.dom4j.Node;
32 import org.jfree.chart.ChartRenderingInfo;
33 import org.jfree.chart.entity.StandardEntityCollection;
34 import org.jfree.chart.imagemap.ImageMapUtilities;
35 import org.jfree.chart.imagemap.StandardToolTipTagFragmentGenerator;
36 import org.jfree.data.general.Dataset;
37 import org.pentaho.core.connection.IPentahoResultSet;
38 import org.pentaho.core.repository.ISolutionRepository;
39 import org.pentaho.core.system.PentahoSystem;
40 import org.pentaho.plugin.ComponentBase;
41
42 public class ChartComponent extends ComponentBase {
43     private static final long serialVersionUID = 9050456842938084174L;
44
45     private static final String JavaDoc CHART_DATA_PROP = "chart-data"; //$NON-NLS-1$
46

47     private static final String JavaDoc CHART_ATTRIBUTES_PROP = "chart-attributes"; //$NON-NLS-1$
48

49     private static final String JavaDoc BY_ROW_PROP = "by-row"; //$NON-NLS-1$
50

51     private static final String JavaDoc URL_TEMPLATE = "url-template"; //$NON-NLS-1$
52

53     private static final String JavaDoc PARAMETER_NAME = "paramName"; //$NON-NLS-1$
54

55     private static final String JavaDoc OUTER_PARAMETER_NAME = "series-name"; //$NON-NLS-1$
56

57     private static final String JavaDoc OUTPUT_TYPE_PROP = "output-type"; //$NON-NLS-1$
58

59     private static final String JavaDoc CHART_FILE_NAME_OUTPUT = "chart-filename"; //$NON-NLS-1$
60

61     private static final String JavaDoc HTML_MAPPING_OUTPUT = "chart-mapping"; //$NON-NLS-1$
62

63     private static final String JavaDoc BASE_URL_OUTPUT = "base-url"; //$NON-NLS-1$
64

65     private static final String JavaDoc SVG_TYPE = "SVG"; //$NON-NLS-1$
66

67     private static final String JavaDoc TEMP_DIRECTORY = "system/tmp/"; //$NON-NLS-1$
68

69     private static final String JavaDoc FILENAME_PREFIX = "tmp_chart_"; //$NON-NLS-1$
70

71     private static final String JavaDoc PNG_EXTENSION = ".png"; //$NON-NLS-1$
72

73     private static final String JavaDoc SVG_EXTENSION = ".svg"; //$NON-NLS-1$
74

75     private static final String JavaDoc MAP_EXTENSION = ".map"; //$NON-NLS-1$
76

77     private static final int FILE_NAME = 0;
78
79     private static final int MAP_NAME = 1;
80
81     public Log getLogger() {
82         return LogFactory.getLog(ChartComponent.class);
83     }
84
85     protected boolean validateSystemSettings() {
86         // This component does not have any system settings to validate
87
return true;
88     }
89
90     protected boolean validateAction() {
91         // See if we have chart data
92
if (!isDefinedInput(CHART_DATA_PROP)) {
93             inputMissingError(CHART_DATA_PROP);
94             return false;
95         }
96         // See if we have chart attributes
97
if (!isDefinedInput(CHART_ATTRIBUTES_PROP)) {
98             inputMissingError(CHART_ATTRIBUTES_PROP);
99             return false;
100         }
101
102         if (!isDefinedInput(CHART_ATTRIBUTES_PROP)) {
103             inputMissingError(CHART_ATTRIBUTES_PROP);
104             return false;
105         }
106         // Anything else should be optional
107
return true;
108     }
109
110     public void done() {
111     }
112
113     protected boolean executeAction() {
114         int height = -1;
115         int width = -1;
116
117         
118         IPentahoResultSet data = (IPentahoResultSet) getInputValue(CHART_DATA_PROP);
119         String JavaDoc urlTemplate = (String JavaDoc) getInputValue(URL_TEMPLATE);
120         Node chartAttributes = getComponentDefinition( true ).selectSingleNode(CHART_ATTRIBUTES_PROP);
121         
122         if (urlTemplate == null || urlTemplate.length() == 0) {
123             if (chartAttributes.selectSingleNode(URL_TEMPLATE) != null) {
124                 urlTemplate = chartAttributes.selectSingleNode(URL_TEMPLATE).getText();
125             }
126         }
127         
128         String JavaDoc parameterName = (String JavaDoc) getInputValue(PARAMETER_NAME);
129         if (parameterName == null || parameterName.length() == 0) {
130             if (chartAttributes.selectSingleNode(PARAMETER_NAME) != null) {
131                 parameterName = chartAttributes.selectSingleNode(PARAMETER_NAME).getText();
132             }
133         }
134         
135         String JavaDoc outerParameterName = (String JavaDoc) getInputValue(OUTER_PARAMETER_NAME);
136         if (outerParameterName == null || outerParameterName.length() == 0) {
137             if (chartAttributes.selectSingleNode(OUTER_PARAMETER_NAME) != null) {
138                 outerParameterName = chartAttributes.selectSingleNode(OUTER_PARAMETER_NAME).getText();
139             }
140         }
141
142         String JavaDoc chartType = chartAttributes.selectSingleNode(ChartDefinition.TYPE_NODE_NAME).getText();
143
144         // ------------- This code allows inputs to override the chartAttributes
145
// of width, height, and title
146
Object JavaDoc widthObj = getInputValue(ChartDefinition.WIDTH_NODE_NAME);
147         if (widthObj != null) {
148             width = Integer.parseInt(widthObj.toString());
149             if (width != -1) {
150                 if (chartAttributes.selectSingleNode(ChartDefinition.WIDTH_NODE_NAME) == null) {
151                     ((Element)chartAttributes).addElement(ChartDefinition.WIDTH_NODE_NAME);
152                 }
153                 chartAttributes.selectSingleNode(ChartDefinition.WIDTH_NODE_NAME).setText(Integer.toString(width));
154             }
155         }
156         Object JavaDoc heightObj = getInputValue(ChartDefinition.HEIGHT_NODE_NAME);
157         if (heightObj != null) {
158             height = Integer.parseInt(heightObj.toString());
159             if (height != -1) {
160                 if (chartAttributes.selectSingleNode(ChartDefinition.HEIGHT_NODE_NAME) == null) {
161                     ((Element)chartAttributes).addElement(ChartDefinition.HEIGHT_NODE_NAME);
162                 }
163                 chartAttributes.selectSingleNode(ChartDefinition.HEIGHT_NODE_NAME).setText(Integer.toString(height));
164             }
165         }
166         Object JavaDoc titleObj = getInputValue(ChartDefinition.TITLE_NODE_NAME);
167         if (titleObj != null) {
168             if (chartAttributes.selectSingleNode(ChartDefinition.TITLE_NODE_NAME) == null) {
169                 ((Element)chartAttributes).addElement(ChartDefinition.TITLE_NODE_NAME);
170             }
171             chartAttributes.selectSingleNode(ChartDefinition.TITLE_NODE_NAME).setText(titleObj.toString());
172         }
173         // ----------------End of Override
174

175         // ---------------Feed the Title and Subtitle information through the imput substitution
176
Node titleNode = chartAttributes.selectSingleNode(ChartDefinition.TITLE_NODE_NAME);
177         if (titleNode != null) {
178             String JavaDoc titleStr = titleNode.getText();
179             if (titleStr != null) {
180                 String JavaDoc newTitle = applyInputsToFormat(titleStr);
181                 titleNode.setText(newTitle);
182             }
183         }
184         
185         Node subtitleNode = chartAttributes.selectSingleNode(ChartDefinition.SUBTITLE_NODE_NAME);
186         if (subtitleNode != null) {
187             String JavaDoc subtitleStr = subtitleNode.getText();
188             if (subtitleStr != null) {
189                 String JavaDoc newSubtitle = applyInputsToFormat(subtitleStr);
190                 subtitleNode.setText(newSubtitle);
191             }
192         }
193         //----------------End of Format
194

195         // code-------------------------------------------------------------
196

197         boolean byRow = false;
198         if (getInputStringValue(BY_ROW_PROP) != null) {
199             byRow = Boolean.valueOf(getInputStringValue(BY_ROW_PROP)).booleanValue();
200         }
201         int outputType = JFreeChartEngine.OUTPUT_PNG; // default to png output
202
if (getInputStringValue(OUTPUT_TYPE_PROP) != null) {
203             if (SVG_TYPE.equalsIgnoreCase(getInputStringValue(OUTPUT_TYPE_PROP))) {
204                 outputType = JFreeChartEngine.OUTPUT_SVG;
205             }
206         }
207
208         height = (int) getInputLongValue(CHART_ATTRIBUTES_PROP + "/" + ChartDefinition.HEIGHT_NODE_NAME, 50); //$NON-NLS-1$
209
width = (int) getInputLongValue(CHART_ATTRIBUTES_PROP + "/" + ChartDefinition.WIDTH_NODE_NAME, 100); //$NON-NLS-1$
210
String JavaDoc title = getInputStringValue(CHART_ATTRIBUTES_PROP + "/" + ChartDefinition.TITLE_NODE_NAME); //$NON-NLS-1$
211

212         // Select the right dataset to use based on the chart type
213

214         String JavaDoc datasetType = ChartDefinition.CATAGORY_DATASET_STR; // Default to category dataset
215
Node datasetTypeNode = chartAttributes.selectSingleNode(ChartDefinition.DATASET_TYPE_NODE_NAME);
216         if (datasetTypeNode != null) {
217             datasetType = datasetTypeNode.getText();
218         }
219         Dataset dataDefinition = null;
220         if (ChartDefinition.XY_SERIES_COLLECTION_STR.equalsIgnoreCase(datasetType)) {
221             dataDefinition = new XYSeriesCollectionChartDefinition(data, byRow, chartAttributes, getSession());
222         } else if (ChartDefinition.TIME_SERIES_COLLECTION_STR.equalsIgnoreCase(datasetType)) {
223             dataDefinition = new TimeSeriesCollectionChartDefinition(data, byRow, chartAttributes, getSession());
224         } else if (ChartDefinition.PIE_CHART_STR.equalsIgnoreCase(chartType)) {
225             dataDefinition = new PieDatasetChartDefinition(data, byRow, chartAttributes, getSession());
226         } else if (ChartDefinition.DIAL_CHART_STR.equalsIgnoreCase(chartType)) {
227             dataDefinition = new DialWidgetDefinition(data, byRow, chartAttributes, width, height, getSession());
228         } else {
229             dataDefinition = new CategoryDatasetChartDefinition(data, byRow, chartAttributes, getSession());
230         }
231
232
233         File JavaDoc[] fileResults = createTempFile(outputType);
234         String JavaDoc filePathWithoutExtension = TEMP_DIRECTORY + fileResults[FILE_NAME].getName().substring(0, fileResults[FILE_NAME].getName().indexOf('.'));
235         PrintWriter JavaDoc printWriter = new PrintWriter JavaDoc(new StringWriter JavaDoc());
236         ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
237         JFreeChartEngine.saveChart(dataDefinition, title, "", filePathWithoutExtension, width, height, outputType, printWriter, info, this); //$NON-NLS-1$
238
String JavaDoc mapString = ImageMapUtilities.getImageMap(fileResults[MAP_NAME].getName().substring(0, fileResults[MAP_NAME].getName().indexOf('.')), info, new StandardToolTipTagFragmentGenerator(), new PentahoChartURLTagFragmentGenerator(urlTemplate, dataDefinition, parameterName, outerParameterName));
239         try {
240             BufferedWriter JavaDoc out = new BufferedWriter JavaDoc(new FileWriter JavaDoc(fileResults[MAP_NAME]));
241             out.write(mapString);
242             out.close();
243         } catch (IOException JavaDoc e) {
244             // TODO Auto-generated catch block
245
e.printStackTrace();
246         }
247
248         // Now set the outputs
249
Set JavaDoc outputs = getOutputNames();
250         if (outputs != null && outputs.size() > 0) {
251             Iterator JavaDoc iter = outputs.iterator();
252             while (iter.hasNext()) {
253                 String JavaDoc outputName = (String JavaDoc) iter.next();
254                 String JavaDoc outputValue = null;
255                 if (outputName.equals(CHART_FILE_NAME_OUTPUT)) {
256                     outputValue = fileResults[FILE_NAME].getName();
257                 } else if (outputName.equals(HTML_MAPPING_OUTPUT)) {
258                     outputValue = fileResults[MAP_NAME].getName();
259                 } else if (outputName.equals(BASE_URL_OUTPUT)) {
260                     outputValue = PentahoSystem.getApplicationContext().getBaseUrl();
261                 }
262                 
263                 if (outputValue != null) {
264                     setOutputValue(outputName, outputValue);
265                 }
266             }
267         } else { // No output was specified so throw up a simple html page.
268
try {
269             getFeedbackOutputStream().write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">".getBytes()); //$NON-NLS-1$
270
getFeedbackOutputStream().write("<html xmlns=\"http://www.w3.org/1999/xhtml\">".getBytes()); //$NON-NLS-1$
271
getFeedbackOutputStream().write("<body><center><br />".getBytes()); //$NON-NLS-1$
272

273             ISolutionRepository repository = PentahoSystem.getSolutionRepository(getSession());
274             InputStream JavaDoc is = repository.getResourceInputStream(getSolutionRelativePath(fileResults[MAP_NAME].getAbsolutePath()));
275
276             byte bytes[] = new byte[1024];
277             int numRead = 0;
278             while ((numRead=is.read(bytes)) >= 0) {
279                 getFeedbackOutputStream().write(bytes, 0, numRead);
280             }
281             is.close();
282             
283             getFeedbackOutputStream().write("<img border=\"0\" ".getBytes()); //$NON-NLS-1$
284
getFeedbackOutputStream().write(("width=\"" + width +"\" ").getBytes()); //$NON-NLS-1$//$NON-NLS-2$
285
getFeedbackOutputStream().write(("height=\"" + height +"\" ").getBytes()); //$NON-NLS-1$ //$NON-NLS-2$
286
getFeedbackOutputStream().write(("usemap=\"#" + fileResults[MAP_NAME].getName().substring(0, fileResults[MAP_NAME].getName().indexOf('.')) + "\" ").getBytes()); //$NON-NLS-1$ //$NON-NLS-2$
287
getFeedbackOutputStream().write(("src=\"" + PentahoSystem.getApplicationContext().getBaseUrl() + "getImage?image=" + fileResults[FILE_NAME].getName() + "\"/>").getBytes()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
288

289             getFeedbackOutputStream().write("</center></body></html>".getBytes()); //$NON-NLS-1$
290
} catch (Exception JavaDoc e) {
291             e.printStackTrace();
292           }
293         }
294         
295         
296         return true;
297     }
298
299     public boolean init() {
300         // nothing to do here really
301
return true;
302     }
303
304     /**
305      * @return String that represents the file path to a temporary file
306      */

307     protected File JavaDoc[] createTempFile(int outputType) {
308         File JavaDoc[] results = new File JavaDoc[2];
309
310         String JavaDoc extension = outputType == JFreeChartEngine.OUTPUT_SVG ? SVG_EXTENSION : PNG_EXTENSION;
311
312         try {
313             File JavaDoc file = File.createTempFile(FILENAME_PREFIX, extension, new File JavaDoc(PentahoSystem.getApplicationContext().getFileOutputPath(TEMP_DIRECTORY)));
314             file.deleteOnExit();
315             results[FILE_NAME] = file;
316             file = File.createTempFile(FILENAME_PREFIX, MAP_EXTENSION, new File JavaDoc(PentahoSystem.getApplicationContext().getFileOutputPath(TEMP_DIRECTORY)));
317             file.deleteOnExit();
318             results[MAP_NAME] = file;
319         } catch (IOException JavaDoc e) {
320             // TODO Auto-generated catch block
321
e.printStackTrace();
322         }
323         return results;
324     }
325     
326     protected String JavaDoc getSolutionRelativePath(String JavaDoc fullPath) {
327             String JavaDoc prefix = PentahoSystem.getApplicationContext().getSolutionPath(""); //$NON-NLS-1$
328
String JavaDoc result = fullPath.replaceFirst(prefix, ""); //$NON-NLS-1$
329
return result;
330     }
331 }
332
Popular Tags