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);
89 // can be overwritten by passed in params
90 if (paramsStrings != null && paramsStrings.length > 0)
92 if (paramsStrings.length % 2 != 0)
95 "Cannot addEvent with odd number of paramsStrings. Ignoring the last one.");
97 for (int i = 0; i < paramsStrings.length - 1; i += 2)
99 String key = paramsStrings[i];
100 String value = paramsStrings[i + 1];
101 params.put(key, value);
105 addEvent(eventName, params);
106 addQueryStringValue("measurement_id", MEASUREMENT_ID);
107 addQueryStringValue("api_secret", API_SECRET);
108 addJsonValue("client_id", CLIENT_ID);
109 addJsonValues("events", Event.toObjectList(events));
110 StringBuilder urlSb = new StringBuilder();
111 urlSb.append(BASE_URL);
113 urlSb.append(buildQueryString());
116 URL url = new URL(urlSb.toString());
117 URLConnection urlConnection = url.openConnection();
118 HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
119 httpURLConnection.setRequestMethod("POST");
120 httpURLConnection.setDoOutput(true);
122 String jsonString = buildJson();
124 Console.debug("GA4: HTTP Request is: '" + urlSb.toString() + "'");
125 Console.debug("GA4: POSTed JSON is:\n" + jsonString);
127 byte[] jsonBytes = jsonString.getBytes(StandardCharsets.UTF_8);
128 int jsonLength = jsonBytes.length;
130 httpURLConnection.setFixedLengthStreamingMode(jsonLength);
131 httpURLConnection.setRequestProperty("Content-Type",
132 "application/json; charset=UTF-8");
133 httpURLConnection.connect();
134 try (OutputStream os = httpURLConnection.getOutputStream())
138 int responseCode = httpURLConnection.getResponseCode();
139 String responseMessage = httpURLConnection.getResponseMessage();
140 if (responseCode < 200 || responseCode > 299)
142 Console.warn("GoogleAnalytics4 connection failed: '" + responseCode
143 + " " + responseMessage + "'");
147 Console.debug("GoogleAnalytics4 connection succeeded: '"
148 + responseCode + " " + responseMessage + "'");
150 } catch (MalformedURLException e)
153 "Somehow the GoogleAnalytics4 BASE_URL and queryString is malformed.",
156 } catch (IOException e)
158 Console.debug("Connection to GoogleAnalytics4 BASE_URL '" + BASE_URL
160 } catch (ClassCastException e)
163 "Couldn't cast URLConnection to HttpURLConnection in GoogleAnalytics4.",
168 public void addEvent(String name, Map<String, String> params)
170 Event event = new Event(name);
171 if (params != null && params.size() > 0)
173 for (String key : params.keySet())
175 String value = params.get(key);
176 event.addParam(key, value);
182 private void addJsonObject(String key,
183 List<Map.Entry<String, Object>> object)
185 jsonObject.add(objectEntry(key, object));
188 private void addJsonValues(String key, List<Object> values)
190 jsonObject.add(objectEntry(key, values));
193 private void addJsonValue(String key, String value)
195 jsonObject.add(objectEntry(key, value));
198 private void addJsonValue(String key, int value)
200 jsonObject.add(objectEntry(key, Integer.valueOf(value)));
203 private void addJsonValue(String key, boolean value)
205 jsonObject.add(objectEntry(key, Boolean.valueOf(value)));
208 private void addQueryStringValue(String key, String value)
210 queryStringValues.add(stringEntry(key, value));
213 private void addCookieValue(String key, String value)
215 cookieValues.add(stringEntry(key, value));
218 private void resetLists()
220 jsonObject = new ArrayList<>();
221 events = new ArrayList<Event>();
222 queryStringValues = new ArrayList<>();
223 cookieValues = new ArrayList<>();
226 public static GoogleAnalytics4 getInstance()
228 if (instance == null)
230 instance = new GoogleAnalytics4();
235 public static void reset()
237 getInstance().resetLists();
240 private String buildQueryString()
242 StringBuilder sb = new StringBuilder();
243 for (Map.Entry<String, String> entry : queryStringValues)
249 sb.append(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8));
252 URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8));
254 return sb.toString();
257 private void buildCookieHeaders()
259 // TODO not needed yet
262 private String buildJson()
264 StringBuilder sb = new StringBuilder();
265 addJsonObject(sb, 0, jsonObject);
266 return sb.toString();
269 private void addJsonObject(StringBuilder sb, int indent,
270 List<Map.Entry<String, Object>> entries)
275 Iterator<Map.Entry<String, Object>> entriesI = entries.iterator();
276 while (entriesI.hasNext())
278 Map.Entry<String, Object> entry = entriesI.next();
279 String key = entry.getKey();
280 // TODO sensibly escape " characters in key
281 Object value = entry.getValue();
282 indent(sb, indent + 1);
283 sb.append('"').append(quoteEscape(key)).append('"').append(':');
285 if (value != null && value instanceof List)
289 addJsonValue(sb, indent + 2, value);
290 if (entriesI.hasNext())
300 private void addJsonValue(StringBuilder sb, int indent, Object value)
308 if (value instanceof Map.Entry)
310 Map.Entry<String, Object> entry = (Map.Entry<String, Object>) value;
311 List<Map.Entry<String, Object>> object = new ArrayList<>();
313 addJsonObject(sb, indent, object);
315 else if (value instanceof List)
317 // list of Map.Entries or list of values?
318 List<Object> valueList = (List<Object>) value;
319 if (valueList.size() > 0 && valueList.get(0) instanceof Map.Entry)
322 // indent(sb, indent);
323 List<Map.Entry<String, Object>> entryList = (List<Map.Entry<String, Object>>) value;
324 addJsonObject(sb, indent, entryList);
332 Iterator<Object> valueListI = valueList.iterator();
333 while (valueListI.hasNext())
335 Object v = valueListI.next();
336 addJsonValue(sb, indent + 1, v);
337 if (valueListI.hasNext())
347 else if (value instanceof String)
349 sb.append('"').append(quoteEscape((String) value)).append('"');
351 else if (value instanceof Integer)
353 sb.append(((Integer) value).toString());
355 else if (value instanceof Boolean)
357 sb.append('"').append(((Boolean) value).toString()).append('"');
359 } catch (ClassCastException e)
362 "Could not deal with type of json Object " + value.toString(),
367 private static String quoteEscape(String s)
373 // this escapes quotation marks (") that aren't already escaped (in the
374 // string) ready to go into a quoted JSON string value
375 return s.replaceAll("((?<!\\\\)(?:\\\\{2})*)\"", "$1\\\\\"");
378 private static void prettyWhitespace(StringBuilder sb, String whitespace,
381 // only add whitespace if we're in DEBUG mode
382 if (!Console.getLogger().isDebugEnabled())
386 if (repeat >= 0 && whitespace != null)
388 sb.append(whitespace.repeat(repeat));
392 sb.append(whitespace);
396 private static void indent(StringBuilder sb, int indent)
398 prettyWhitespace(sb, " ", indent);
401 private static void newline(StringBuilder sb)
403 prettyWhitespace(sb, "\n", -1);
406 private static void space(StringBuilder sb)
408 prettyWhitespace(sb, " ", -1);
411 protected static Map.Entry<String, Object> objectEntry(String s, Object o)
413 return new AbstractMap.SimpleEntry<String, Object>(s, o);
416 protected static Map.Entry<String, String> stringEntry(String s, String v)
418 return new AbstractMap.SimpleEntry<String, String>(s, v);
426 private List<Map.Entry<String, String>> params;
429 public Event(String name, Map.Entry<String, String>... paramEntries)
432 this.params = new ArrayList<Map.Entry<String, String>>();
433 for (Map.Entry<String, String> paramEntry : paramEntries)
435 if (paramEntry == null)
439 params.add(paramEntry);
443 public void addParam(String param, String value)
445 params.add(GoogleAnalytics4.stringEntry(param, value));
448 protected List<Map.Entry<String, Object>> toObject()
450 List<Map.Entry<String, Object>> object = new ArrayList<>();
451 object.add(GoogleAnalytics4.objectEntry("name", (Object) name));
452 if (params.size() > 0)
454 object.add(GoogleAnalytics4.objectEntry("params", (Object) params));
459 protected static List<Object> toObjectList(List<Event> events)
461 List<Object> eventObjectList = new ArrayList<>();
462 for (Event event : events)
464 eventObjectList.add((Object) event.toObject());
466 return eventObjectList;