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;
27 import jalview.util.HttpUtils;
29 public class Plausible
31 private static final String USER_AGENT = HttpUtils.getUserAgent(
32 MethodHandles.lookup().lookupClass().getCanonicalName());
34 private static final String JALVIEW_ID = "Jalview Desktop";
36 private static final String DOMAIN = "jalview.org";
38 private static final String CONFIG_API_BASE_URL = "https://www.jalview.org/config/analytics/url";
40 private static final String DEFAULT_API_BASE_URL = "https://plausible.io/api/event";
42 private static final String API_BASE_URL;
44 public static final String APPLICATION_BASE_URL = "desktop://localhost";
46 private List<Map.Entry<String, String>> queryStringValues;
48 private List<Map.Entry<String, Object>> jsonObject;
50 private List<Map.Entry<String, String>> cookieValues;
52 private static boolean ENABLED = false;
54 private static boolean DEBUG = true;
56 private static Plausible instance = null;
58 private static final Map<String, String> defaultProps;
62 defaultProps = new HashMap<>();
63 defaultProps.put("app_name",
64 ChannelProperties.getProperty("app_name") + " Desktop");
65 defaultProps.put("version", Cache.getProperty("VERSION"));
66 defaultProps.put("build_date",
67 Cache.getDefault("BUILD_DATE", "unknown"));
68 defaultProps.put("java_version", System.getProperty("java.version"));
69 String val = System.getProperty("sys.install4jVersion");
72 defaultProps.put("install4j_version", val);
74 val = System.getProperty("installer_template_version");
77 defaultProps.put("install4j_template_version", val);
79 val = System.getProperty("launcher_version");
82 defaultProps.put("launcher_version", val);
84 defaultProps.put("java_arch",
85 System.getProperty("os.arch") + " "
86 + System.getProperty("os.name") + " "
87 + System.getProperty("os.version"));
88 String installation = Cache.applicationProperties
89 .getProperty("INSTALLATION");
90 if (installation != null)
92 defaultProps.put("installation", installation);
95 // ascertain the API_BASE_URL
96 API_BASE_URL = getAPIBaseURL();
104 public static void setEnabled(boolean b)
109 public void sendEvent(String eventName, String urlString,
110 String... propsStrings)
112 sendEvent(eventName, urlString, false, propsStrings);
116 * The simplest way to send an analytic event.
119 * The event name. To emulate a webpage view use "pageview" and set a
120 * "url" key/value. See https://plausible.io/docs/events-api
121 * @param sendDefaultProps
122 * Flag whether to add the default props about the application.
123 * @param propsStrings
124 * Optional multiple Strings in key, value pairs (there should be an
125 * even number of propsStrings) to be set as property of the event.
126 * To emulate a webpage view set "url" as the URL in a "pageview"
129 public void sendEvent(String eventName, String urlString,
130 boolean sendDefaultProps, String... propsStrings)
132 // clear out old lists
137 Console.debug("Plausible not enabled.");
140 Map<String, String> props = new HashMap<>();
142 // add these to all events from this application instance
143 if (sendDefaultProps)
145 props.putAll(defaultProps);
146 if (Jalview.isHeadlessMode())
148 props.put("headless", "true");
152 // add (and overwrite with) the passed in props
153 if (propsStrings != null && propsStrings.length > 0)
155 if (propsStrings.length % 2 != 0)
158 "Cannot addEvent with odd number of propsStrings. Ignoring the last one.");
160 for (int i = 0; i < propsStrings.length - 1; i += 2)
162 String key = propsStrings[i];
163 String value = propsStrings[i + 1];
164 props.put(key, value);
168 addJsonValue("domain", DOMAIN);
169 addJsonValue("name", eventName);
170 StringBuilder eventUrlSb = new StringBuilder(APPLICATION_BASE_URL);
171 if (!APPLICATION_BASE_URL.endsWith("/") && !urlString.startsWith("/"))
173 eventUrlSb.append("/");
175 eventUrlSb.append(urlString);
176 addJsonValue("url", eventUrlSb.toString());
177 addJsonObject("props", props);
178 StringBuilder urlSb = new StringBuilder();
179 urlSb.append(API_BASE_URL);
180 String qs = buildQueryString();
181 if (qs != null && qs.length() > 0)
188 URL url = new URL(urlSb.toString());
189 URLConnection urlConnection = url.openConnection();
190 HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
191 httpURLConnection.setRequestMethod("POST");
192 httpURLConnection.setDoOutput(true);
194 String jsonString = buildJson();
197 "Plausible: HTTP Request is: '" + urlSb.toString() + "'");
200 Console.debug("Plausible: User-Agent is: '" + USER_AGENT + "'");
202 Console.debug("Plausible: POSTed JSON is:\n" + jsonString);
204 byte[] jsonBytes = jsonString.getBytes(StandardCharsets.UTF_8);
205 int jsonLength = jsonBytes.length;
207 httpURLConnection.setFixedLengthStreamingMode(jsonLength);
208 httpURLConnection.setRequestProperty("Content-Type",
210 httpURLConnection.setRequestProperty("User-Agent", USER_AGENT);
211 httpURLConnection.connect();
212 try (OutputStream os = httpURLConnection.getOutputStream())
216 int responseCode = httpURLConnection.getResponseCode();
217 String responseMessage = httpURLConnection.getResponseMessage();
219 if (responseCode < 200 || responseCode > 299)
221 Console.warn("Plausible connection failed: '" + responseCode + " "
222 + responseMessage + "'");
226 Console.debug("Plausible connection succeeded: '" + responseCode
227 + " " + responseMessage + "'");
232 BufferedReader br = new BufferedReader(new InputStreamReader(
233 (httpURLConnection.getInputStream())));
234 StringBuilder sb = new StringBuilder();
236 while ((response = br.readLine()) != null)
240 String body = sb.toString();
241 Console.debug("Plausible response content:\n" + body);
243 } catch (MalformedURLException e)
246 "Somehow the Plausible BASE_URL and queryString is malformed: '"
247 + urlSb.toString() + "'",
250 } catch (IOException e)
252 Console.debug("Connection to Plausible BASE_URL '" + API_BASE_URL
254 } catch (ClassCastException e)
257 "Couldn't cast URLConnection to HttpURLConnection in Plausible.",
262 private void addJsonObject(String key, Map<String, String> map)
264 List<Map.Entry<String, ? extends Object>> list = new ArrayList<>();
265 for (String k : map.keySet())
267 list.add(stringEntry(k, map.get(k)));
269 addJsonObject(key, list);
273 private void addJsonObject(String key,
274 List<Map.Entry<String, ? extends Object>> object)
276 jsonObject.add(objectEntry(key, object));
279 private void addJsonValues(String key, List<Object> values)
281 jsonObject.add(objectEntry(key, values));
284 private void addJsonValue(String key, String value)
286 jsonObject.add(objectEntry(key, value));
289 private void addJsonValue(String key, int value)
291 jsonObject.add(objectEntry(key, Integer.valueOf(value)));
294 private void addJsonValue(String key, boolean value)
296 jsonObject.add(objectEntry(key, Boolean.valueOf(value)));
299 private void addQueryStringValue(String key, String value)
301 queryStringValues.add(stringEntry(key, value));
304 private void addCookieValue(String key, String value)
306 cookieValues.add(stringEntry(key, value));
309 private void resetLists()
311 jsonObject = new ArrayList<>();
312 queryStringValues = new ArrayList<>();
313 cookieValues = new ArrayList<>();
316 public static Plausible getInstance()
318 if (instance == null)
320 instance = new Plausible();
325 public static void reset()
327 getInstance().resetLists();
330 private String buildQueryString()
332 StringBuilder sb = new StringBuilder();
333 for (Map.Entry<String, String> entry : queryStringValues)
341 sb.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
342 } catch (UnsupportedEncodingException e)
344 sb.append(entry.getKey());
349 sb.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
350 } catch (UnsupportedEncodingException e)
352 sb.append(entry.getValue());
355 return sb.toString();
358 private void buildCookieHeaders()
360 // TODO not needed yet
363 private String buildJson()
365 StringBuilder sb = new StringBuilder();
366 addJsonObject(sb, 0, jsonObject);
367 return sb.toString();
370 private void addJsonObject(StringBuilder sb, int indent,
371 List<Map.Entry<String, Object>> entries)
376 Iterator<Map.Entry<String, Object>> entriesI = entries.iterator();
377 while (entriesI.hasNext())
379 Map.Entry<String, Object> entry = entriesI.next();
380 String key = entry.getKey();
381 // TODO sensibly escape " characters in key
382 Object value = entry.getValue();
383 indent(sb, indent + 1);
384 sb.append('"').append(quoteEscape(key)).append('"').append(':');
386 if (value != null && value instanceof List)
390 addJsonValue(sb, indent + 2, value);
391 if (entriesI.hasNext())
401 private void addJsonValue(StringBuilder sb, int indent, Object value)
409 if (value instanceof Map.Entry)
411 Map.Entry<String, Object> entry = (Map.Entry<String, Object>) value;
412 List<Map.Entry<String, Object>> object = new ArrayList<>();
414 addJsonObject(sb, indent, object);
416 else if (value instanceof List)
418 // list of Map.Entries or list of values?
419 List<Object> valueList = (List<Object>) value;
420 if (valueList.size() > 0 && valueList.get(0) instanceof Map.Entry)
423 // indent(sb, indent);
424 List<Map.Entry<String, Object>> entryList = (List<Map.Entry<String, Object>>) value;
425 addJsonObject(sb, indent, entryList);
433 Iterator<Object> valueListI = valueList.iterator();
434 while (valueListI.hasNext())
436 Object v = valueListI.next();
437 addJsonValue(sb, indent + 1, v);
438 if (valueListI.hasNext())
448 else if (value instanceof String)
450 sb.append('"').append(quoteEscape((String) value)).append('"');
452 else if (value instanceof Integer)
454 sb.append(((Integer) value).toString());
456 else if (value instanceof Boolean)
458 sb.append('"').append(((Boolean) value).toString()).append('"');
460 } catch (ClassCastException e)
463 "Could not deal with type of json Object " + value.toString(),
468 private static String quoteEscape(String s)
474 // this escapes quotation marks (") that aren't already escaped (in the
475 // string) ready to go into a quoted JSON string value
476 return s.replaceAll("((?<!\\\\)(?:\\\\{2})*)\"", "$1\\\\\"");
479 private static void prettyWhitespace(StringBuilder sb, String whitespace,
482 // only add whitespace if we're in DEBUG mode
487 if (repeat >= 0 && whitespace != null)
489 // sb.append(whitespace.repeat(repeat));
490 sb.append(String.join("", Collections.nCopies(repeat, whitespace)));
495 sb.append(whitespace);
499 private static void indent(StringBuilder sb, int indent)
501 prettyWhitespace(sb, " ", indent);
504 private static void newline(StringBuilder sb)
506 prettyWhitespace(sb, "\n", -1);
509 private static void space(StringBuilder sb)
511 prettyWhitespace(sb, " ", -1);
514 protected static Map.Entry<String, Object> objectEntry(String s, Object o)
516 return new AbstractMap.SimpleEntry<String, Object>(s, o);
519 protected static Map.Entry<String, String> stringEntry(String s, String v)
521 return new AbstractMap.SimpleEntry<String, String>(s, v);
524 private static String getAPIBaseURL()
528 URL url = new URL(CONFIG_API_BASE_URL);
529 URLConnection urlConnection = url.openConnection();
530 HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
531 httpURLConnection.setRequestMethod("GET");
532 httpURLConnection.setRequestProperty("User-Agent", USER_AGENT);
533 httpURLConnection.setConnectTimeout(5000);
534 httpURLConnection.setReadTimeout(3000);
535 httpURLConnection.connect();
536 int responseCode = httpURLConnection.getResponseCode();
537 String responseMessage = httpURLConnection.getResponseMessage();
539 if (responseCode < 200 || responseCode > 299)
541 Console.warn("Config URL connection to '" + CONFIG_API_BASE_URL
542 + "' failed: '" + responseCode + " " + responseMessage
546 BufferedReader br = new BufferedReader(
547 new InputStreamReader((httpURLConnection.getInputStream())));
548 StringBuilder sb = new StringBuilder();
550 while ((response = br.readLine()) != null)
554 if (sb.length() > 7 && sb.substring(0, 5).equals("https"))
556 return sb.toString();
559 } catch (MalformedURLException e)
561 Console.debug("Somehow the config URL is malformed: '"
562 + CONFIG_API_BASE_URL + "'", e);
563 } catch (IOException e)
565 Console.debug("Connection to Plausible BASE_URL '" + API_BASE_URL
567 } catch (ClassCastException e)
570 "Couldn't cast URLConnection to HttpURLConnection in Plausible.",
573 return DEFAULT_API_BASE_URL;