1 package jalview.analytics;
3 import java.io.BufferedReader;
4 import java.io.IOException;
5 import java.io.InputStreamReader;
6 import java.io.OutputStream;
7 import java.io.UnsupportedEncodingException;
8 import java.lang.invoke.MethodHandles;
9 import java.net.HttpURLConnection;
10 import java.net.MalformedURLException;
12 import java.net.URLConnection;
13 import java.net.URLEncoder;
14 import java.nio.charset.StandardCharsets;
15 import java.util.AbstractMap;
16 import java.util.ArrayList;
17 import java.util.Collections;
18 import java.util.HashMap;
19 import java.util.Iterator;
20 import java.util.List;
23 import jalview.bin.Cache;
24 import jalview.bin.Console;
25 import jalview.bin.Jalview;
26 import jalview.util.ChannelProperties;
28 public class Plausible
30 private static final String USER_AGENT = ChannelProperties
31 .getProperty("app_name", "Jalview") + " "
32 + Cache.getDefault("VERSION", "Unknown") + " "
33 + MethodHandles.lookup().lookupClass() + " help@jalview.org";
35 private static final String JALVIEW_ID = "Jalview Desktop";
37 private static final String DOMAIN = "jalview.org";
39 private static final String API_BASE_URL = "https://plausible.io/api/event";
41 public static final String APPLICATION_BASE_URL = "desktop://localhost";
43 private List<Map.Entry<String, String>> queryStringValues;
45 private List<Map.Entry<String, Object>> jsonObject;
47 private List<Event> events;
49 private List<Map.Entry<String, String>> cookieValues;
51 private static boolean ENABLED = false;
53 private static boolean DEBUG = true;
55 private static Plausible instance = null;
57 private static final Map<String, String> defaultParams;
61 defaultParams = new HashMap<>();
62 defaultParams.put("app_name",
63 ChannelProperties.getProperty("app_name") + " Desktop");
64 defaultParams.put("version", Cache.getProperty("VERSION"));
65 defaultParams.put("build_date",
66 Cache.getDefault("BUILD_DATE", "unknown"));
67 defaultParams.put("java_version", System.getProperty("java.version"));
68 String val = System.getProperty("sys.install4jVersion");
71 defaultParams.put("install4j_version", val);
73 val = System.getProperty("installer_template_version");
76 defaultParams.put("install4j_template_version", val);
78 val = System.getProperty("launcher_version");
81 defaultParams.put("launcher_version", val);
83 defaultParams.put("java_arch",
84 System.getProperty("os.arch") + " "
85 + System.getProperty("os.name") + " "
86 + System.getProperty("os.version"));
94 public static void setEnabled(boolean b)
99 public void sendEvent(String eventName, String path,
100 String... paramsStrings)
102 sendEvent(eventName, path, false, paramsStrings);
106 * The simplest way to send an analytic event.
109 * The event name. To emulate a webpage view use "page_view" and set
110 * a "page_location" parameter. See
111 * https://developers.google.com/analytics/devguides/collection/ga4/events?client_type=gtag
112 * @param sendDefaultParams
113 * Flag whether to add the default params about the application.
114 * @param paramsStrings
115 * Optional multiple Strings in key, value pairs (there should be an
116 * even number of paramsStrings) to be set as parameters of the
117 * event. To emulate a webpage view use "page_location" as the URL in
118 * a "page_view" event.
120 public void sendEvent(String eventName, String path,
121 boolean sendDefaultParams, String... paramsStrings)
123 // clear out old lists
128 Console.debug("Plausible not enabled.");
131 Map<String, String> params = new HashMap<>();
133 // add these to all events from this application instance
134 if (sendDefaultParams)
136 params.putAll(defaultParams);
137 if (Jalview.isHeadlessMode())
139 params.put("headless", "true");
143 // add (and overwrite with) the passed in params
144 if (paramsStrings != null && paramsStrings.length > 0)
146 if (paramsStrings.length % 2 != 0)
149 "Cannot addEvent with odd number of paramsStrings. Ignoring the last one.");
151 for (int i = 0; i < paramsStrings.length - 1; i += 2)
153 String key = paramsStrings[i];
154 String value = paramsStrings[i + 1];
155 params.put(key, value);
159 addJsonValue("domain", DOMAIN);
160 addJsonValue("name", eventName);
161 StringBuilder recordedUrlSb = new StringBuilder(APPLICATION_BASE_URL);
162 if (!APPLICATION_BASE_URL.endsWith("/") && !path.startsWith("/"))
164 recordedUrlSb.append("/");
166 recordedUrlSb.append(path);
167 addJsonValue("url", recordedUrlSb.toString());
168 addEvent(eventName, params);
169 addJsonObject("props", params);
170 StringBuilder urlSb = new StringBuilder();
171 urlSb.append(API_BASE_URL);
172 String qs = buildQueryString();
173 if (qs != null && qs.length() > 0)
180 URL url = new URL(urlSb.toString());
181 URLConnection urlConnection = url.openConnection();
182 HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
183 httpURLConnection.setRequestMethod("POST");
184 httpURLConnection.setDoOutput(true);
186 String jsonString = buildJson();
189 "Plausible: HTTP Request is: '" + urlSb.toString() + "'");
190 Console.debug("Plausible: POSTed JSON is:\n" + jsonString);
192 byte[] jsonBytes = jsonString.getBytes(StandardCharsets.UTF_8);
193 int jsonLength = jsonBytes.length;
195 httpURLConnection.setFixedLengthStreamingMode(jsonLength);
196 httpURLConnection.setRequestProperty("Content-Type",
198 httpURLConnection.setRequestProperty("User-Agent", USER_AGENT);
199 httpURLConnection.connect();
200 try (OutputStream os = httpURLConnection.getOutputStream())
204 int responseCode = httpURLConnection.getResponseCode();
205 String responseMessage = httpURLConnection.getResponseMessage();
207 if (responseCode < 200 || responseCode > 299)
209 Console.warn("Plausible connection failed: '" + responseCode + " "
210 + responseMessage + "'");
214 Console.debug("Plausible connection succeeded: '" + responseCode
215 + " " + responseMessage + "'");
220 BufferedReader br = new BufferedReader(new InputStreamReader(
221 (httpURLConnection.getInputStream())));
222 StringBuilder sb = new StringBuilder();
224 while ((response = br.readLine()) != null)
228 String body = sb.toString();
229 Console.debug("Plausible response content; " + body);
231 } catch (MalformedURLException e)
234 "Somehow the Plausible BASE_URL and queryString is malformed: '"
235 + urlSb.toString() + "'",
238 } catch (IOException e)
240 Console.debug("Connection to Plausible BASE_URL '" + API_BASE_URL
242 } catch (ClassCastException e)
245 "Couldn't cast URLConnection to HttpURLConnection in Plausible.",
250 public void addEvent(String name, Map<String, String> params)
252 Event event = new Event(name);
253 if (params != null && params.size() > 0)
255 for (String key : params.keySet())
257 String value = params.get(key);
258 event.addParam(key, value);
264 private void addJsonObject(String key, Map<String, String> map)
266 List<Map.Entry<String, ? extends Object>> list = new ArrayList<>();
267 for (String k : map.keySet())
269 list.add(stringEntry(k, map.get(k)));
271 addJsonObject(key, list);
275 private void addJsonObject(String key,
276 List<Map.Entry<String, ? extends Object>> object)
278 jsonObject.add(objectEntry(key, object));
281 private void addJsonValues(String key, List<Object> values)
283 jsonObject.add(objectEntry(key, values));
286 private void addJsonValue(String key, String value)
288 jsonObject.add(objectEntry(key, value));
291 private void addJsonValue(String key, int value)
293 jsonObject.add(objectEntry(key, Integer.valueOf(value)));
296 private void addJsonValue(String key, boolean value)
298 jsonObject.add(objectEntry(key, Boolean.valueOf(value)));
301 private void addQueryStringValue(String key, String value)
303 queryStringValues.add(stringEntry(key, value));
306 private void addCookieValue(String key, String value)
308 cookieValues.add(stringEntry(key, value));
311 private void resetLists()
313 jsonObject = new ArrayList<>();
314 events = new ArrayList<Event>();
315 queryStringValues = new ArrayList<>();
316 cookieValues = new ArrayList<>();
319 public static Plausible getInstance()
321 if (instance == null)
323 instance = new Plausible();
328 public static void reset()
330 getInstance().resetLists();
333 private String buildQueryString()
335 StringBuilder sb = new StringBuilder();
336 for (Map.Entry<String, String> entry : queryStringValues)
344 sb.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
345 } catch (UnsupportedEncodingException e)
347 sb.append(entry.getKey());
352 sb.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
353 } catch (UnsupportedEncodingException e)
355 sb.append(entry.getValue());
358 return sb.toString();
361 private void buildCookieHeaders()
363 // TODO not needed yet
366 private String buildJson()
368 StringBuilder sb = new StringBuilder();
369 addJsonObject(sb, 0, jsonObject);
370 return sb.toString();
373 private void addJsonObject(StringBuilder sb, int indent,
374 List<Map.Entry<String, Object>> entries)
379 Iterator<Map.Entry<String, Object>> entriesI = entries.iterator();
380 while (entriesI.hasNext())
382 Map.Entry<String, Object> entry = entriesI.next();
383 String key = entry.getKey();
384 // TODO sensibly escape " characters in key
385 Object value = entry.getValue();
386 indent(sb, indent + 1);
387 sb.append('"').append(quoteEscape(key)).append('"').append(':');
389 if (value != null && value instanceof List)
393 addJsonValue(sb, indent + 2, value);
394 if (entriesI.hasNext())
404 private void addJsonValue(StringBuilder sb, int indent, Object value)
412 if (value instanceof Map.Entry)
414 Map.Entry<String, Object> entry = (Map.Entry<String, Object>) value;
415 List<Map.Entry<String, Object>> object = new ArrayList<>();
417 addJsonObject(sb, indent, object);
419 else if (value instanceof List)
421 // list of Map.Entries or list of values?
422 List<Object> valueList = (List<Object>) value;
423 if (valueList.size() > 0 && valueList.get(0) instanceof Map.Entry)
426 // indent(sb, indent);
427 List<Map.Entry<String, Object>> entryList = (List<Map.Entry<String, Object>>) value;
428 addJsonObject(sb, indent, entryList);
436 Iterator<Object> valueListI = valueList.iterator();
437 while (valueListI.hasNext())
439 Object v = valueListI.next();
440 addJsonValue(sb, indent + 1, v);
441 if (valueListI.hasNext())
451 else if (value instanceof String)
453 sb.append('"').append(quoteEscape((String) value)).append('"');
455 else if (value instanceof Integer)
457 sb.append(((Integer) value).toString());
459 else if (value instanceof Boolean)
461 sb.append('"').append(((Boolean) value).toString()).append('"');
463 } catch (ClassCastException e)
466 "Could not deal with type of json Object " + value.toString(),
471 private static String quoteEscape(String s)
477 // this escapes quotation marks (") that aren't already escaped (in the
478 // string) ready to go into a quoted JSON string value
479 return s.replaceAll("((?<!\\\\)(?:\\\\{2})*)\"", "$1\\\\\"");
482 private static void prettyWhitespace(StringBuilder sb, String whitespace,
485 // only add whitespace if we're in DEBUG mode
486 if (!Console.getLogger().isDebugEnabled())
490 if (repeat >= 0 && whitespace != null)
492 // sb.append(whitespace.repeat(repeat));
493 sb.append(String.join("", Collections.nCopies(repeat, whitespace)));
498 sb.append(whitespace);
502 private static void indent(StringBuilder sb, int indent)
504 prettyWhitespace(sb, " ", indent);
507 private static void newline(StringBuilder sb)
509 prettyWhitespace(sb, "\n", -1);
512 private static void space(StringBuilder sb)
514 prettyWhitespace(sb, " ", -1);
517 protected static Map.Entry<String, Object> objectEntry(String s, Object o)
519 return new AbstractMap.SimpleEntry<String, Object>(s, o);
522 protected static Map.Entry<String, String> stringEntry(String s, String v)
524 return new AbstractMap.SimpleEntry<String, String>(s, v);