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