1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.syncope.client.console.chartjs;
20
21 import com.fasterxml.jackson.annotation.JsonInclude.Include;
22 import com.fasterxml.jackson.core.JsonProcessingException;
23 import com.fasterxml.jackson.databind.json.JsonMapper;
24 import org.apache.wicket.markup.html.WebMarkupContainer;
25 import org.apache.wicket.markup.html.panel.Panel;
26 import org.apache.wicket.model.IModel;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
29
30 public class ChartJSPanel extends Panel {
31
32 private static final long serialVersionUID = -3844680585650585253L;
33
34 private static final Logger LOG = LoggerFactory.getLogger(ChartJSPanel.class);
35
36 private static final JsonMapper MAPPER = JsonMapper.builder().
37 findAndAddModules().serializationInclusion(Include.NON_NULL).build();
38
39 private final IModel<? extends Chart<?>> model;
40
41 private final WebMarkupContainer container;
42
43 public ChartJSPanel(
44 final String id,
45 final IModel<? extends Chart<?>> model) {
46
47 super(id, model);
48
49 this.model = model;
50 this.container = new WebMarkupContainer("chart");
51 }
52
53 @Override
54 protected void onInitialize() {
55 super.onInitialize();
56 add(container);
57 container.setOutputMarkupId(true);
58 container.add(new ChartJSBehavior());
59 }
60
61 public Chart<?> getChart() {
62 return model.getObject();
63 }
64
65 public String generateChart(final String markupId) {
66 String dataString = null;
67 String optionString = null;
68 try {
69 Object data = (model.getObject() instanceof SimpleChart)
70 ? ((SimpleChart) model.getObject()).getData()
71 : ((DataSetChart) model.getObject()).getData();
72 dataString = MAPPER.writeValueAsString(data);
73 optionString = MAPPER.writeValueAsString(model.getObject().getOptions());
74 } catch (JsonProcessingException e) {
75 LOG.error("Unexpected error during JSON serialization", e);
76 }
77
78 return "WicketCharts['" + markupId + "'] = new Chart("
79 + "getChartCtx('" + markupId + "'),"
80 + "{"
81 + "type: '" + model.getObject().getClass().getSimpleName().toLowerCase() + "',"
82 + "data: " + dataString + ","
83 + "options:" + optionString
84 + "})";
85 }
86 }