JAL-4001 Changed for Java 8 compatibility
[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.io.UnsupportedEncodingException;
6 import java.net.HttpURLConnection;
7 import java.net.MalformedURLException;
8 import java.net.URL;
9 import java.net.URLConnection;
10 import java.net.URLEncoder;
11 import java.nio.charset.StandardCharsets;
12 import java.util.AbstractMap;
13 import java.util.ArrayList;
14 import java.util.Collections;
15 import java.util.HashMap;
16 import java.util.Iterator;
17 import java.util.List;
18 import java.util.Map;
19 import java.util.Random;
20 import java.util.UUID;
21
22 import jalview.bin.Cache;
23 import jalview.bin.Console;
24 import jalview.util.ChannelProperties;
25
26 public class GoogleAnalytics4
27 {
28   private static final String JALVIEW_ID = "Jalview Desktop";
29
30   private static final String SESSION_ID = new Random().toString();
31
32   private static final String MEASUREMENT_ID = "G-6TMPHMXEQ0";
33
34   private static final String API_SECRET = "Qb9NSbqkRDqizG6j2BBJ2g";
35
36   // This will generate a different CLIENT_ID each time the application is
37   // launched. Do we want to store it in .jalview_properties?
38   private static final String CLIENT_ID = UUID.randomUUID().toString();
39
40   private static final String BASE_URL = "https://www.google-analytics.com/mp/collect";
41
42   private static final String DESKTOP_EVENT = "desktop_event";
43
44   private List<Map.Entry<String, String>> queryStringValues;
45
46   private List<Map.Entry<String, Object>> jsonObject;
47
48   private List<Event> events;
49
50   private List<Map.Entry<String, String>> cookieValues;
51
52   private static boolean ENABLED = false;
53
54   private static GoogleAnalytics4 instance = null;
55
56   private static final Map<String, String> defaultParams;
57
58   static
59   {
60     defaultParams = new HashMap<>();
61     defaultParams.put("app_name",
62             ChannelProperties.getProperty("app_name") + " Desktop");
63     defaultParams.put("version", Cache.getProperty("VERSION"));
64     defaultParams.put("build_date",
65             Cache.getDefault("BUILD_DATE", "unknown"));
66     defaultParams.put("java_version", System.getProperty("java.version"));
67     String val = System.getProperty("sys.install4jVersion");
68     if (val != null)
69     {
70       defaultParams.put("install4j_version", val);
71     }
72     val = System.getProperty("installer_template_version");
73     if (val != null)
74     {
75       defaultParams.put("install4j_template_version", val);
76     }
77     val = System.getProperty("launcher_version");
78     if (val != null)
79     {
80       defaultParams.put("launcher_version", val);
81     }
82     defaultParams.put("java_arch",
83             System.getProperty("os.arch") + " "
84                     + System.getProperty("os.name") + " "
85                     + System.getProperty("os.version"));
86   }
87
88   private GoogleAnalytics4()
89   {
90     this.resetLists();
91   }
92
93   public static void setEnabled(boolean b)
94   {
95     ENABLED = b;
96   }
97
98   public void sendAnalytics(String eventName, String... paramsStrings)
99   {
100     sendAnalytics(eventName, false, paramsStrings);
101   }
102
103   /**
104    * The simplest way to send an analytic event.
105    * 
106    * @param eventName
107    *          The event name. To emulate a webpage view use "page_view" and set
108    *          a "page_location" parameter. See
109    *          https://developers.google.com/analytics/devguides/collection/ga4/events?client_type=gtag
110    * @param sendDefaultParams
111    *          Flag whether to add the default params about the application.
112    * @param paramsStrings
113    *          Optional multiple Strings in key, value pairs (there should be an
114    *          even number of paramsStrings) to be set as parameters of the
115    *          event. To emulate a webpage view use "page_location" as the URL in
116    *          a "page_view" event.
117    */
118   public void sendAnalytics(String eventName, boolean sendDefaultParams,
119           String... paramsStrings)
120   {
121     // clear out old lists
122     this.resetLists();
123
124     if (!ENABLED)
125     {
126       Console.debug("GoogleAnalytics4 not enabled.");
127       return;
128     }
129     Map<String, String> params = new HashMap<>();
130     params.put("event_category", DESKTOP_EVENT);
131     params.put("event_label", eventName);
132
133     // add these to all events from this application instance
134     if (sendDefaultParams)
135     {
136       params.putAll(defaultParams);
137     }
138
139     // add (and overwrite with) the passed in params
140     if (paramsStrings != null && paramsStrings.length > 0)
141     {
142       if (paramsStrings.length % 2 != 0)
143       {
144         Console.warn(
145                 "Cannot addEvent with odd number of paramsStrings.  Ignoring the last one.");
146       }
147       for (int i = 0; i < paramsStrings.length - 1; i += 2)
148       {
149         String key = paramsStrings[i];
150         String value = paramsStrings[i + 1];
151         params.put(key, value);
152       }
153     }
154
155     addEvent(eventName, params);
156     addQueryStringValue("measurement_id", MEASUREMENT_ID);
157     addQueryStringValue("api_secret", API_SECRET);
158     addJsonValue("client_id", CLIENT_ID);
159     addJsonValues("events", Event.toObjectList(events));
160     StringBuilder urlSb = new StringBuilder();
161     urlSb.append(BASE_URL);
162     urlSb.append('?');
163     urlSb.append(buildQueryString());
164     try
165     {
166       URL url = new URL(urlSb.toString());
167       URLConnection urlConnection = url.openConnection();
168       HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
169       httpURLConnection.setRequestMethod("POST");
170       httpURLConnection.setDoOutput(true);
171
172       String jsonString = buildJson();
173
174       Console.debug("GA4: HTTP Request is: '" + urlSb.toString() + "'");
175       Console.debug("GA4: POSTed JSON is:\n" + jsonString);
176
177       byte[] jsonBytes = jsonString.getBytes(StandardCharsets.UTF_8);
178       int jsonLength = jsonBytes.length;
179
180       httpURLConnection.setFixedLengthStreamingMode(jsonLength);
181       httpURLConnection.setRequestProperty("Content-Type",
182               "application/json; charset=UTF-8");
183       httpURLConnection.connect();
184       try (OutputStream os = httpURLConnection.getOutputStream())
185       {
186         os.write(jsonBytes);
187       }
188       int responseCode = httpURLConnection.getResponseCode();
189       String responseMessage = httpURLConnection.getResponseMessage();
190       if (responseCode < 200 || responseCode > 299)
191       {
192         Console.warn("GoogleAnalytics4 connection failed: '" + responseCode
193                 + " " + responseMessage + "'");
194       }
195       else
196       {
197         Console.debug("GoogleAnalytics4 connection succeeded: '"
198                 + responseCode + " " + responseMessage + "'");
199       }
200     } catch (MalformedURLException e)
201     {
202       Console.debug(
203               "Somehow the GoogleAnalytics4 BASE_URL and queryString is malformed.",
204               e);
205       return;
206     } catch (IOException e)
207     {
208       Console.debug("Connection to GoogleAnalytics4 BASE_URL '" + BASE_URL
209               + "' failed.", e);
210     } catch (ClassCastException e)
211     {
212       Console.debug(
213               "Couldn't cast URLConnection to HttpURLConnection in GoogleAnalytics4.",
214               e);
215     }
216   }
217
218   public void addEvent(String name, Map<String, String> params)
219   {
220     Event event = new Event(name);
221     if (params != null && params.size() > 0)
222     {
223       for (String key : params.keySet())
224       {
225         String value = params.get(key);
226         event.addParam(key, value);
227       }
228     }
229     events.add(event);
230   }
231
232   private void addJsonObject(String key,
233           List<Map.Entry<String, Object>> object)
234   {
235     jsonObject.add(objectEntry(key, object));
236   }
237
238   private void addJsonValues(String key, List<Object> values)
239   {
240     jsonObject.add(objectEntry(key, values));
241   }
242
243   private void addJsonValue(String key, String value)
244   {
245     jsonObject.add(objectEntry(key, value));
246   }
247
248   private void addJsonValue(String key, int value)
249   {
250     jsonObject.add(objectEntry(key, Integer.valueOf(value)));
251   }
252
253   private void addJsonValue(String key, boolean value)
254   {
255     jsonObject.add(objectEntry(key, Boolean.valueOf(value)));
256   }
257
258   private void addQueryStringValue(String key, String value)
259   {
260     queryStringValues.add(stringEntry(key, value));
261   }
262
263   private void addCookieValue(String key, String value)
264   {
265     cookieValues.add(stringEntry(key, value));
266   }
267
268   private void resetLists()
269   {
270     jsonObject = new ArrayList<>();
271     events = new ArrayList<Event>();
272     queryStringValues = new ArrayList<>();
273     cookieValues = new ArrayList<>();
274   }
275
276   public static GoogleAnalytics4 getInstance()
277   {
278     if (instance == null)
279     {
280       instance = new GoogleAnalytics4();
281     }
282     return instance;
283   }
284
285   public static void reset()
286   {
287     getInstance().resetLists();
288   }
289
290   private String buildQueryString()
291   {
292     StringBuilder sb = new StringBuilder();
293     for (Map.Entry<String, String> entry : queryStringValues)
294     {
295       if (sb.length() > 0)
296       {
297         sb.append('&');
298       }
299       try
300       {
301         sb.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
302       } catch (UnsupportedEncodingException e)
303       {
304         sb.append(entry.getKey());
305       }
306       sb.append('=');
307       try
308       {
309         sb.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
310       } catch (UnsupportedEncodingException e)
311       {
312         sb.append(entry.getValue());
313       }
314     }
315     return sb.toString();
316   }
317
318   private void buildCookieHeaders()
319   {
320     // TODO not needed yet
321   }
322
323   private String buildJson()
324   {
325     StringBuilder sb = new StringBuilder();
326     addJsonObject(sb, 0, jsonObject);
327     return sb.toString();
328   }
329
330   private void addJsonObject(StringBuilder sb, int indent,
331           List<Map.Entry<String, Object>> entries)
332   {
333     indent(sb, indent);
334     sb.append('{');
335     newline(sb);
336     Iterator<Map.Entry<String, Object>> entriesI = entries.iterator();
337     while (entriesI.hasNext())
338     {
339       Map.Entry<String, Object> entry = entriesI.next();
340       String key = entry.getKey();
341       // TODO sensibly escape " characters in key
342       Object value = entry.getValue();
343       indent(sb, indent + 1);
344       sb.append('"').append(quoteEscape(key)).append('"').append(':');
345       space(sb);
346       if (value != null && value instanceof List)
347       {
348         newline(sb);
349       }
350       addJsonValue(sb, indent + 2, value);
351       if (entriesI.hasNext())
352       {
353         sb.append(',');
354       }
355       newline(sb);
356     }
357     indent(sb, indent);
358     sb.append('}');
359   }
360
361   private void addJsonValue(StringBuilder sb, int indent, Object value)
362   {
363     if (value == null)
364     {
365       return;
366     }
367     try
368     {
369       if (value instanceof Map.Entry)
370       {
371         Map.Entry<String, Object> entry = (Map.Entry<String, Object>) value;
372         List<Map.Entry<String, Object>> object = new ArrayList<>();
373         object.add(entry);
374         addJsonObject(sb, indent, object);
375       }
376       else if (value instanceof List)
377       {
378         // list of Map.Entries or list of values?
379         List<Object> valueList = (List<Object>) value;
380         if (valueList.size() > 0 && valueList.get(0) instanceof Map.Entry)
381         {
382           // entries
383           // indent(sb, indent);
384           List<Map.Entry<String, Object>> entryList = (List<Map.Entry<String, Object>>) value;
385           addJsonObject(sb, indent, entryList);
386         }
387         else
388         {
389           // values
390           indent(sb, indent);
391           sb.append('[');
392           newline(sb);
393           Iterator<Object> valueListI = valueList.iterator();
394           while (valueListI.hasNext())
395           {
396             Object v = valueListI.next();
397             addJsonValue(sb, indent + 1, v);
398             if (valueListI.hasNext())
399             {
400               sb.append(',');
401             }
402             newline(sb);
403           }
404           indent(sb, indent);
405           sb.append("]");
406         }
407       }
408       else if (value instanceof String)
409       {
410         sb.append('"').append(quoteEscape((String) value)).append('"');
411       }
412       else if (value instanceof Integer)
413       {
414         sb.append(((Integer) value).toString());
415       }
416       else if (value instanceof Boolean)
417       {
418         sb.append('"').append(((Boolean) value).toString()).append('"');
419       }
420     } catch (ClassCastException e)
421     {
422       Console.debug(
423               "Could not deal with type of json Object " + value.toString(),
424               e);
425     }
426   }
427
428   private static String quoteEscape(String s)
429   {
430     if (s == null)
431     {
432       return null;
433     }
434     // this escapes quotation marks (") that aren't already escaped (in the
435     // string) ready to go into a quoted JSON string value
436     return s.replaceAll("((?<!\\\\)(?:\\\\{2})*)\"", "$1\\\\\"");
437   }
438
439   private static void prettyWhitespace(StringBuilder sb, String whitespace,
440           int repeat)
441   {
442     // only add whitespace if we're in DEBUG mode
443     if (!Console.getLogger().isDebugEnabled())
444     {
445       return;
446     }
447     if (repeat >= 0 && whitespace != null)
448     {
449       // sb.append(whitespace.repeat(repeat));
450       sb.append(String.join("", Collections.nCopies(repeat, whitespace)));
451
452     }
453     else
454     {
455       sb.append(whitespace);
456     }
457   }
458
459   private static void indent(StringBuilder sb, int indent)
460   {
461     prettyWhitespace(sb, "  ", indent);
462   }
463
464   private static void newline(StringBuilder sb)
465   {
466     prettyWhitespace(sb, "\n", -1);
467   }
468
469   private static void space(StringBuilder sb)
470   {
471     prettyWhitespace(sb, " ", -1);
472   }
473
474   protected static Map.Entry<String, Object> objectEntry(String s, Object o)
475   {
476     return new AbstractMap.SimpleEntry<String, Object>(s, o);
477   }
478
479   protected static Map.Entry<String, String> stringEntry(String s, String v)
480   {
481     return new AbstractMap.SimpleEntry<String, String>(s, v);
482   }
483 }
484
485 class Event
486 {
487   private String name;
488
489   private List<Map.Entry<String, String>> params;
490
491   @SafeVarargs
492   public Event(String name, Map.Entry<String, String>... paramEntries)
493   {
494     this.name = name;
495     this.params = new ArrayList<Map.Entry<String, String>>();
496     for (Map.Entry<String, String> paramEntry : paramEntries)
497     {
498       if (paramEntry == null)
499       {
500         continue;
501       }
502       params.add(paramEntry);
503     }
504   }
505
506   public void addParam(String param, String value)
507   {
508     params.add(GoogleAnalytics4.stringEntry(param, value));
509   }
510
511   protected List<Map.Entry<String, Object>> toObject()
512   {
513     List<Map.Entry<String, Object>> object = new ArrayList<>();
514     object.add(GoogleAnalytics4.objectEntry("name", (Object) name));
515     if (params.size() > 0)
516     {
517       object.add(GoogleAnalytics4.objectEntry("params", (Object) params));
518     }
519     return object;
520   }
521
522   protected static List<Object> toObjectList(List<Event> events)
523   {
524     List<Object> eventObjectList = new ArrayList<>();
525     for (Event event : events)
526     {
527       eventObjectList.add((Object) event.toObject());
528     }
529     return eventObjectList;
530   }
531 }