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;
22 import java.util.Random;
24 import jalview.bin.Cache;
25 import jalview.bin.Console;
26 import jalview.util.ChannelProperties;
27 import jalview.util.HttpUtils;
29 public class Plausible
31 private static final String USER_AGENT;
33 private static final String JALVIEW_ID = "Jalview Desktop";
35 private static final String DOMAIN = "jalview.org";
37 private static final String CONFIG_API_BASE_URL = "https://www.jalview.org/services/config/analytics/url";
39 private static final String DEFAULT_API_BASE_URL = "https://analytics.jalview.org/api/event";
41 private static final String API_BASE_URL;
43 private static final String clientId;
45 public static final String APPLICATION_BASE_URL = "desktop://localhost";
47 private List<Map.Entry<String, String>> queryStringValues;
49 private List<Map.Entry<String, Object>> jsonObject;
51 private List<Map.Entry<String, String>> cookieValues;
53 private static boolean ENABLED = false;
55 private static boolean DEBUG = true;
57 private static Plausible instance = null;
59 private static final Map<String, String> defaultProps;
63 defaultProps = new HashMap<>();
64 defaultProps.put("app_name",
65 ChannelProperties.getProperty("app_name") + " Desktop");
66 defaultProps.put("version", Cache.getProperty("VERSION"));
67 defaultProps.put("build_date",
68 Cache.getDefault("BUILD_DATE", "unknown"));
69 defaultProps.put("java_version", System.getProperty("java.version"));
70 String val = System.getProperty("sys.install4jVersion");
73 defaultProps.put("install4j_version", val);
75 val = System.getProperty("installer_template_version");
78 defaultProps.put("install4j_template_version", val);
80 val = System.getProperty("launcher_version");
83 defaultProps.put("launcher_version", val);
85 defaultProps.put("java_arch",
86 System.getProperty("os.arch") + " "
87 + System.getProperty("os.name") + " "
88 + System.getProperty("os.version"));
89 defaultProps.put("os", System.getProperty("os.name"));
90 defaultProps.put("os_version", System.getProperty("os.version"));
91 defaultProps.put("os_arch", System.getProperty("os.arch"));
92 String installation = Cache.applicationProperties
93 .getProperty("INSTALLATION");
94 if (installation != null)
96 defaultProps.put("installation", installation);
99 // ascertain the API_BASE_URL
100 API_BASE_URL = getAPIBaseURL();
102 // random clientId to make User-Agent unique (to register analytic)
103 clientId = String.format("%08x", new Random().nextInt());
105 USER_AGENT = HttpUtils.getUserAgent(
106 MethodHandles.lookup().lookupClass().getCanonicalName() + " "
115 public static void setEnabled(boolean b)
120 public void sendEvent(String eventName, String urlString,
121 String... propsStrings)
123 sendEvent(eventName, urlString, false, propsStrings);
127 * The simplest way to send an analytic event.
130 * The event name. To emulate a webpage view use "pageview" and set a
131 * "url" key/value. See https://plausible.io/docs/events-api
132 * @param sendDefaultProps
133 * Flag whether to add the default props about the application.
134 * @param propsStrings
135 * Optional multiple Strings in key, value pairs (there should be an
136 * even number of propsStrings) to be set as property of the event.
137 * To emulate a webpage view set "url" as the URL in a "pageview"
140 public void sendEvent(String eventName, String urlString,
141 boolean sendDefaultProps, String... propsStrings)
143 // clear out old lists
148 Console.debug("Plausible not enabled.");
151 Map<String, String> props = new HashMap<>();
153 // add these to all events from this application instance
154 if (sendDefaultProps)
156 props.putAll(defaultProps);
159 // add (and overwrite with) the passed in props
160 if (propsStrings != null && propsStrings.length > 0)
162 if (propsStrings.length % 2 != 0)
165 "Cannot addEvent with odd number of propsStrings. Ignoring the last one.");
167 for (int i = 0; i < propsStrings.length - 1; i += 2)
169 String key = propsStrings[i];
170 String value = propsStrings[i + 1];
171 props.put(key, value);
175 addJsonValue("domain", DOMAIN);
176 addJsonValue("name", eventName);
177 StringBuilder eventUrlSb = new StringBuilder(APPLICATION_BASE_URL);
178 if (!APPLICATION_BASE_URL.endsWith("/") && !urlString.startsWith("/"))
180 eventUrlSb.append("/");
182 eventUrlSb.append(urlString);
183 addJsonValue("url", eventUrlSb.toString());
184 addJsonObject("props", props);
185 StringBuilder urlSb = new StringBuilder();
186 urlSb.append(API_BASE_URL);
187 String qs = buildQueryString();
188 if (qs != null && qs.length() > 0)
195 URL url = new URL(urlSb.toString());
196 URLConnection urlConnection = url.openConnection();
197 HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
198 httpURLConnection.setRequestMethod("POST");
199 httpURLConnection.setDoOutput(true);
201 String jsonString = buildJson();
204 "Plausible: HTTP Request is: '" + urlSb.toString() + "'");
207 Console.debug("Plausible: User-Agent is: '" + USER_AGENT + "'");
209 Console.debug("Plausible: POSTed JSON is:\n" + jsonString);
211 byte[] jsonBytes = jsonString.getBytes(StandardCharsets.UTF_8);
212 int jsonLength = jsonBytes.length;
214 httpURLConnection.setFixedLengthStreamingMode(jsonLength);
215 httpURLConnection.setRequestProperty("Content-Type",
217 httpURLConnection.setRequestProperty("User-Agent", USER_AGENT);
218 httpURLConnection.connect();
219 try (OutputStream os = httpURLConnection.getOutputStream())
223 int responseCode = httpURLConnection.getResponseCode();
224 String responseMessage = httpURLConnection.getResponseMessage();
226 if (responseCode < 200 || responseCode > 299)
228 Console.warn("Plausible connection failed: '" + responseCode + " "
229 + responseMessage + "'");
233 Console.debug("Plausible connection succeeded: '" + responseCode
234 + " " + responseMessage + "'");
239 BufferedReader br = new BufferedReader(new InputStreamReader(
240 (httpURLConnection.getInputStream())));
241 StringBuilder sb = new StringBuilder();
243 while ((response = br.readLine()) != null)
247 String body = sb.toString();
248 Console.debug("Plausible response content:\n" + body);
250 } catch (MalformedURLException e)
253 "Somehow the Plausible BASE_URL and queryString is malformed: '"
254 + urlSb.toString() + "'",
257 } catch (IOException e)
259 Console.debug("Connection to Plausible BASE_URL '" + API_BASE_URL
261 } catch (ClassCastException e)
264 "Couldn't cast URLConnection to HttpURLConnection in Plausible.",
269 private void addJsonObject(String key, Map<String, String> map)
271 List<Map.Entry<String, ? extends Object>> list = new ArrayList<>();
272 for (String k : map.keySet())
274 list.add(stringEntry(k, map.get(k)));
276 addJsonObject(key, list);
280 private void addJsonObject(String key,
281 List<Map.Entry<String, ? extends Object>> object)
283 jsonObject.add(objectEntry(key, object));
286 private void addJsonValues(String key, List<Object> values)
288 jsonObject.add(objectEntry(key, values));
291 private void addJsonValue(String key, String value)
293 jsonObject.add(objectEntry(key, value));
296 private void addJsonValue(String key, int value)
298 jsonObject.add(objectEntry(key, Integer.valueOf(value)));
301 private void addJsonValue(String key, boolean value)
303 jsonObject.add(objectEntry(key, Boolean.valueOf(value)));
306 private void addQueryStringValue(String key, String value)
308 queryStringValues.add(stringEntry(key, value));
311 private void addCookieValue(String key, String value)
313 cookieValues.add(stringEntry(key, value));
316 private void resetLists()
318 jsonObject = new ArrayList<>();
319 queryStringValues = new ArrayList<>();
320 cookieValues = new ArrayList<>();
323 public static Plausible getInstance()
325 if (instance == null)
327 instance = new Plausible();
332 public static void reset()
334 getInstance().resetLists();
337 private String buildQueryString()
339 StringBuilder sb = new StringBuilder();
340 for (Map.Entry<String, String> entry : queryStringValues)
348 sb.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
349 } catch (UnsupportedEncodingException e)
351 sb.append(entry.getKey());
356 sb.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
357 } catch (UnsupportedEncodingException e)
359 sb.append(entry.getValue());
362 return sb.toString();
365 private void buildCookieHeaders()
367 // TODO not needed yet
370 private String buildJson()
372 StringBuilder sb = new StringBuilder();
373 addJsonObject(sb, 0, jsonObject);
374 return sb.toString();
377 private void addJsonObject(StringBuilder sb, int indent,
378 List<Map.Entry<String, Object>> entries)
383 Iterator<Map.Entry<String, Object>> entriesI = entries.iterator();
384 while (entriesI.hasNext())
386 Map.Entry<String, Object> entry = entriesI.next();
387 String key = entry.getKey();
388 // TODO sensibly escape " characters in key
389 Object value = entry.getValue();
390 indent(sb, indent + 1);
391 sb.append('"').append(quoteEscape(key)).append('"').append(':');
393 if (value != null && value instanceof List)
397 addJsonValue(sb, indent + 2, value);
398 if (entriesI.hasNext())
408 private void addJsonValue(StringBuilder sb, int indent, Object value)
416 if (value instanceof Map.Entry)
418 Map.Entry<String, Object> entry = (Map.Entry<String, Object>) value;
419 List<Map.Entry<String, Object>> object = new ArrayList<>();
421 addJsonObject(sb, indent, object);
423 else if (value instanceof List)
425 // list of Map.Entries or list of values?
426 List<Object> valueList = (List<Object>) value;
427 if (valueList.size() > 0 && valueList.get(0) instanceof Map.Entry)
430 // indent(sb, indent);
431 List<Map.Entry<String, Object>> entryList = (List<Map.Entry<String, Object>>) value;
432 addJsonObject(sb, indent, entryList);
440 Iterator<Object> valueListI = valueList.iterator();
441 while (valueListI.hasNext())
443 Object v = valueListI.next();
444 addJsonValue(sb, indent + 1, v);
445 if (valueListI.hasNext())
455 else if (value instanceof String)
457 sb.append('"').append(quoteEscape((String) value)).append('"');
459 else if (value instanceof Integer)
461 sb.append(((Integer) value).toString());
463 else if (value instanceof Boolean)
465 sb.append('"').append(((Boolean) value).toString()).append('"');
467 } catch (ClassCastException e)
470 "Could not deal with type of json Object " + value.toString(),
475 private static String quoteEscape(String s)
481 // this escapes quotation marks (") that aren't already escaped (in the
482 // string) ready to go into a quoted JSON string value
483 return s.replaceAll("((?<!\\\\)(?:\\\\{2})*)\"", "$1\\\\\"");
486 private static void prettyWhitespace(StringBuilder sb, String whitespace,
489 // only add whitespace if we're in DEBUG mode
494 if (repeat >= 0 && whitespace != null)
496 // sb.append(whitespace.repeat(repeat));
497 sb.append(String.join("", Collections.nCopies(repeat, whitespace)));
502 sb.append(whitespace);
506 private static void indent(StringBuilder sb, int indent)
508 prettyWhitespace(sb, " ", indent);
511 private static void newline(StringBuilder sb)
513 prettyWhitespace(sb, "\n", -1);
516 private static void space(StringBuilder sb)
518 prettyWhitespace(sb, " ", -1);
521 protected static Map.Entry<String, Object> objectEntry(String s, Object o)
523 return new AbstractMap.SimpleEntry<String, Object>(s, o);
526 protected static Map.Entry<String, String> stringEntry(String s, String v)
528 return new AbstractMap.SimpleEntry<String, String>(s, v);
531 private static String getAPIBaseURL()
535 URL url = new URL(CONFIG_API_BASE_URL);
536 URLConnection urlConnection = url.openConnection();
537 HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
538 httpURLConnection.setRequestMethod("GET");
539 httpURLConnection.setRequestProperty("User-Agent", USER_AGENT);
540 httpURLConnection.setConnectTimeout(5000);
541 httpURLConnection.setReadTimeout(3000);
542 httpURLConnection.connect();
543 int responseCode = httpURLConnection.getResponseCode();
544 String responseMessage = httpURLConnection.getResponseMessage();
546 if (responseCode < 200 || responseCode > 299)
548 Console.warn("Config URL connection to '" + CONFIG_API_BASE_URL
549 + "' failed: '" + responseCode + " " + responseMessage
553 BufferedReader br = new BufferedReader(
554 new InputStreamReader((httpURLConnection.getInputStream())));
555 StringBuilder sb = new StringBuilder();
557 while ((response = br.readLine()) != null)
561 if (sb.length() > 7 && sb.substring(0, 5).equals("https"))
563 return sb.toString();
566 } catch (MalformedURLException e)
568 Console.debug("Somehow the config URL is malformed: '"
569 + CONFIG_API_BASE_URL + "'", e);
570 } catch (IOException e)
572 Console.debug("Connection to Plausible BASE_URL '" + API_BASE_URL
574 } catch (ClassCastException e)
577 "Couldn't cast URLConnection to HttpURLConnection in Plausible.",
580 return DEFAULT_API_BASE_URL;