39975438910e048e43cc7206c305d6e478801953
[jalview.git] / src / jalview / analytics / GoogleAnalytics4.java
1 package jalview.analytics;
2
3 import java.io.IOException;
4 import java.io.OutputStream;
5 import java.net.HttpURLConnection;
6 import java.net.MalformedURLException;
7 import java.net.URL;
8 import java.net.URLConnection;
9 import java.net.URLEncoder;
10 import java.nio.charset.StandardCharsets;
11 import java.util.AbstractMap;
12 import java.util.ArrayList;
13 import java.util.List;
14 import java.util.Map;
15 import java.util.Random;
16 import java.util.UUID;
17
18 import jalview.bin.Console;
19
20 public class GoogleAnalytics4
21 {
22   private static final String JALVIEW_ID = "Jalview Desktop";
23
24   private static final String SESSION_ID = new Random().toString();
25
26   private static final String MEASUREMENT_ID = "G-6TMPHMXEQ0";
27
28   private static final String API_SECRET = "Qb9NSbqkRDqizG6j2BBJ2g";
29
30   // This will generate a different CLIENT_ID each time the application is
31   // launched. Do we want to store it in .jalview_properties?
32   private static final String CLIENT_ID = UUID.randomUUID().toString();
33
34   private static final String BASE_URL = "https://www.google-analytics.com/mp/collect";
35
36   private List<Map.Entry<String, String>> queryStringValues;
37
38   private List<Map.Entry<String, Object>> jsonObject;
39
40   private List<Event> events;
41
42   private List<Map.Entry<String, String>> cookieValues;
43
44   private static boolean ENABLED = false;
45
46   public GoogleAnalytics4()
47   {
48     this.reset();
49   }
50
51   private static void setEnabled(boolean b)
52   {
53     ENABLED = b;
54   }
55
56   public void sendAnalytics()
57   {
58     sendAnalytics(null);
59   }
60
61   public void sendAnalytics(String path)
62   {
63     if (!ENABLED)
64     {
65       Console.debug("GoogleAnalytics4 not enabled.");
66       return;
67     }
68     if (path != null)
69     {
70       addEvent("page_event", path);
71     }
72     addQueryStringValue("measurement_id", MEASUREMENT_ID);
73     addQueryStringValue("api_secret", API_SECRET);
74     addJsonValue("client_id", CLIENT_ID);
75     addJsonValues("events", Event.toObjectList(events));
76     // addJsonValue("events", )
77     StringBuilder urlSb = new StringBuilder();
78     urlSb.append(BASE_URL);
79     urlSb.append('?');
80     urlSb.append(buildQueryString());
81     try
82     {
83       URL url = new URL(urlSb.toString());
84       URLConnection urlConnection = url.openConnection();
85       HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
86       httpURLConnection.setRequestMethod("POST");
87       httpURLConnection.setDoOutput(true);
88
89       String jsonString = buildJson();
90
91       Console.debug("##### HTTP Request is: '" + urlSb.toString() + "'");
92       Console.debug("##### POSTed JSON is:\n" + jsonString);
93
94       byte[] jsonBytes = jsonString.getBytes(StandardCharsets.UTF_8);
95       int jsonLength = jsonBytes.length;
96
97       httpURLConnection.setFixedLengthStreamingMode(jsonLength);
98       httpURLConnection.setRequestProperty("Content-Type",
99               "application/json; charset=UTF-8");
100       httpURLConnection.connect();
101       try (OutputStream os = httpURLConnection.getOutputStream())
102       {
103         os.write(jsonBytes);
104       }
105       int responseCode = httpURLConnection.getResponseCode();
106       String responseMessage = httpURLConnection.getResponseMessage();
107       if (responseCode < 200 || responseCode > 299)
108       {
109         Console.warn("GoogleAnalytics4 connection failed: '" + responseCode
110                 + " " + responseMessage + "'");
111       }
112       else
113       {
114         Console.debug("GoogleAnalytics4 connection succeeded: '"
115                 + responseCode + " " + responseMessage + "'");
116       }
117     } catch (MalformedURLException e)
118     {
119       Console.debug(
120               "Somehow the GoogleAnalytics4 BASE_URL and queryString is malformed.",
121               e);
122       return;
123     } catch (IOException e)
124     {
125       Console.debug("Connection to GoogleAnalytics4 BASE_URL '" + BASE_URL
126               + "' failed.", e);
127     } catch (ClassCastException e)
128     {
129       Console.debug(
130               "Couldn't cast URLConnection to HttpURLConnection in GoogleAnalytics4.",
131               e);
132     }
133   }
134
135   public void addEvent(String name, String... paramsStrings)
136   {
137     if (paramsStrings.length % 2 != 0)
138     {
139       Console.error(
140               "Cannot addEvent with odd number of paramsStrings.  Ignoring.");
141       return;
142     }
143     Event event = new Event(name);
144     for (int i = 0; i < paramsStrings.length - 1; i += 2)
145     {
146       String key = paramsStrings[i];
147       String value = paramsStrings[i + 1];
148       event.addParam(key, value);
149     }
150     events.add(event);
151   }
152
153   private void addJsonObject(String key,
154           List<Map.Entry<String, Object>> object)
155   {
156     jsonObject.add(objectEntry(key, object));
157   }
158
159   private void addJsonValues(String key, List<Object> values)
160   {
161     jsonObject.add(objectEntry(key, values));
162   }
163
164   private void addJsonValue(String key, String value)
165   {
166     jsonObject.add(objectEntry(key, value));
167   }
168
169   private void addJsonValue(String key, int value)
170   {
171     jsonObject.add(objectEntry(key, Integer.valueOf(value)));
172   }
173
174   private void addJsonValue(String key, boolean value)
175   {
176     jsonObject.add(objectEntry(key, Boolean.valueOf(value)));
177   }
178
179   private void addQueryStringValue(String key, String value)
180   {
181     queryStringValues.add(stringEntry(key, value));
182   }
183
184   private void addCookieValue(String key, String value)
185   {
186     cookieValues.add(stringEntry(key, value));
187   }
188
189   public void reset()
190   {
191     jsonObject = new ArrayList<>();
192     events = new ArrayList<Event>();
193     queryStringValues = new ArrayList<>();
194     cookieValues = new ArrayList<>();
195   }
196
197   private String buildQueryString()
198   {
199     StringBuilder sb = new StringBuilder();
200     for (Map.Entry<String, String> entry : queryStringValues)
201     {
202       if (sb.length() > 0)
203       {
204         sb.append('&');
205       }
206       sb.append(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8));
207       sb.append('=');
208       sb.append(
209               URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8));
210     }
211     return sb.toString();
212   }
213
214   private void buildCookieHeaders()
215   {
216     // TODO not needed yet
217   }
218
219   private String buildJson()
220   {
221     StringBuilder sb = new StringBuilder();
222     addJsonObject(sb, 0, jsonObject);
223     return sb.toString();
224   }
225
226   private void addJsonObject(StringBuilder sb, int indent,
227           List<Map.Entry<String, Object>> entries)
228   {
229     indent(sb, indent);
230     sb.append("{\n");
231     for (Map.Entry<String, Object> entry : entries)
232     {
233       String key = entry.getKey();
234       // TODO sensibly escape " characters in key
235       Object value = entry.getValue();
236       indent(sb, indent);
237       sb.append('"').append(key).append('"');
238       sb.append(": ");
239       if (List.class.equals(value.getClass()))
240       {
241         sb.append('\n');
242       }
243       addJsonValue(sb, indent + 1, value);
244       sb.append(",\n");
245     }
246     sb.append("}\n");
247   }
248
249   private void addJsonValue(StringBuilder sb, int indent, Object value)
250   {
251     if (value == null)
252     {
253       return;
254     }
255     try
256     {
257       Class<? extends Object> c = value.getClass();
258       if (Map.Entry.class.equals(c))
259       {
260         Map.Entry<String, Object> entry = (Map.Entry<String, Object>) value;
261         List<Map.Entry<String, Object>> object = new ArrayList<>();
262         object.add(entry);
263         addJsonObject(sb, indent + 1, object);
264       }
265       else if (List.class.equals(c))
266       {
267         // list of Map.Entries or list of values?
268         List<Object> valueList = (List<Object>) value;
269         if (valueList.size() > 0
270                 && Map.Entry.class.equals(valueList.get(0).getClass()))
271         {
272           // entries
273           indent(sb, indent);
274           List<Map.Entry<String, Object>> entryList = (List<Map.Entry<String, Object>>) value;
275           addJsonObject(sb, indent + 1, entryList);
276         }
277         else
278         {
279           // values
280           indent(sb, indent);
281           sb.append("[\n");
282           for (Object v : valueList)
283           {
284             indent(sb, indent + 1);
285             addJsonValue(sb, indent + 1, v);
286             sb.append(",\n");
287           }
288           indent(sb, indent);
289           sb.append("]");
290         }
291       }
292       else if (String.class.equals(c))
293       {
294         sb.append('"');
295         sb.append((String) value);
296         sb.append('"');
297       }
298       else if (Integer.class.equals(c))
299       {
300         sb.append(((Integer) value).toString());
301       }
302       else if (Boolean.class.equals(c))
303       {
304         sb.append(((Boolean) value).toString());
305       }
306     } catch (ClassCastException e)
307     {
308       Console.debug(
309               "Could not deal with type of jsonObject " + value.toString(),
310               e);
311     }
312   }
313
314   private void indent(StringBuilder sb, int indent)
315   {
316     sb.append("  ".repeat(indent));
317   }
318
319   protected static Map.Entry<String, Object> objectEntry(String s, Object o)
320   {
321     return new AbstractMap.SimpleEntry<String, Object>(s, o);
322   }
323
324   protected static Map.Entry<String, String> stringEntry(String s, String v)
325   {
326     return new AbstractMap.SimpleEntry<String, String>(s, v);
327   }
328 }
329
330 class Event
331 {
332   private String name;
333
334   private List<Map.Entry<String, String>> params;
335
336   @SafeVarargs
337   public Event(String name, Map.Entry<String, String>... paramEntries)
338   {
339     this.name = name;
340     this.params = new ArrayList<Map.Entry<String, String>>();
341     for (Map.Entry<String, String> paramEntry : paramEntries)
342     {
343       if (paramEntry == null)
344       {
345         continue;
346       }
347       params.add(paramEntry);
348     }
349   }
350
351   public void addParam(String param, String value)
352   {
353     params.add(GoogleAnalytics4.stringEntry(param, value));
354   }
355
356   protected List<Map.Entry<String, Object>> toObject()
357   {
358     List<Map.Entry<String, Object>> object = new ArrayList<>();
359     object.add(GoogleAnalytics4.objectEntry("name", (Object) name));
360     if (params.size() > 0)
361     {
362       object.add(GoogleAnalytics4.objectEntry("params", (Object) params));
363     }
364     return object;
365   }
366
367   protected static List<Object> toObjectList(List<Event> events)
368   {
369     List<Object> eventObjectList = new ArrayList<>();
370     for (Event event : events)
371     {
372       eventObjectList.add((Object) event.toObject());
373     }
374     return eventObjectList;
375   }
376 }