KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > pentaho > ui > component > charting > CategoryDatasetChartComponent


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 wseyler
15  */

16
17 package org.pentaho.ui.component.charting;
18
19 import java.io.IOException JavaDoc;
20 import java.io.PrintWriter JavaDoc;
21 import java.io.StringWriter JavaDoc;
22 import java.io.UnsupportedEncodingException JavaDoc;
23 import java.net.URLEncoder JavaDoc;
24 import java.util.ArrayList JavaDoc;
25 import java.util.Iterator JavaDoc;
26 import java.util.List JavaDoc;
27 import org.dom4j.Document;
28 import org.dom4j.DocumentHelper;
29 import org.dom4j.Element;
30 import org.dom4j.Node;
31 import org.jfree.chart.ChartRenderingInfo;
32 import org.jfree.chart.entity.CategoryItemEntity;
33 import org.jfree.chart.entity.ChartEntity;
34 import org.jfree.chart.entity.PieSectionEntity;
35 import org.jfree.chart.entity.StandardEntityCollection;
36 import org.jfree.chart.imagemap.ImageMapUtilities;
37 import org.jfree.data.category.DefaultCategoryDataset;
38 import org.jfree.data.general.Dataset;
39 import org.pentaho.core.connection.IPentahoResultSet;
40 import org.pentaho.messages.Messages;
41 import org.pentaho.core.solution.ActionResource;
42 import org.pentaho.core.solution.IActionResource;
43 import org.pentaho.core.system.PentahoSystem;
44 import org.pentaho.core.ui.IPentahoUrlFactory;
45 import org.pentaho.core.util.TemplateUtil;
46 import org.pentaho.core.util.XmlHelper;
47 import org.pentaho.messages.util.LocaleHelper;
48 import org.pentaho.plugin.jfreechart.CategoryDatasetChartDefinition;
49 import org.pentaho.plugin.jfreechart.JFreeChartEngine;
50
51 public class CategoryDatasetChartComponent extends AbstractJFreeChartComponent {
52     private static final long serialVersionUID = -6268840271596447555L;
53
54     protected String JavaDoc seriesName = null;
55
56     public CategoryDatasetChartComponent(int chartType, String JavaDoc definitionPath, int width, int height, IPentahoUrlFactory urlFactory, List JavaDoc messages) {
57         super(chartType, definitionPath, width, height, urlFactory, messages);
58         // Set the XSL file to be used to generate the HTML
59
setXsl("text/html", "Chart.xsl"); //$NON-NLS-1$ //$NON-NLS-2$
60
}
61
62     public CategoryDatasetChartComponent(String JavaDoc definitionPath, IPentahoUrlFactory urlFactory, ArrayList JavaDoc messages) {
63         super(definitionPath, urlFactory, messages);
64         // Set the XSL file to be used to generate the HTML
65
setXsl("text/html", "Chart.xsl"); //$NON-NLS-1$ //$NON-NLS-2$
66
}
67
68     public CategoryDatasetChartComponent(IPentahoUrlFactory urlFactory, List JavaDoc messages) {
69         super(urlFactory, messages);
70         // Set the XSL file to be used to generate the HTML
71
setXsl("text/html", "Chart.xsl"); //$NON-NLS-1$ //$NON-NLS-2$
72
}
73
74     public void setSeriesName( String JavaDoc seriesName ) {
75         this.seriesName = seriesName;
76     }
77     
78     public Dataset createChart(Document doc) {
79         if (solution != null) { // if we have a solution then get the values
80
values = getActionData();
81         } else {
82             // TODO support other methods of getting data
83
}
84
85         if( values == null ) {
86             // we could not get any data
87
return null;
88         }
89         // get the chart node from the document
90
Node chartAttributes = doc.selectSingleNode("//" + CHART_NODE_NAME); //$NON-NLS-1$
91
// create the definition
92
CategoryDatasetChartDefinition chartDefinition = new CategoryDatasetChartDefinition((IPentahoResultSet) values, byRow, chartAttributes, getSession());
93
94         // set the misc values from chartDefinition
95
setChartType(chartDefinition.getChartType());
96         setTitle(chartDefinition.getTitle());
97
98         // get the URL template
99
Node urlTemplateNode = chartAttributes.selectSingleNode(URLTEMPLE_NODE_NAME);
100         if (urlTemplateNode != null) {
101             setUrlTemplate(urlTemplateNode.getText());
102         }
103
104         // get the additional parameter
105
Node paramName2Node = chartAttributes.selectSingleNode(PARAM2_NODE_NAME);
106         if (paramName2Node != null) {
107             seriesName = paramName2Node.getText();
108         }
109
110         if (chartDefinition.getWidth() != -1 && (width == -1 )) {
111             setWidth(chartDefinition.getWidth());
112         }
113         if (chartDefinition.getHeight() != -1 && (height == -1 )) {
114             setHeight(chartDefinition.getHeight());
115         }
116
117         return chartDefinition;
118     }
119
120     public boolean setDataAction(String JavaDoc chartDefinition) {
121         ActionResource resource = new ActionResource("", IActionResource.SOLUTION_FILE_RESOURCE, "text/xml", //$NON-NLS-1$ //$NON-NLS-2$
122
chartDefinition);
123         try {
124             Document dataActionDocument = PentahoSystem.getSolutionRepository(getSession()).getResourceAsDocument(resource);
125             if (dataActionDocument == null) {
126                 return false;
127             }
128             Node dataNode = dataActionDocument.selectSingleNode("chart/data"); //$NON-NLS-1$
129
chartType = (int) XmlHelper.getNodeText("chart-type", dataNode, -1); //$NON-NLS-1$
130
solution = XmlHelper.getNodeText("data-solution", dataNode); //$NON-NLS-1$
131
actionPath = XmlHelper.getNodeText("data-path", dataNode); //$NON-NLS-1$
132
actionName = XmlHelper.getNodeText("data-action", dataNode); //$NON-NLS-1$
133
actionOutput = XmlHelper.getNodeText("data-output", dataNode); //$NON-NLS-1$
134
byRow = XmlHelper.getNodeText("data-orientation", dataNode, "rows").equals("rows"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
135
if( width == 0 ) {
136                 width = (int) XmlHelper.getNodeText("chart/width", dataActionDocument, 125); //$NON-NLS-1$
137
}
138             if( height == 0 ) {
139                 height = (int) XmlHelper.getNodeText("chart/height", dataActionDocument, 125); //$NON-NLS-1$
140
}
141         } catch (Exception JavaDoc e) {
142             error(Messages.getString("CategoryDatasetChartComponent.ERROR_0001_INVALID_CHART_DEFINITION", chartDefinition), e); //$NON-NLS-1$
143
return false;
144         }
145         return true;
146     }
147
148     public Document getXmlContent() {
149
150         // Create a document that describes the result
151
Document result = DocumentHelper.createDocument();
152         String JavaDoc baseUrl = PentahoSystem.getApplicationContext().getBaseUrl();
153         setXslProperty("baseUrl", baseUrl); //$NON-NLS-1$
154

155         // load the XML document that defines the pie
156
ActionResource resource = new ActionResource(title, IActionResource.SOLUTION_FILE_RESOURCE, "text/xml", //$NON-NLS-1$
157
definitionPath);
158         Document chartDefinition = null;
159         String JavaDoc mapName = "chart" + chartCount++; //$NON-NLS-1$
160
try {
161             chartDefinition = PentahoSystem.getSolutionRepository(getSession()).getResourceAsDocument(resource);
162         } catch (IOException JavaDoc e) {
163         }
164
165         if( chartDefinition == null ) {
166             Element errorElement = result.addElement("error"); //$NON-NLS-1$
167
errorElement.addElement("title").setText( Messages.getString( "ABSTRACTCHARTEXPRESSION.ERROR_0001_ERROR_GENERATING_CHART" ) ); //$NON-NLS-1$ //$NON-NLS-2$
168
String JavaDoc message = Messages.getString( "CHARTS.ERROR_0001_CHART_DEFINIION_MISSING", definitionPath ); //$NON-NLS-1$
169
errorElement.addElement("message").setText( message ); //$NON-NLS-1$
170
error( message );
171             return result;
172         }
173         // create a pie definition from the XML definition
174
dataDefinition = createChart(chartDefinition);
175
176         if( dataDefinition == null ) {
177             Element errorElement = result.addElement("error"); //$NON-NLS-1$
178
errorElement.addElement("title").setText( Messages.getString( "ABSTRACTCHARTEXPRESSION.ERROR_0001_ERROR_GENERATING_CHART" ) ); //$NON-NLS-1$ //$NON-NLS-2$
179
String JavaDoc message = Messages.getString( "CHARTS.ERROR_0002_CHART_DATA_MISSING", solution + "/"+ actionPath + "/" + actionName ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
180
errorElement.addElement("message").setText( message ); //$NON-NLS-1$
181
//System .out.println( result.asXML() );
182
return result;
183         }
184
185         // create an image for the dial using the JFreeChart engine
186
PrintWriter JavaDoc printWriter = new PrintWriter JavaDoc(new StringWriter JavaDoc());
187         // we'll dispay the title in HTML so that the dial image does not have
188
// to
189
// accommodate it
190
String JavaDoc chartTitle = ""; //$NON-NLS-1$
191
try {
192             if( width == -1 ) {
193                 width = Integer.parseInt(chartDefinition.selectSingleNode("/chart/width").getText()); //$NON-NLS-1$
194
}
195             if( height == -1 ) {
196                 height = Integer.parseInt(chartDefinition.selectSingleNode("/chart/height").getText()); //$NON-NLS-1$
197
}
198         } catch (Exception JavaDoc e) {
199             // go with the default
200
}
201         if (chartDefinition.selectSingleNode("/chart/"+URLTEMPLE_NODE_NAME) != null) { //$NON-NLS-1$
202
urlTemplate = chartDefinition.selectSingleNode("/chart/"+URLTEMPLE_NODE_NAME).getText(); //$NON-NLS-1$
203
}
204
205         if (chartDefinition.selectSingleNode("/chart/paramName") != null) { //$NON-NLS-1$
206
paramName = chartDefinition.selectSingleNode("/chart/paramName").getText(); //$NON-NLS-1$
207
}
208
209         Element root = result.addElement("charts"); //$NON-NLS-1$
210
DefaultCategoryDataset chartDataDefinition = (DefaultCategoryDataset) dataDefinition;
211         if (chartDataDefinition.getRowCount() > 0) {
212             // create temporary file names
213
String JavaDoc[] tempFileInfo = createTempFile();
214             String JavaDoc fileName = tempFileInfo[AbstractChartComponent.FILENAME_INDEX];
215             String JavaDoc filePathWithoutExtension = tempFileInfo[AbstractChartComponent.FILENAME_WITHOUT_EXTENSION_INDEX];
216
217             ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
218             JFreeChartEngine.saveChart(chartDataDefinition, chartTitle, "", filePathWithoutExtension, width, height, JFreeChartEngine.OUTPUT_PNG, printWriter, info, this); //$NON-NLS-1$
219
applyOuterURLTemplateParam();
220             popultateInfo(info);
221             Element chartElement = root.addElement("chart"); //$NON-NLS-1$
222
chartElement.addElement("mapName").setText(mapName); //$NON-NLS-1$
223
chartElement.addElement("width").setText(Integer.toString(width)); //$NON-NLS-1$
224
chartElement.addElement("height").setText(Integer.toString(height)); //$NON-NLS-1$
225
for (int row = 0; row < chartDataDefinition.getRowCount(); row++) {
226                 for (int column = 0; column < chartDataDefinition.getColumnCount(); column++) {
227                     Number JavaDoc value = chartDataDefinition.getValue(row, column);
228                     Comparable JavaDoc rowKey = chartDataDefinition.getRowKey(row);
229                     Comparable JavaDoc columnKey = chartDataDefinition.getColumnKey(column);
230                     Element valueElement = chartElement.addElement("value2D"); //$NON-NLS-1$
231
valueElement.addElement("value").setText(value.toString()); //$NON-NLS-1$
232
valueElement.addElement("row-key").setText(rowKey.toString()); //$NON-NLS-1$
233
valueElement.addElement("column-key").setText(columnKey.toString()); //$NON-NLS-1$
234
}
235             }
236             String JavaDoc mapString = ImageMapUtilities.getImageMap(mapName, info);
237             chartElement.addElement("imageMap").setText(mapString); //$NON-NLS-1$
238
chartElement.addElement("image").setText(fileName); //$NON-NLS-1$
239
}
240         return result;
241     }
242
243     private void popultateInfo(ChartRenderingInfo info) {
244         if( urlTemplate == null ) {
245             return;
246         }
247         ArrayList JavaDoc seriesListArray = null;
248         int seriesListIndex = 0;
249         Iterator JavaDoc iter = info.getEntityCollection().iterator();
250         while (iter.hasNext()) {
251             ChartEntity entity = (ChartEntity) iter.next();
252             if (entity instanceof PieSectionEntity) {
253                 PieSectionEntity pieSectionEntity = (PieSectionEntity) entity;
254                 String JavaDoc value = pieSectionEntity.getSectionKey().toString();
255                 if (paramName == null) {
256                     pieSectionEntity.setURLText(value);
257                 } else {
258                     try {
259                         String JavaDoc encodedVal = URLEncoder.encode(value, LocaleHelper.getSystemEncoding());
260                         String JavaDoc drillURL = TemplateUtil.applyTemplate(urlTemplate, paramName, encodedVal);
261                         pieSectionEntity.setURLText(drillURL);
262
263                     } catch (UnsupportedEncodingException JavaDoc e) {
264                         // TODO Auto-generated catch block
265
e.printStackTrace();
266                     }
267                 }
268             } else if (entity instanceof CategoryItemEntity) {
269                 CategoryItemEntity categoryItemEntity = (CategoryItemEntity) entity;
270                 if (seriesListArray == null) {
271                     seriesListArray = new ArrayList JavaDoc(categoryItemEntity.getDataset().getRowKeys());
272                 }
273                 String JavaDoc category = categoryItemEntity.getCategory().toString();
274                 if (paramName == null) {
275                     categoryItemEntity.setURLText(category);
276                 } else {
277                     try {
278                         String JavaDoc encodedVal = URLEncoder.encode(category, LocaleHelper.getSystemEncoding());
279                         String JavaDoc drillURL = TemplateUtil.applyTemplate(urlTemplate, paramName, encodedVal);
280                         if (seriesListIndex >= seriesListArray.size()) {
281                             seriesListIndex = 0;
282                         }
283                         encodedVal = URLEncoder.encode(seriesListArray.get(seriesListIndex).toString(), LocaleHelper.getSystemEncoding());
284                         seriesListIndex++;
285                         if( seriesName == null ) {
286                             drillURL = TemplateUtil.applyTemplate(drillURL, "SERIES", encodedVal); //$NON-NLS-1$
287
} else {
288                             drillURL = TemplateUtil.applyTemplate(drillURL, seriesName, encodedVal);
289                         }
290                         categoryItemEntity.setURLText(drillURL);
291
292                     } catch (UnsupportedEncodingException JavaDoc e) {
293                         // TODO Auto-generated catch block
294
e.printStackTrace();
295                     }
296                 }
297             }
298         }
299     }
300
301     public boolean validate() {
302         // TODO Auto-generated method stub
303
return true;
304     }
305
306 }
307
Popular Tags