KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > za > org > coefficient > modules > statistics > StatisticsDisplay


1
2 /*
3  * Coefficient - facilitates project based collaboration
4  * Copyright (C) 2003, Dylan Etkin, CSIR icomtek
5  * PO Box 395
6  * Pretoria 0001, RSA
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19  */

20
21 package za.org.coefficient.modules.statistics;
22
23 import org.apache.commons.lang.StringUtils;
24
25 import org.jfree.chart.ChartFactory;
26 import org.jfree.chart.JFreeChart;
27 import org.jfree.data.time.Day;
28 import org.jfree.data.time.TimeTableXYDataset;
29 import org.jfree.data.DefaultKeyedValues;
30 import org.jfree.data.general.DefaultPieDataset;
31 import org.jfree.chart.plot.PlotOrientation;
32 import org.jfree.chart.servlet.ServletUtilities;
33 import org.jfree.chart.servlet.ChartDeleter;
34 import org.jfree.chart.plot.XYPlot;
35 import org.jfree.chart.plot.PiePlot3D;
36 import org.jfree.chart.axis.NumberAxis;
37 import org.jfree.chart.axis.DateAxis;
38 import org.jfree.chart.renderer.xy.StandardXYItemRenderer;
39 import org.jfree.chart.labels.StandardXYToolTipGenerator;
40 import org.jfree.chart.renderer.xy.XYItemRenderer;
41 import org.jfree.util.Rotation;
42
43 import net.sf.hibernate.HibernateException;
44 import net.sf.hibernate.Hibernate;
45
46 import za.org.coefficient.core.Constants;
47 import za.org.coefficient.core.Project;
48 import za.org.coefficient.authentication.Role;
49 import za.org.coefficient.interfaces.CoefficientContext;
50 import za.org.coefficient.modules.BaseModule;
51 import za.org.coefficient.modules.project.ProjectConstants;
52 import za.org.coefficient.statistics.data.ProjectStatistics;
53 import za.org.coefficient.statistics.data.ProjectStatisticsData;
54 import za.org.coefficient.statistics.data.ModuleStatistics;
55 import za.org.coefficient.statistics.data.ModuleStatisticsData;
56 import net.sf.hibernate.util.HibernateUtil;
57 import za.org.coefficient.util.ejb.VelocityScreenUtil;
58
59 import java.awt.Color JavaDoc;
60 import java.awt.Paint JavaDoc;
61
62 import java.io.IOException JavaDoc;
63
64 import java.util.ArrayList JavaDoc;
65 import java.util.Date JavaDoc;
66 import java.util.HashMap JavaDoc;
67 import java.util.Iterator JavaDoc;
68 import java.util.Map JavaDoc;
69
70 /**
71  * @pojo2ejb.class
72  * name="StatisticsDisplay"
73  * jndi-prefix="za/org/coefficient/orphan/"
74  * interface-extends="za.org.coefficient.interfaces.Module"
75  * interface-local-extends="za.org.coefficient.interfaces.ModuleLocal"
76  *
77  * @web.resource-env-ref
78  * name="za/org/coefficient/orphan/StatisticsDisplay"
79  * type="za.org.coefficient.modules.statistics.StatisticsDisplay"
80  * @web.resource-env-ref
81  * name="StatisticsDisplay"
82  * type="za.org.coefficient.modules.statistics.StatisticsDisplay"
83  */

84 public class StatisticsDisplay extends BaseModule {
85
86     //~ Methods ================================================================
87

88     public String JavaDoc getMainMethod() {
89         return "showStatistics";
90     }
91
92     public String JavaDoc getModuleDescription() {
93         return "This module generates graphic displays of Statistics.";
94     }
95
96     public String JavaDoc getModuleDisplayName() {
97         return "Statistics Display";
98     }
99
100     public String JavaDoc canExecuteForRole(CoefficientContext ctx, String JavaDoc methodName,
101                                     Role usersHighestRole) {
102         return null;
103     }
104
105     public CoefficientContext showStatistics(CoefficientContext ctx) {
106         HashMap JavaDoc map = new HashMap JavaDoc();
107         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
108
109         int numDays = ctx.getParameterAsInt("numDays", 7);
110         if(numDays <= 0) {
111             ctx.setError("You can not view statistics for a negative or zero date range.");
112         } else {
113             String JavaDoc totalXYLineChart =
114                 generateAndSaveProjectTotalsXYLineChart(ctx, numDays);
115             String JavaDoc pieChart = generateAndSavePercentActivityPieChart(ctx, numDays);
116             ArrayList JavaDoc moduleGraphs =
117                 generateAndSaveModuleXYLineCharts(ctx, numDays);
118
119             if(!ctx.isError()) {
120                 map.put("moduleGraphs", moduleGraphs);
121                 map.put("totalXYLineChart", totalXYLineChart);
122                 map.put("pieChart", pieChart);
123                 map.put("numDays", new Integer JavaDoc(numDays));
124                 sb = VelocityScreenUtil.getProcessedScreen("showStats.vm", map);
125                 
126                 // Set the html into the context
127
ctx.setModuleContent(sb.toString(), getModuleDisplayName());
128             }
129         }
130         return ctx;
131     }
132
133     public String JavaDoc generateAndSavePercentActivityPieChart(CoefficientContext ctx,
134                                                          int daysToInclude) {
135         Project prj = ctx.getProject();
136         if(prj != null) {
137             ProjectStatistics prjStats = prj.getStatistics();
138             try {
139                 // Make sure we have the latest and greatest from the DB
140
HibernateUtil.refresh(prjStats);
141             } catch(HibernateException he) {
142                 // do nothing just work with what we have
143
he.printStackTrace();
144             }
145             // Generate the PieChart for % activities
146

147             //long rank = prjStats.getCurrentData().getRank();
148
long rank = prjStats
149                 .getRankForNumberOfDaysIncludingToday(daysToInclude);
150
151             DefaultKeyedValues pieValues = new DefaultKeyedValues();
152             int numPieces = 1;
153             long totalFromMods = 0;
154             for(Iterator JavaDoc it = prjStats.getModuleStatistics().keySet().iterator();
155                 it.hasNext();) {
156                 String JavaDoc moduleName = (String JavaDoc)it.next();
157                 ModuleStatistics modStat = (ModuleStatistics)prjStats
158                     .getModuleStatistics().get(moduleName);
159                 
160                 pieValues.addValue(moduleName, new Long JavaDoc((long)(((double)modStat.getActivityTotalForNumberOfDaysIncludingToday(daysToInclude) / (double)rank) * 100)));
161                 totalFromMods += modStat.calculateStats();
162                 numPieces++;
163             }
164
165             pieValues.addValue(StringUtils.capitalise(ProjectConstants.PROJECT_NAME) + " Views", new Long JavaDoc((long)(((double)(prjStats.getViewActivityTotalForNumberOfDaysIncludingToday(daysToInclude)) / (double)rank) * 100)));
166             pieValues.addValue(StringUtils.capitalise(ProjectConstants.PROJECT_NAME) + " Downloads", new Long JavaDoc((long)(((double)(prjStats.getDownloadActivityTotalForNumberOfDaysIncludingToday(daysToInclude)) / (double)rank) * 100)));
167
168             DefaultPieDataset pieDataset = new DefaultPieDataset(pieValues);
169
170             JFreeChart pieChart = ChartFactory
171                 .createPieChart3D("Percent Activity by Module for: "
172                                   + prj.getName(), pieDataset,
173                                   true, true, false);
174             PiePlot3D plot = (PiePlot3D)pieChart.getPlot();
175
176             plot.setStartAngle(270D);
177             plot.setDirection(Rotation.CLOCKWISE);
178             plot.setForegroundAlpha(0.5F);
179
180             pieChart.setBackgroundPaint(Color.WHITE);
181             try {
182                 return saveChartForViewing(ctx, pieChart);
183             } catch (IOException JavaDoc e) {
184                 e.printStackTrace();
185                 ctx.setError("There was a problem generating the pie chart.");
186             }
187         } else {
188             ctx.setError("There must be a project in the context to generate project percent activity pie chart.");
189         }
190         return null;
191     }
192
193     public String JavaDoc generateAndSaveProjectTotalsXYLineChart(CoefficientContext ctx,
194                                                           int daysToInclude) {
195         Project prj = ctx.getProject();
196         if(prj != null) {
197             ProjectStatistics prjStats = prj.getStatistics();
198             // Make sure we have the latest and greatest from the DB
199
try {
200                 HibernateUtil.refresh(prjStats);
201             } catch(HibernateException he) {
202                 // do nothing just work with what we have
203
he.printStackTrace();
204             }
205
206             // Generate the XY Graph
207
TimeTableXYDataset dataset = new TimeTableXYDataset();
208             HashMap JavaDoc projectStats = new HashMap JavaDoc();
209
210             Map JavaDoc projectTotalStats = prjStats
211                 .getTotalActivityForNumberOfDaysIncludingToday(daysToInclude);
212
213             Map JavaDoc projectViewStats = prjStats
214                 .getViewActivityForNumberOfDaysIncludingToday(daysToInclude);
215
216             Map JavaDoc projectDownloadStats = prjStats
217                 .getDownloadActivityForNumberOfDaysIncludingToday(daysToInclude);
218                              
219             addDataToDataset(projectTotalStats, dataset, "Total Activity");
220             addDataToDataset(projectViewStats, dataset, StringUtils.capitalise(ProjectConstants.PROJECT_NAME) + " Views");
221             addDataToDataset(projectDownloadStats, dataset, StringUtils.capitalise(ProjectConstants.PROJECT_NAME) + " Downloads");
222             NumberAxis yAxis = new NumberAxis("activity");
223             DateAxis xAxis = new DateAxis("past " + daysToInclude + " days");
224             XYItemRenderer renderer = new StandardXYItemRenderer(StandardXYItemRenderer.LINES);
225             XYPlot plot = new XYPlot(dataset, xAxis, yAxis, renderer);
226             plot.setOrientation(PlotOrientation.VERTICAL);
227             renderer.setToolTipGenerator(new StandardXYToolTipGenerator());
228             JFreeChart lineChart = new JFreeChart("Statistics for: "
229                                                   + prj.getName(),
230                                                   JFreeChart.DEFAULT_TITLE_FONT,
231                                                   plot, true);
232             lineChart.setBackgroundPaint(Color.WHITE);
233             try {
234                 return saveChartForViewing(ctx, lineChart);
235             } catch (IOException JavaDoc e) {
236                 e.printStackTrace();
237                 ctx.setError("There was a problem generating the graph for project totals");
238             }
239         } else {
240             ctx.setError("There must be a project in the context to generate project totals graph.");
241         }
242         return null;
243     }
244
245     public ArrayList JavaDoc generateAndSaveModuleXYLineCharts(CoefficientContext ctx,
246                                                        int daysToInclude) {
247         ArrayList JavaDoc retVals = new ArrayList JavaDoc();
248         Project prj = ctx.getProject();
249         if(prj != null) {
250             ProjectStatistics prjStats = prj.getStatistics();
251             // Make sure we have the latest and greatest from the DB
252
try {
253                 HibernateUtil.refresh(prjStats);
254             } catch(HibernateException he) {
255                 // do nothing just work with what we have
256
he.printStackTrace();
257             }
258
259             for(Iterator JavaDoc it = prjStats.getModuleStatistics().keySet().iterator();
260                 it.hasNext(); ) {
261                 String JavaDoc modName = (String JavaDoc)it.next();
262                 ModuleStatistics modStats =
263                     (ModuleStatistics)prjStats.getModuleStatistics().get(modName);
264                 /*
265                   Map completeStats = modStats
266                   .getActivityForNumberOfDaysIncludingToday(daysToInclude,
267                   "complete");
268                 */

269                 Map JavaDoc createStats = modStats
270                     .getActivityForNumberOfDaysIncludingToday(daysToInclude,
271                                                               "create");
272                 Map JavaDoc updateStats = modStats
273                     .getActivityForNumberOfDaysIncludingToday(daysToInclude,
274                                                               "update");
275
276                 // Generate the XY Graph
277
TimeTableXYDataset dataset = new TimeTableXYDataset();
278
279                 //addDataToDataset(completeStats, dataset, "Number of Completions");
280
addDataToDataset(createStats, dataset, "Number of Creations");
281                 addDataToDataset(updateStats, dataset, "Number of Updates");
282
283                 NumberAxis yAxis = new NumberAxis("amount");
284                 DateAxis xAxis = new DateAxis("past " + daysToInclude + " days");
285                 XYItemRenderer renderer =
286                     new StandardXYItemRenderer(StandardXYItemRenderer.LINES);
287                 XYPlot plot = new XYPlot(dataset, xAxis, yAxis, renderer);
288                 plot.setOrientation(PlotOrientation.VERTICAL);
289                 renderer.setToolTipGenerator(new StandardXYToolTipGenerator());
290                 JFreeChart lineChart = new JFreeChart("Summary for Module: "
291                                                       + modName,
292                                                       JFreeChart.DEFAULT_TITLE_FONT,
293                                                       plot, true);
294                 lineChart.setBackgroundPaint(Color.WHITE);
295                 try {
296                     retVals.add(saveChartForViewing(ctx, lineChart));
297                 } catch (IOException JavaDoc e) {
298                     e.printStackTrace();
299                     ctx.setError("There was a problem generating the graph for "
300                                  + modName + " summary.");
301                 }
302             }
303         } else {
304             ctx.setError("There must be a project in the context to generate modules stats graphs.");
305         }
306         return retVals;
307     }
308
309     public String JavaDoc saveChartForViewing(CoefficientContext ctx, JFreeChart jfc)
310         throws IOException JavaDoc
311     {
312         String JavaDoc fileName = ServletUtilities
313             .saveChartAsJPEG(jfc, Constants.STATISTICS_GRAPH_WIDTH,
314                              Constants.STATISTICS_GRAPH_HEIGHT, null);
315         registerChartForDeletion(fileName, ctx);
316         return fileName;
317     }
318
319     private void addDataToDataset(Map JavaDoc dateDataMap, TimeTableXYDataset dataset,
320                                   String JavaDoc seriesName) {
321         for(Iterator JavaDoc it = dateDataMap.keySet().iterator(); it.hasNext(); ) {
322             Date JavaDoc xValue = (Date JavaDoc)it.next();
323             Long JavaDoc yValue = (Long JavaDoc)dateDataMap.get(xValue);
324             Day day = new Day(xValue);
325             dataset.add(day, yValue, seriesName, false);
326         }
327     }
328
329     /**
330      * Adds a ChartDeleter object to the session object with the name JFreeChart_Deleter
331      * if there is not already one bound to the session and adds the filename to the
332      * list of charts to be deleted.
333      *
334      * @param tempFile the file to be deleted.
335      * @param ctx the coefficient context
336      */

337     private void registerChartForDeletion(String JavaDoc fileName, CoefficientContext ctx) {
338
339         // Add chart to deletion list in session
340
if (ctx != null) {
341             ChartDeleter chartDeleter =
342                 (ChartDeleter) ctx.getSessionAttribute("JFreeChart_Deleter");
343             if (chartDeleter == null) {
344                 chartDeleter = new ChartDeleter();
345                 ctx.setSessionAttribute("JFreeChart_Deleter", chartDeleter);
346             }
347             chartDeleter.addChart(fileName);
348         } else {
349             System.out.println("CoefficientContext is null - chart will not be deleted");
350         }
351     }
352
353 }
354
Popular Tags