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 API_BASE_URL = "https://plausible.io/api/event";
40 public static final String APPLICATION_BASE_URL = "desktop://localhost";
42 private List<Map.Entry<String, String>> queryStringValues;
44 private List<Map.Entry<String, Object>> jsonObject;
46 private List<Map.Entry<String, String>> cookieValues;
48 private static boolean ENABLED = false;
50 private static boolean DEBUG = true;
52 private static Plausible instance = null;
54 private static final Map<String, String> defaultProps;
58 defaultProps = new HashMap<>();
59 defaultProps.put("app_name",
60 ChannelProperties.getProperty("app_name") + " Desktop");
61 defaultProps.put("version", Cache.getProperty("VERSION"));
62 defaultProps.put("build_date",
63 Cache.getDefault("BUILD_DATE", "unknown"));
64 defaultProps.put("java_version", System.getProperty("java.version"));
65 String val = System.getProperty("sys.install4jVersion");
68 defaultProps.put("install4j_version", val);
70 val = System.getProperty("installer_template_version");
73 defaultProps.put("install4j_template_version", val);
75 val = System.getProperty("launcher_version");
78 defaultProps.put("launcher_version", val);
80 defaultProps.put("java_arch",
81 System.getProperty("os.arch") + " "
82 + System.getProperty("os.name") + " "
83 + System.getProperty("os.version"));
91 public static void setEnabled(boolean b)
96 public void sendEvent(String eventName, String path,
97 String... propsStrings)
99 sendEvent(eventName, path, false, propsStrings);
103 * The simplest way to send an analytic event.
106 * The event name. To emulate a webpage view use "pageview" and set a
107 * "url" key/value. See https://plausible.io/docs/events-api
108 * @param sendDefaultProps
109 * Flag whether to add the default props about the application.
110 * @param propsStrings
111 * Optional multiple Strings in key, value pairs (there should be an
112 * even number of propsStrings) to be set as properties of the event.
113 * To emulate a webpage view use "url" as the URL in a "pageview"
116 public void sendEvent(String eventName, String path,
117 boolean sendDefaultProps, String... propsStrings)
119 // clear out old lists
124 Console.debug("Plausible not enabled.");
127 Map<String, String> props = new HashMap<>();
129 // add these to all events from this application instance
130 if (sendDefaultProps)
132 props.putAll(defaultProps);
133 if (Jalview.isHeadlessMode())
135 props.put("headless", "true");
139 // add (and overwrite with) the passed in props
140 if (propsStrings != null && propsStrings.length > 0)
142 if (propsStrings.length % 2 != 0)
145 "Cannot addEvent with odd number of propsStrings. Ignoring the last one.");
147 for (int i = 0; i < propsStrings.length - 1; i += 2)
149 String key = propsStrings[i];
150 String value = propsStrings[i + 1];
151 props.put(key, value);
155 addJsonValue("domain", DOMAIN);
156 addJsonValue("name", eventName);
157 StringBuilder recordedUrlSb = new StringBuilder(APPLICATION_BASE_URL);
158 if (!APPLICATION_BASE_URL.endsWith("/") && !path.startsWith("/"))
160 recordedUrlSb.append("/");
162 recordedUrlSb.append(path);
163 addJsonValue("url", recordedUrlSb.toString());
164 addJsonObject("props", props);
165 StringBuilder urlSb = new StringBuilder();
166 urlSb.append(API_BASE_URL);
167 String qs = buildQueryString();
168 if (qs != null && qs.length() > 0)
175 URL url = new URL(urlSb.toString());
176 URLConnection urlConnection = url.openConnection();
177 HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
178 httpURLConnection.setRequestMethod("POST");
179 httpURLConnection.setDoOutput(true);
181 String jsonString = buildJson();
184 "Plausible: HTTP Request is: '" + urlSb.toString() + "'");
187 Console.debug("Plausible: User-Agent is: '" + USER_AGENT + "'");
189 Console.debug("Plausible: POSTed JSON is:\n" + jsonString);
191 byte[] jsonBytes = jsonString.getBytes(StandardCharsets.UTF_8);
192 int jsonLength = jsonBytes.length;
194 httpURLConnection.setFixedLengthStreamingMode(jsonLength);
195 httpURLConnection.setRequestProperty("Content-Type",
197 httpURLConnection.setRequestProperty("User-Agent", USER_AGENT);
198 httpURLConnection.connect();
199 try (OutputStream os = httpURLConnection.getOutputStream())
203 int responseCode = httpURLConnection.getResponseCode();
204 String responseMessage = httpURLConnection.getResponseMessage();
206 if (responseCode < 200 || responseCode > 299)
208 Console.warn("Plausible connection failed: '" + responseCode + " "
209 + responseMessage + "'");
213 Console.debug("Plausible connection succeeded: '" + responseCode
214 + " " + responseMessage + "'");
219 BufferedReader br = new BufferedReader(new InputStreamReader(
220 (httpURLConnection.getInputStream())));
221 StringBuilder sb = new StringBuilder();
223 while ((response = br.readLine()) != null)
227 String body = sb.toString();
228 Console.debug("Plausible response content:\n" + body);
230 } catch (MalformedURLException e)
233 "Somehow the Plausible BASE_URL and queryString is malformed: '"
234 + urlSb.toString() + "'",
237 } catch (IOException e)
239 Console.debug("Connection to Plausible BASE_URL '" + API_BASE_URL
241 } catch (ClassCastException e)
244 "Couldn't cast URLConnection to HttpURLConnection in Plausible.",
249 private void addJsonObject(String key, Map<String, String> map)
251 List<Map.Entry<String, ? extends Object>> list = new ArrayList<>();
252 for (String k : map.keySet())
254 list.add(stringEntry(k, map.get(k)));
256 addJsonObject(key, list);
260 private void addJsonObject(String key,
261 List<Map.Entry<String, ? extends Object>> object)
263 jsonObject.add(objectEntry(key, object));
266 private void addJsonValues(String key, List<Object> values)
268 jsonObject.add(objectEntry(key, values));
271 private void addJsonValue(String key, String value)
273 jsonObject.add(objectEntry(key, value));
276 private void addJsonValue(String key, int value)
278 jsonObject.add(objectEntry(key, Integer.valueOf(value)));
281 private void addJsonValue(String key, boolean value)
283 jsonObject.add(objectEntry(key, Boolean.valueOf(value)));
286 private void addQueryStringValue(String key, String value)
288 queryStringValues.add(stringEntry(key, value));
291 private void addCookieValue(String key, String value)
293 cookieValues.add(stringEntry(key, value));
296 private void resetLists()
298 jsonObject = new ArrayList<>();
299 queryStringValues = new ArrayList<>();
300 cookieValues = new ArrayList<>();
303 public static Plausible getInstance()
305 if (instance == null)
307 instance = new Plausible();
312 public static void reset()
314 getInstance().resetLists();
317 private String buildQueryString()
319 StringBuilder sb = new StringBuilder();
320 for (Map.Entry<String, String> entry : queryStringValues)
328 sb.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
329 } catch (UnsupportedEncodingException e)
331 sb.append(entry.getKey());
336 sb.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
337 } catch (UnsupportedEncodingException e)
339 sb.append(entry.getValue());
342 return sb.toString();
345 private void buildCookieHeaders()
347 // TODO not needed yet
350 private String buildJson()
352 StringBuilder sb = new StringBuilder();
353 addJsonObject(sb, 0, jsonObject);
354 return sb.toString();
357 private void addJsonObject(StringBuilder sb, int indent,
358 List<Map.Entry<String, Object>> entries)
363 Iterator<Map.Entry<String, Object>> entriesI = entries.iterator();
364 while (entriesI.hasNext())
366 Map.Entry<String, Object> entry = entriesI.next();
367 String key = entry.getKey();
368 // TODO sensibly escape " characters in key
369 Object value = entry.getValue();
370 indent(sb, indent + 1);
371 sb.append('"').append(quoteEscape(key)).append('"').append(':');
373 if (value != null && value instanceof List)
377 addJsonValue(sb, indent + 2, value);
378 if (entriesI.hasNext())
388 private void addJsonValue(StringBuilder sb, int indent, Object value)
396 if (value instanceof Map.Entry)
398 Map.Entry<String, Object> entry = (Map.Entry<String, Object>) value;
399 List<Map.Entry<String, Object>> object = new ArrayList<>();
401 addJsonObject(sb, indent, object);
403 else if (value instanceof List)
405 // list of Map.Entries or list of values?
406 List<Object> valueList = (List<Object>) value;
407 if (valueList.size() > 0 && valueList.get(0) instanceof Map.Entry)
410 // indent(sb, indent);
411 List<Map.Entry<String, Object>> entryList = (List<Map.Entry<String, Object>>) value;
412 addJsonObject(sb, indent, entryList);
420 Iterator<Object> valueListI = valueList.iterator();
421 while (valueListI.hasNext())
423 Object v = valueListI.next();
424 addJsonValue(sb, indent + 1, v);
425 if (valueListI.hasNext())
435 else if (value instanceof String)
437 sb.append('"').append(quoteEscape((String) value)).append('"');
439 else if (value instanceof Integer)
441 sb.append(((Integer) value).toString());
443 else if (value instanceof Boolean)
445 sb.append('"').append(((Boolean) value).toString()).append('"');
447 } catch (ClassCastException e)
450 "Could not deal with type of json Object " + value.toString(),
455 private static String quoteEscape(String s)
461 // this escapes quotation marks (") that aren't already escaped (in the
462 // string) ready to go into a quoted JSON string value
463 return s.replaceAll("((?<!\\\\)(?:\\\\{2})*)\"", "$1\\\\\"");
466 private static void prettyWhitespace(StringBuilder sb, String whitespace,
469 // only add whitespace if we're in DEBUG mode
474 if (repeat >= 0 && whitespace != null)
476 // sb.append(whitespace.repeat(repeat));
477 sb.append(String.join("", Collections.nCopies(repeat, whitespace)));
482 sb.append(whitespace);
486 private static void indent(StringBuilder sb, int indent)
488 prettyWhitespace(sb, " ", indent);
491 private static void newline(StringBuilder sb)
493 prettyWhitespace(sb, "\n", -1);
496 private static void space(StringBuilder sb)
498 prettyWhitespace(sb, " ", -1);
501 protected static Map.Entry<String, Object> objectEntry(String s, Object o)
503 return new AbstractMap.SimpleEntry<String, Object>(s, o);
506 protected static Map.Entry<String, String> stringEntry(String s, String v)
508 return new AbstractMap.SimpleEntry<String, String>(s, v);