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://DEFAULT.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"));
89 // ascertain the API_BASE_URL
90 API_BASE_URL = getAPIBaseURL();
98 public static void setEnabled(boolean b)
103 public void sendEvent(String eventName, String urlString,
104 String... propsStrings)
106 sendEvent(eventName, urlString, false, propsStrings);
110 * The simplest way to send an analytic event.
113 * The event name. To emulate a webpage view use "pageview" and set a
114 * "url" key/value. See https://plausible.io/docs/events-api
115 * @param sendDefaultProps
116 * Flag whether to add the default props about the application.
117 * @param propsStrings
118 * Optional multiple Strings in key, value pairs (there should be an
119 * even number of propsStrings) to be set as property of the event.
120 * To emulate a webpage view set "url" as the URL in a "pageview"
123 public void sendEvent(String eventName, String urlString,
124 boolean sendDefaultProps, String... propsStrings)
126 // clear out old lists
131 Console.debug("Plausible not enabled.");
134 Map<String, String> props = new HashMap<>();
136 // add these to all events from this application instance
137 if (sendDefaultProps)
139 props.putAll(defaultProps);
140 if (Jalview.isHeadlessMode())
142 props.put("headless", "true");
146 // add (and overwrite with) the passed in props
147 if (propsStrings != null && propsStrings.length > 0)
149 if (propsStrings.length % 2 != 0)
152 "Cannot addEvent with odd number of propsStrings. Ignoring the last one.");
154 for (int i = 0; i < propsStrings.length - 1; i += 2)
156 String key = propsStrings[i];
157 String value = propsStrings[i + 1];
158 props.put(key, value);
162 addJsonValue("domain", DOMAIN);
163 addJsonValue("name", eventName);
164 StringBuilder eventUrlSb = new StringBuilder(APPLICATION_BASE_URL);
165 if (!APPLICATION_BASE_URL.endsWith("/") && !urlString.startsWith("/"))
167 eventUrlSb.append("/");
169 eventUrlSb.append(urlString);
170 addJsonValue("url", eventUrlSb.toString());
171 addJsonObject("props", props);
172 StringBuilder urlSb = new StringBuilder();
173 urlSb.append(API_BASE_URL);
174 String qs = buildQueryString();
175 if (qs != null && qs.length() > 0)
182 URL url = new URL(urlSb.toString());
183 URLConnection urlConnection = url.openConnection();
184 HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
185 httpURLConnection.setRequestMethod("POST");
186 httpURLConnection.setDoOutput(true);
188 String jsonString = buildJson();
191 "Plausible: HTTP Request is: '" + urlSb.toString() + "'");
194 Console.debug("Plausible: User-Agent is: '" + USER_AGENT + "'");
196 Console.debug("Plausible: POSTed JSON is:\n" + jsonString);
198 byte[] jsonBytes = jsonString.getBytes(StandardCharsets.UTF_8);
199 int jsonLength = jsonBytes.length;
201 httpURLConnection.setFixedLengthStreamingMode(jsonLength);
202 httpURLConnection.setRequestProperty("Content-Type",
204 httpURLConnection.setRequestProperty("User-Agent", USER_AGENT);
205 httpURLConnection.connect();
206 try (OutputStream os = httpURLConnection.getOutputStream())
210 int responseCode = httpURLConnection.getResponseCode();
211 String responseMessage = httpURLConnection.getResponseMessage();
213 if (responseCode < 200 || responseCode > 299)
215 Console.warn("Plausible connection failed: '" + responseCode + " "
216 + responseMessage + "'");
220 Console.debug("Plausible connection succeeded: '" + responseCode
221 + " " + responseMessage + "'");
226 BufferedReader br = new BufferedReader(new InputStreamReader(
227 (httpURLConnection.getInputStream())));
228 StringBuilder sb = new StringBuilder();
230 while ((response = br.readLine()) != null)
234 String body = sb.toString();
235 Console.debug("Plausible response content:\n" + body);
237 } catch (MalformedURLException e)
240 "Somehow the Plausible BASE_URL and queryString is malformed: '"
241 + urlSb.toString() + "'",
244 } catch (IOException e)
246 Console.debug("Connection to Plausible BASE_URL '" + API_BASE_URL
248 } catch (ClassCastException e)
251 "Couldn't cast URLConnection to HttpURLConnection in Plausible.",
256 private void addJsonObject(String key, Map<String, String> map)
258 List<Map.Entry<String, ? extends Object>> list = new ArrayList<>();
259 for (String k : map.keySet())
261 list.add(stringEntry(k, map.get(k)));
263 addJsonObject(key, list);
267 private void addJsonObject(String key,
268 List<Map.Entry<String, ? extends Object>> object)
270 jsonObject.add(objectEntry(key, object));
273 private void addJsonValues(String key, List<Object> values)
275 jsonObject.add(objectEntry(key, values));
278 private void addJsonValue(String key, String value)
280 jsonObject.add(objectEntry(key, value));
283 private void addJsonValue(String key, int value)
285 jsonObject.add(objectEntry(key, Integer.valueOf(value)));
288 private void addJsonValue(String key, boolean value)
290 jsonObject.add(objectEntry(key, Boolean.valueOf(value)));
293 private void addQueryStringValue(String key, String value)
295 queryStringValues.add(stringEntry(key, value));
298 private void addCookieValue(String key, String value)
300 cookieValues.add(stringEntry(key, value));
303 private void resetLists()
305 jsonObject = new ArrayList<>();
306 queryStringValues = new ArrayList<>();
307 cookieValues = new ArrayList<>();
310 public static Plausible getInstance()
312 if (instance == null)
314 instance = new Plausible();
319 public static void reset()
321 getInstance().resetLists();
324 private String buildQueryString()
326 StringBuilder sb = new StringBuilder();
327 for (Map.Entry<String, String> entry : queryStringValues)
335 sb.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
336 } catch (UnsupportedEncodingException e)
338 sb.append(entry.getKey());
343 sb.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
344 } catch (UnsupportedEncodingException e)
346 sb.append(entry.getValue());
349 return sb.toString();
352 private void buildCookieHeaders()
354 // TODO not needed yet
357 private String buildJson()
359 StringBuilder sb = new StringBuilder();
360 addJsonObject(sb, 0, jsonObject);
361 return sb.toString();
364 private void addJsonObject(StringBuilder sb, int indent,
365 List<Map.Entry<String, Object>> entries)
370 Iterator<Map.Entry<String, Object>> entriesI = entries.iterator();
371 while (entriesI.hasNext())
373 Map.Entry<String, Object> entry = entriesI.next();
374 String key = entry.getKey();
375 // TODO sensibly escape " characters in key
376 Object value = entry.getValue();
377 indent(sb, indent + 1);
378 sb.append('"').append(quoteEscape(key)).append('"').append(':');
380 if (value != null && value instanceof List)
384 addJsonValue(sb, indent + 2, value);
385 if (entriesI.hasNext())
395 private void addJsonValue(StringBuilder sb, int indent, Object value)
403 if (value instanceof Map.Entry)
405 Map.Entry<String, Object> entry = (Map.Entry<String, Object>) value;
406 List<Map.Entry<String, Object>> object = new ArrayList<>();
408 addJsonObject(sb, indent, object);
410 else if (value instanceof List)
412 // list of Map.Entries or list of values?
413 List<Object> valueList = (List<Object>) value;
414 if (valueList.size() > 0 && valueList.get(0) instanceof Map.Entry)
417 // indent(sb, indent);
418 List<Map.Entry<String, Object>> entryList = (List<Map.Entry<String, Object>>) value;
419 addJsonObject(sb, indent, entryList);
427 Iterator<Object> valueListI = valueList.iterator();
428 while (valueListI.hasNext())
430 Object v = valueListI.next();
431 addJsonValue(sb, indent + 1, v);
432 if (valueListI.hasNext())
442 else if (value instanceof String)
444 sb.append('"').append(quoteEscape((String) value)).append('"');
446 else if (value instanceof Integer)
448 sb.append(((Integer) value).toString());
450 else if (value instanceof Boolean)
452 sb.append('"').append(((Boolean) value).toString()).append('"');
454 } catch (ClassCastException e)
457 "Could not deal with type of json Object " + value.toString(),
462 private static String quoteEscape(String s)
468 // this escapes quotation marks (") that aren't already escaped (in the
469 // string) ready to go into a quoted JSON string value
470 return s.replaceAll("((?<!\\\\)(?:\\\\{2})*)\"", "$1\\\\\"");
473 private static void prettyWhitespace(StringBuilder sb, String whitespace,
476 // only add whitespace if we're in DEBUG mode
477 if (!Console.getLogger().isDebugEnabled())
481 if (repeat >= 0 && whitespace != null)
483 // sb.append(whitespace.repeat(repeat));
484 sb.append(String.join("", Collections.nCopies(repeat, whitespace)));
489 sb.append(whitespace);
493 private static void indent(StringBuilder sb, int indent)
495 prettyWhitespace(sb, " ", indent);
498 private static void newline(StringBuilder sb)
500 prettyWhitespace(sb, "\n", -1);
503 private static void space(StringBuilder sb)
505 prettyWhitespace(sb, " ", -1);
508 protected static Map.Entry<String, Object> objectEntry(String s, Object o)
510 return new AbstractMap.SimpleEntry<String, Object>(s, o);
513 protected static Map.Entry<String, String> stringEntry(String s, String v)
515 return new AbstractMap.SimpleEntry<String, String>(s, v);
518 private static String getAPIBaseURL()
522 URL url = new URL(CONFIG_API_BASE_URL);
523 URLConnection urlConnection = url.openConnection();
524 HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
525 httpURLConnection.setRequestMethod("GET");
526 httpURLConnection.setRequestProperty("User-Agent", USER_AGENT);
527 httpURLConnection.setConnectTimeout(5000);
528 httpURLConnection.setReadTimeout(3000);
529 httpURLConnection.connect();
530 int responseCode = httpURLConnection.getResponseCode();
531 String responseMessage = httpURLConnection.getResponseMessage();
533 if (responseCode < 200 || responseCode > 299)
535 Console.warn("Config URL connection to '" + CONFIG_API_BASE_URL
536 + "' failed: '" + responseCode + " " + responseMessage
540 BufferedReader br = new BufferedReader(
541 new InputStreamReader((httpURLConnection.getInputStream())));
542 StringBuilder sb = new StringBuilder();
544 while ((response = br.readLine()) != null)
548 if (sb.length() > 7 && sb.substring(0, 5).equals("https"))
550 return sb.toString();
553 } catch (MalformedURLException e)
555 Console.debug("Somehow the config URL is malformed: '"
556 + CONFIG_API_BASE_URL + "'", e);
557 } catch (IOException e)
559 Console.debug("Connection to Plausible BASE_URL '" + API_BASE_URL
561 } catch (ClassCastException e)
564 "Couldn't cast URLConnection to HttpURLConnection in Plausible.",
567 return DEFAULT_API_BASE_URL;