Thursday, April 11, 2013

JSF 2.x Tip of the Day: RichFaces 4.3.x Charts in JSF using JSFlot, JFreeCharts, and PrimeFaces

Sexy PrimeFaces Charts in RichFaces

Introduction

I was asked to look at various charting solutions for JSF. Specifically, I was asked for some choices for use with RichFaces 4.3.1. I knew that PrimeFaces has really good chart components already so I knew it might be kind of fun to integrate them if possible. I was also aware of JFreeChart which will work, but produces some... rather ugly charts. Finally, someone had suggested that I look at jsflot. This was a very promising solution. This project is a proof of concept which demonstrates integration between projects, and technologies.

Requirements

  • jsflot
  • NetBeans This is required for the sample database, although you could create your own data.
The jsflot framework is currently not Mavenized, so if you are going to run my example code, you will need to download it from the link above, and install it in Maven using the command below.
1
mvn install:install-file -Dfile=jsflot-0.7.0.jar -DgroupId=org.jsflot -DartifactId=jsflot -Dversion=0.7.0 -Dpackaging=jar -Dsource=jsflot-0.7.0-src.zip

Code

The code for this NetBeans Maven project can be found on BitBucket here: chart-demo

This is the bean that provides the data models for the charting solutions. There are a number of chart demos in the project. The two charts above are just examples.

ChartBean.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
package com.bluelotussoftware.example.jsf;
 
import com.bluelotussoftware.example.model.Customer;
import com.bluelotussoftware.example.model.Product;
import com.bluelotussoftware.example.model.PurchaseOrder;
import com.bluelotussoftware.example.ssb.CustomerFacade;
import com.bluelotussoftware.example.ssb.ProductFacade;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.imageio.ImageIO;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
import org.jsflot.components.FlotChartRendererData;
import org.jsflot.xydata.XYDataList;
import org.jsflot.xydata.XYDataPoint;
import org.jsflot.xydata.XYDataSetCollection;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.primefaces.model.chart.BubbleChartModel;
import org.primefaces.model.chart.BubbleChartSeries;
import org.primefaces.model.chart.CartesianChartModel;
import org.primefaces.model.chart.ChartSeries;
import org.primefaces.model.chart.MeterGaugeChartModel;
import org.primefaces.model.chart.PieChartModel;
 
/**
 *
 * @author John Yeary
 * @version 1.0
 */
@ManagedBean
@RequestScoped
public class ChartBean {
 
    private Map<Integer, Map<String, Number>> CustomerPurchasesByYearTotals = new HashMap<Integer, Map<String, Number>>();
    private double totalSales;
    //PrimeFaces
    private PieChartModel pieChartModel;
    private CartesianChartModel cartesianChartModel;
    private BubbleChartModel bubbleChartModel;
    private MeterGaugeChartModel meterGaugeChartModel;
    //JSFlot
    private XYDataList series1DataList = new XYDataList();
    private XYDataList series2DataList = new XYDataList();
    private XYDataList series3DataList = new XYDataList();
    private FlotChartRendererData chartData;
    private StreamedContent streamedContent;
    @EJB
    private CustomerFacade cf;
    @EJB
    private ProductFacade pf;
 
    /**
     * Creates a new instance of ChartBean
     */
    public ChartBean() {
    }
 
    @PostConstruct
    private void initialize() throws IOException {
        bubbleChartModel = new BubbleChartModel();
        cartesianChartModel = new CartesianChartModel();
        pieChartModel = new PieChartModel(getSalesByCustomer());
        createCartesianChartModel();
        createBubbleModel();
        createMeterGaugeModel();
 
        //JFreeChart 
        JFreeChart jfreechart = ChartFactory.createPieChart("Products", getPartsDataset(), true, false, false);
        String path = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/");
        File chartFile = new File(path + "dynamichart.png");
        ChartUtilities.saveChartAsPNG(chartFile, jfreechart, 600, 400);
        streamedContent = new DefaultStreamedContent(new FileInputStream(chartFile), "image/png");
 
 
        chartData = new FlotChartRendererData();
 
        for (int i = 0; i <= 100; i++) {
            NumberFormat nf = NumberFormat.getNumberInstance();
            nf.setMaximumFractionDigits(3);
 
            series1DataList.addDataPoint(new XYDataPoint(i, Math.random() * 10, "Point: " + i));
            series2DataList.addDataPoint(new XYDataPoint(i, Math.random() * 10, "Point: " + i));
            series3DataList.addDataPoint(new XYDataPoint(i, Math.random() * 10));
        }
        series1DataList.setLabel("Series 1");
        series2DataList.setLabel("Series 2");
        series3DataList.setLabel("Series 3");
    }
 
    public PieChartModel getPieChartModel() {
        return pieChartModel;
    }
 
    public BubbleChartModel getBubbleChartModel() {
        return bubbleChartModel;
    }
 
    public CartesianChartModel getCartesianChartModel() {
        return cartesianChartModel;
    }
 
    public MeterGaugeChartModel getMeterGaugeChartModel() {
        return meterGaugeChartModel;
    }
 
    private Map<String, Number> getSalesByCustomer() {
        Map<String, Number> salesByCustomer = new HashMap<String, Number>();
 
        List<customer> customers = cf.findAll();
 
        for (Customer c : customers) {
            double sales = 0.0;
            for (PurchaseOrder p : c.getPurchaseOrderCollection()) {
                sales += p.getProductId().getPurchaseCost().doubleValue() * p.getQuantity();
            }
            salesByCustomer.put(c.getName(), sales);
        }
        return salesByCustomer;
    }
 
    private void createCartesianChartModel() {
        Calendar cal = Calendar.getInstance();
        List<customer> customers = cf.findAll();
        List<integer> customersLessThan10K = new ArrayList<integer>();
        List<integer> customersGreaterThan10K = new ArrayList<integer>();
        Collections.sort(customers);
 
        for (Customer c : customers) {
            double sales = 0.0;
 
            for (PurchaseOrder p : c.getPurchaseOrderCollection()) {
                cal.setTime(p.getSalesDate());
                double vx = p.getProductId().getPurchaseCost().doubleValue() * p.getQuantity();
                addOrUpdate(c.getCustomerId(), String.valueOf(cal.get(Calendar.YEAR)), vx);
                sales += vx;
            }
 
            if (sales < 10000.00) {
                customersLessThan10K.add(c.getCustomerId());
            } else {
                customersGreaterThan10K.add(c.getCustomerId());
            }
            totalSales += sales;
        }
 
        Map<Object, Number> lt10k = new HashMap<Object, Number>();
        Map<Object, Number> gt10k = new HashMap<Object, Number>();
 
        for (Integer i : customersLessThan10K) {
            populateMap(lt10k, CustomerPurchasesByYearTotals.get(i));
        }
 
        for (Integer i : customersGreaterThan10K) {
            populateMap(gt10k, CustomerPurchasesByYearTotals.get(i));
        }
 
        ChartSeries customersLessThan10k = new ChartSeries("Customers with Sales < 10K");
        customersLessThan10k.setData(lt10k);
        ChartSeries customersGreaterThan10k = new ChartSeries("Customers with Sales > 10K");
        customersGreaterThan10k.setData(gt10k);
        cartesianChartModel.addSeries(customersLessThan10k);
        cartesianChartModel.addSeries(customersGreaterThan10k);
    }
 
    private void addOrUpdate(Integer customerId, String year, Number value) {
        Map<String, Number> map = CustomerPurchasesByYearTotals.get(customerId);
 
        if (map == null) {
            map = new HashMap<String, Number>();
            CustomerPurchasesByYearTotals.put(customerId, map);
        }
        Number n = map.get(year);
 
        if (n == null) {
            map.put(year, value);
        } else {
            map.put(year, (map.get(year).doubleValue() + value.doubleValue()));
        }
    }
 
    private void populateMap(Map<Object, Number> map, Map<String, Number> data) {
        if (data == null) {
            return;
        }
        for (String key : data.keySet()) {
            Number n = map.get((Object) key);
            if (n == null) {
                map.put((Object) key, data.get(key));
            } else {
                map.put((Object) key, n.doubleValue() + data.get(key).doubleValue());
            }
        }
    }
 
    private void createBubbleModel() {
        for (Product p : pf.findAll()) {
            bubbleChartModel.add(new BubbleChartSeries(
                    p.getDescription(), //label
                    p.getQuantityOnHand(), // x
                    p.getMarkup().intValue(), //y
                    p.getPurchaseCost().intValue() //radius
                    ));
        }
    }
 
    private void createMeterGaugeModel() {
        List<number> intervals = new ArrayList<number>() {
            {
                add(200000);
                add(400000);
                add(600000);
                add(800000);
            }
        };
//        meterGaugeChartModel = new MeterGaugeChartModel("Sales", totalSales, intervals); //PrimeFaces 3.3+
        meterGaugeChartModel = new MeterGaugeChartModel(Double.valueOf(totalSales), intervals); //PrimeFaces 3.4+
    }
 
    public XYDataSetCollection getChartSeries() {
        XYDataSetCollection collection = new XYDataSetCollection();
        XYDataList currentSeries1DataList = new XYDataList();
        XYDataList currentSeries2DataList = new XYDataList();
        XYDataList currentSeries3DataList = new XYDataList();
 
        for (int i = 0; i <= 10; i++) {
            long startTime = 1196463600000l;
            if (chartData.getMode().equalsIgnoreCase("Time")) {
                XYDataPoint p1 = new XYDataPoint(series1DataList.get(i).getX(),
                        series1DataList.get(i).getY(), series1DataList.get(i).getPointLabel());
                p1.setX(startTime + (p1.getX().doubleValue() * 1000 * 60));
 
                XYDataPoint p2 = new XYDataPoint(series2DataList.get(i).getX(),
                        series2DataList.get(i).getY(), series2DataList.get(i).getPointLabel());
                p2.setX(startTime + (p2.getX().doubleValue() * 1000 * 60));
 
                XYDataPoint p3 = new XYDataPoint(series3DataList.get(i).getX(),
                        series3DataList.get(i).getY(), series3DataList.get(i).getPointLabel());
                p3.setX(startTime + (p3.getX().doubleValue() * 1000 * 60));
 
                currentSeries1DataList.addDataPoint(p1);
                currentSeries2DataList.addDataPoint(p2);
                currentSeries3DataList.addDataPoint(p3);
            } else {
                currentSeries1DataList.addDataPoint(series1DataList.get(i));
                currentSeries2DataList.addDataPoint(series2DataList.get(i));
                currentSeries3DataList.addDataPoint(series3DataList.get(i));
            }
        }
        currentSeries1DataList.setLabel(series1DataList.getLabel());
        currentSeries1DataList.setFillLines(series1DataList.isFillLines());
        currentSeries1DataList.setMarkerPosition(series1DataList.getMarkerPosition());
        currentSeries1DataList.setMarkers(series1DataList.isMarkers());
        currentSeries1DataList.setShowDataPoints(series1DataList.isShowDataPoints());
        currentSeries1DataList.setShowLines(series1DataList.isShowLines());
 
        currentSeries2DataList.setLabel(series2DataList.getLabel());
        currentSeries2DataList.setFillLines(series2DataList.isFillLines());
        currentSeries2DataList.setMarkerPosition(series2DataList.getMarkerPosition());
        currentSeries2DataList.setMarkers(series2DataList.isMarkers());
        currentSeries2DataList.setShowDataPoints(series2DataList.isShowDataPoints());
        currentSeries2DataList.setShowLines(series2DataList.isShowLines());
 
        currentSeries3DataList.setLabel(series3DataList.getLabel());
        currentSeries3DataList.setFillLines(series3DataList.isFillLines());
        currentSeries3DataList.setMarkerPosition(series3DataList.getMarkerPosition());
        currentSeries3DataList.setMarkers(series3DataList.isMarkers());
        currentSeries3DataList.setShowDataPoints(series3DataList.isShowDataPoints());
        currentSeries3DataList.setShowLines(series3DataList.isShowLines());
 
        collection.addDataList(currentSeries1DataList);
        collection.addDataList(currentSeries2DataList);
        collection.addDataList(currentSeries3DataList);
        return collection;
    }
 
    public FlotChartRendererData getChartData() {
        return chartData;
    }
 
    public void setChartData(FlotChartRendererData chartData) {
        this.chartData = chartData;
    }
 
    public XYDataList getSeries1DataList() {
        return series1DataList;
    }
 
    public void setSeries1DataList(XYDataList series1DataList) {
        this.series1DataList = series1DataList;
    }
 
    public XYDataList getSeries2DataList() {
        return series2DataList;
    }
 
    public void setSeries2DataList(XYDataList series2DataList) {
        this.series2DataList = series2DataList;
    }
 
    public XYDataList getSeries3DataList() {
        return series3DataList;
    }
 
    public void setSeries3DataList(XYDataList series3DataList) {
        this.series3DataList = series3DataList;
    }
 
    public void generateChartMethod(OutputStream out, Object data) throws IOException {
        JFreeChart chart = ChartFactory.createPieChart3D("Products", getPartsDataset(), false, false, false);
        BufferedImage buffImg = chart.createBufferedImage(600, 400, BufferedImage.TYPE_INT_RGB, null);
        ImageIO.write(buffImg, "png", out);
    }
 
    private PieDataset getPartsDataset() {
        DefaultPieDataset dataset = new DefaultPieDataset();
        double totalCost = 0.0;
        List<product> products = pf.findAll();
        for (Product p : products) {
            totalCost += p.getPurchaseCost().doubleValue();
        }
        for (Product p : products) {
            dataset.setValue(p.getDescription(), (p.getPurchaseCost().doubleValue() / totalCost));
        }
        return dataset;
    }
 
    public StreamedContent getStreamedContent() {
        return streamedContent;
    }
}

0 comments :

Popular Posts