1 package jalview.analytics;
3 import java.io.IOException;
4 import java.io.OutputStream;
5 import java.net.HttpURLConnection;
6 import java.net.MalformedURLException;
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;
17 import java.util.Random;
18 import java.util.UUID;
20 import jalview.bin.Cache;
21 import jalview.bin.Console;
22 import jalview.util.ChannelProperties;
24 public class GoogleAnalytics4
26 private static final String JALVIEW_ID = "Jalview Desktop";
28 private static final String SESSION_ID = new Random().toString();
30 private static final String MEASUREMENT_ID = "G-6TMPHMXEQ0";
32 private static final String API_SECRET = "Qb9NSbqkRDqizG6j2BBJ2g";
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();
38 private static final String BASE_URL = "https://www.google-analytics.com/mp/collect";
40 private List<Map.Entry<String, String>> queryStringValues;
42 private List<Map.Entry<String, Object>> jsonObject;
44 private List<Event> events;
46 private List<Map.Entry<String, String>> cookieValues;
48 private static boolean ENABLED = false;
50 private static GoogleAnalytics4 instance = null;
52 private static final String appName;
54 private static final String version;
58 appName = ChannelProperties.getProperty("app_name") + " Desktop";
59 version = Cache.getProperty("VERSION") + "_"
60 + Cache.getDefault("BUILD_DATE", "unknown");
63 private GoogleAnalytics4()
68 public static void setEnabled(boolean b)
73 public void sendAnalytics(String eventName, String... paramsStrings)
75 // clear out old lists
80 Console.debug("GoogleAnalytics4 not enabled.");
83 Map<String, String> params = new HashMap<>();
85 // add these to all events from this application instance
86 params.put("app_name", appName);
87 params.put("version", version);
88 params.put("TEST", "you've got to pick a pocket or twoooooo");
90 // can be overwritten by passed in params
91 if (paramsStrings != null && paramsStrings.length > 0)
93 if (paramsStrings.length % 2 != 0)
96 "Cannot addEvent with odd number of paramsStrings. Ignoring the last one.");
98 for (int i = 0; i < paramsStrings.length - 1; i += 2)
100 String key = paramsStrings[i];
101 String value = paramsStrings[i + 1];
102 params.put(key, value);
106 addEvent(eventName, params);
107 addQueryStringValue("measurement_id", MEASUREMENT_ID);
108 addQueryStringValue("api_secret", API_SECRET);
109 addJsonValue("client_id", CLIENT_ID);
110 addJsonValues("events", Event.toObjectList(events));
111 StringBuilder urlSb = new StringBuilder();
112 urlSb.append(BASE_URL);
114 urlSb.append(buildQueryString());
117 URL url = new URL(urlSb.toString());
118 URLConnection urlConnection = url.openConnection();
119 HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
120 httpURLConnection.setRequestMethod("POST");
121 httpURLConnection.setDoOutput(true);
123 String jsonString = buildJson();
125 Console.debug("GA4: HTTP Request is: '" + urlSb.toString() + "'");
126 Console.debug("GA4: POSTed JSON is:\n" + jsonString);
128 byte[] jsonBytes = jsonString.getBytes(StandardCharsets.UTF_8);
129 int jsonLength = jsonBytes.length;
131 httpURLConnection.setFixedLengthStreamingMode(jsonLength);
132 httpURLConnection.setRequestProperty("Content-Type",
133 "application/json; charset=UTF-8");
134 httpURLConnection.connect();
135 try (OutputStream os = httpURLConnection.getOutputStream())
139 int responseCode = httpURLConnection.getResponseCode();
140 String responseMessage = httpURLConnection.getResponseMessage();
141 if (responseCode < 200 || responseCode > 299)
143 Console.warn("GoogleAnalytics4 connection failed: '" + responseCode
144 + " " + responseMessage + "'");
148 Console.debug("GoogleAnalytics4 connection succeeded: '"
149 + responseCode + " " + responseMessage + "'");
151 } catch (MalformedURLException e)
154 "Somehow the GoogleAnalytics4 BASE_URL and queryString is malformed.",
157 } catch (IOException e)
159 Console.debug("Connection to GoogleAnalytics4 BASE_URL '" + BASE_URL
161 } catch (ClassCastException e)
164 "Couldn't cast URLConnection to HttpURLConnection in GoogleAnalytics4.",
169 public void addEvent(String name, Map<String, String> params)
171 Event event = new Event(name);
172 if (params != null && params.size() > 0)
174 for (String key : params.keySet())
176 String value = params.get(key);
177 event.addParam(key, value);
183 private void addJsonObject(String key,
184 List<Map.Entry<String, Object>> object)
186 jsonObject.add(objectEntry(key, object));
189 private void addJsonValues(String key, List<Object> values)
191 jsonObject.add(objectEntry(key, values));
194 private void addJsonValue(String key, String value)
196 jsonObject.add(objectEntry(key, value));
199 private void addJsonValue(String key, int value)
201 jsonObject.add(objectEntry(key, Integer.valueOf(value)));
204 private void addJsonValue(String key, boolean value)
206 jsonObject.add(objectEntry(key, Boolean.valueOf(value)));
209 private void addQueryStringValue(String key, String value)
211 queryStringValues.add(stringEntry(key, value));
214 private void addCookieValue(String key, String value)
216 cookieValues.add(stringEntry(key, value));
219 private void resetLists()
221 jsonObject = new ArrayList<>();
222 events = new ArrayList<Event>();
223 queryStringValues = new ArrayList<>();
224 cookieValues = new ArrayList<>();
227 public static GoogleAnalytics4 getInstance()
229 if (instance == null)
231 instance = new GoogleAnalytics4();
236 public static void reset()
238 getInstance().resetLists();
241 private String buildQueryString()
243 StringBuilder sb = new StringBuilder();
244 for (Map.Entry<String, String> entry : queryStringValues)
250 sb.append(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8));
253 URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8));
255 return sb.toString();
258 private void buildCookieHeaders()
260 // TODO not needed yet
263 private String buildJson()
265 StringBuilder sb = new StringBuilder();
266 addJsonObject(sb, 0, jsonObject);
267 return sb.toString();
270 private void addJsonObject(StringBuilder sb, int indent,
271 List<Map.Entry<String, Object>> entries)
276 Iterator<Map.Entry<String, Object>> entriesI = entries.iterator();
277 while (entriesI.hasNext())
279 Map.Entry<String, Object> entry = entriesI.next();
280 String key = entry.getKey();
281 // TODO sensibly escape " characters in key
282 Object value = entry.getValue();
283 indent(sb, indent + 1);
284 sb.append('"').append(quoteEscape(key)).append('"').append(':');
286 if (value != null && value instanceof List)
290 addJsonValue(sb, indent + 2, value);
291 if (entriesI.hasNext())
301 private void addJsonValue(StringBuilder sb, int indent, Object value)
309 if (value instanceof Map.Entry)
311 Map.Entry<String, Object> entry = (Map.Entry<String, Object>) value;
312 List<Map.Entry<String, Object>> object = new ArrayList<>();
314 addJsonObject(sb, indent, object);
316 else if (value instanceof List)
318 // list of Map.Entries or list of values?
319 List<Object> valueList = (List<Object>) value;
320 if (valueList.size() > 0 && valueList.get(0) instanceof Map.Entry)
323 // indent(sb, indent);
324 List<Map.Entry<String, Object>> entryList = (List<Map.Entry<String, Object>>) value;
325 addJsonObject(sb, indent, entryList);
333 Iterator<Object> valueListI = valueList.iterator();
334 while (valueListI.hasNext())
336 Object v = valueListI.next();
337 addJsonValue(sb, indent + 1, v);
338 if (valueListI.hasNext())
348 else if (value instanceof String)
350 sb.append('"').append(quoteEscape((String) value)).append('"');
352 else if (value instanceof Integer)
354 sb.append(((Integer) value).toString());
356 else if (value instanceof Boolean)
358 sb.append('"').append(((Boolean) value).toString()).append('"');
360 } catch (ClassCastException e)
363 "Could not deal with type of json Object " + value.toString(),
368 private static String quoteEscape(String s)
374 // this escapes quotation marks (") that aren't already escaped (in the
375 // string) ready to go into a quoted JSON string value
376 return s.replaceAll("((?<!\\\\)(?:\\\\{2})*)\"", "$1\\\\\"");
379 private static void prettyWhitespace(StringBuilder sb, String whitespace,
382 // only add whitespace if we're in DEBUG mode
383 if (!Console.getLogger().isDebugEnabled())
387 if (repeat >= 0 && whitespace != null)
389 sb.append(whitespace.repeat(repeat));
393 sb.append(whitespace);
397 private static void indent(StringBuilder sb, int indent)
399 prettyWhitespace(sb, " ", indent);
402 private static void newline(StringBuilder sb)
404 prettyWhitespace(sb, "\n", -1);
407 private static void space(StringBuilder sb)
409 prettyWhitespace(sb, " ", -1);
412 protected static Map.Entry<String, Object> objectEntry(String s, Object o)
414 return new AbstractMap.SimpleEntry<String, Object>(s, o);
417 protected static Map.Entry<String, String> stringEntry(String s, String v)
419 return new AbstractMap.SimpleEntry<String, String>(s, v);
427 private List<Map.Entry<String, String>> params;
430 public Event(String name, Map.Entry<String, String>... paramEntries)
433 this.params = new ArrayList<Map.Entry<String, String>>();
434 for (Map.Entry<String, String> paramEntry : paramEntries)
436 if (paramEntry == null)
440 params.add(paramEntry);
444 public void addParam(String param, String value)
446 params.add(GoogleAnalytics4.stringEntry(param, value));
449 protected List<Map.Entry<String, Object>> toObject()
451 List<Map.Entry<String, Object>> object = new ArrayList<>();
452 object.add(GoogleAnalytics4.objectEntry("name", (Object) name));
453 if (params.size() > 0)
455 object.add(GoogleAnalytics4.objectEntry("params", (Object) params));
460 protected static List<Object> toObjectList(List<Event> events)
462 List<Object> eventObjectList = new ArrayList<>();
463 for (Event event : events)
465 eventObjectList.add((Object) event.toObject());
467 return eventObjectList;