James Moger
2011-12-28 abeaaf77673e9e764fe68e398eeda1e3c3c22ea5
commit | author | age
44bbc4 1 /*
db91a3 2  Copyright 2011 gitblit.com.
44bbc4 3
JM 4  Licensed under the Apache License, Version 2.0 (the "License");
5  you may not use this file except in compliance with the License.
6  You may obtain a copy of the License at
7
8      http://www.apache.org/licenses/LICENSE-2.0
9
10  Unless required by applicable law or agreed to in writing, software
11  distributed under the License is distributed on an "AS IS" BASIS,
12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  See the License for the specific language governing permissions and
14  limitations under the License.
15  */
16
17 package com.gitblit.wicket.charting;
18
19 import java.util.ArrayList;
20 import java.util.List;
21
22 import org.apache.wicket.markup.html.IHeaderContributor;
23 import org.apache.wicket.markup.html.IHeaderResponse;
24
25 /**
26  * The Google Visualization API provides interactive JavaScript based charts and
27  * graphs. This class implements the JavaScript header necessary to display
28  * complete graphs and charts.
29  * 
30  * @author James Moger
31  * 
32  */
33 public class GoogleCharts implements IHeaderContributor {
34
35     private static final long serialVersionUID = 1L;
36
db91a3 37     public final List<GoogleChart> charts = new ArrayList<GoogleChart>();
44bbc4 38
JM 39     public void addChart(GoogleChart chart) {
40         charts.add(chart);
41     }
42
43     @Override
44     public void renderHead(IHeaderResponse response) {
45         // add Google Chart JS API reference
46         response.renderJavascriptReference("https://www.google.com/jsapi");
47
48         // prepare draw chart function
49         StringBuilder sb = new StringBuilder();
50         line(sb, "google.load(\"visualization\", \"1\", {packages:[\"corechart\"]});");
51         line(sb, "google.setOnLoadCallback(drawChart);");
52         line(sb, "function drawChart() {");
53
54         // add charts to header
55         for (GoogleChart chart : charts) {
56             chart.appendChart(sb);
57         }
58
59         // end draw chart function
60         line(sb, "}");
61         response.renderJavascript(sb.toString(), null);
62     }
63
64     private void line(StringBuilder sb, String line) {
65         sb.append(line);
66         sb.append('\n');
67     }
68 }