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.util.ChannelProperties;
26 import jalview.util.HttpUtils;
28 public class Plausible
30 private static final String USER_AGENT = HttpUtils.getUserAgent(
31 MethodHandles.lookup().lookupClass().getCanonicalName());
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/analytics/config/url";
39 private static final String DEFAULT_API_BASE_URL = "https://plausible.io/api/event";
41 private static final String API_BASE_URL;
43 public static final String APPLICATION_BASE_URL = "desktop://localhost";
45 private List<Map.Entry<String, String>> queryStringValues;
47 private List<Map.Entry<String, Object>> jsonObject;
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> defaultProps;
61 defaultProps = new HashMap<>();
62 defaultProps.put("app_name",
63 ChannelProperties.getProperty("app_name") + " Desktop");
64 defaultProps.put("version", Cache.getProperty("VERSION"));
65 defaultProps.put("build_date",
66 Cache.getDefault("BUILD_DATE", "unknown"));
67 defaultProps.put("java_version", System.getProperty("java.version"));
68 String val = System.getProperty("sys.install4jVersion");
71 defaultProps.put("install4j_version", val);
73 val = System.getProperty("installer_template_version");
76 defaultProps.put("install4j_template_version", val);
78 val = System.getProperty("launcher_version");
81 defaultProps.put("launcher_version", val);
83 defaultProps.put("java_arch",
84 System.getProperty("os.arch") + " "
85 + System.getProperty("os.name") + " "
86 + System.getProperty("os.version"));
87 defaultProps.put("os", System.getProperty("os.name"));
88 defaultProps.put("os_version", System.getProperty("os.version"));
89 defaultProps.put("os_arch", System.getProperty("os.arch"));
90 String installation = Cache.applicationProperties
91 .getProperty("INSTALLATION");
92 if (installation != null)
94 defaultProps.put("installation", installation);
97 // ascertain the API_BASE_URL
98 API_BASE_URL = getAPIBaseURL();
106 public static void setEnabled(boolean b)
111 public void sendEvent(String eventName, String urlString,
112 String... propsStrings)
114 sendEvent(eventName, urlString, false, propsStrings);
118 * The simplest way to send an analytic event.
121 * The event name. To emulate a webpage view use "pageview" and set a
122 * "url" key/value. See https://plausible.io/docs/events-api
123 * @param sendDefaultProps
124 * Flag whether to add the default props about the application.
125 * @param propsStrings
126 * Optional multiple Strings in key, value pairs (there should be an
127 * even number of propsStrings) to be set as property of the event.
128 * To emulate a webpage view set "url" as the URL in a "pageview"
131 public void sendEvent(String eventName, String urlString,
132 boolean sendDefaultProps, String... propsStrings)
134 // clear out old lists
139 Console.debug("Plausible not enabled.");
142 Map<String, String> props = new HashMap<>();
144 // add these to all events from this application instance
145 if (sendDefaultProps)
147 props.putAll(defaultProps);
150 // add (and overwrite with) the passed in props
151 if (propsStrings != null && propsStrings.length > 0)
153 if (propsStrings.length % 2 != 0)
156 "Cannot addEvent with odd number of propsStrings. Ignoring the last one.");
158 for (int i = 0; i < propsStrings.length - 1; i += 2)
160 String key = propsStrings[i];
161 String value = propsStrings[i + 1];
162 props.put(key, value);
166 addJsonValue("domain", DOMAIN);
167 addJsonValue("name", eventName);
168 StringBuilder eventUrlSb = new StringBuilder(APPLICATION_BASE_URL);
169 if (!APPLICATION_BASE_URL.endsWith("/") && !urlString.startsWith("/"))
171 eventUrlSb.append("/");
173 eventUrlSb.append(urlString);
174 addJsonValue("url", eventUrlSb.toString());
175 addJsonObject("props", props);
176 StringBuilder urlSb = new StringBuilder();
177 urlSb.append(API_BASE_URL);
178 String qs = buildQueryString();
179 if (qs != null && qs.length() > 0)
186 URL url = new URL(urlSb.toString());
187 URLConnection urlConnection = url.openConnection();
188 HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
189 httpURLConnection.setRequestMethod("POST");
190 httpURLConnection.setDoOutput(true);
192 String jsonString = buildJson();
195 "Plausible: HTTP Request is: '" + urlSb.toString() + "'");
198 Console.debug("Plausible: User-Agent is: '" + USER_AGENT + "'");
200 Console.debug("Plausible: POSTed JSON is:\n" + jsonString);
202 byte[] jsonBytes = jsonString.getBytes(StandardCharsets.UTF_8);
203 int jsonLength = jsonBytes.length;
205 httpURLConnection.setFixedLengthStreamingMode(jsonLength);
206 httpURLConnection.setRequestProperty("Content-Type",
208 httpURLConnection.setRequestProperty("User-Agent", USER_AGENT);
209 httpURLConnection.connect();
210 try (OutputStream os = httpURLConnection.getOutputStream())
214 int responseCode = httpURLConnection.getResponseCode();
215 String responseMessage = httpURLConnection.getResponseMessage();
217 if (responseCode < 200 || responseCode > 299)
219 Console.warn("Plausible connection failed: '" + responseCode + " "
220 + responseMessage + "'");
224 Console.debug("Plausible connection succeeded: '" + responseCode
225 + " " + responseMessage + "'");
230 BufferedReader br = new BufferedReader(new InputStreamReader(
231 (httpURLConnection.getInputStream())));
232 StringBuilder sb = new StringBuilder();
234 while ((response = br.readLine()) != null)
238 String body = sb.toString();
239 Console.debug("Plausible response content:\n" + body);
241 } catch (MalformedURLException e)
244 "Somehow the Plausible BASE_URL and queryString is malformed: '"
245 + urlSb.toString() + "'",
248 } catch (IOException e)
250 Console.debug("Connection to Plausible BASE_URL '" + API_BASE_URL
252 } catch (ClassCastException e)
255 "Couldn't cast URLConnection to HttpURLConnection in Plausible.",
260 private void addJsonObject(String key, Map<String, String> map)
262 List<Map.Entry<String, ? extends Object>> list = new ArrayList<>();
263 for (String k : map.keySet())
265 list.add(stringEntry(k, map.get(k)));
267 addJsonObject(key, list);
271 private void addJsonObject(String key,
272 List<Map.Entry<String, ? extends Object>> object)
274 jsonObject.add(objectEntry(key, object));
277 private void addJsonValues(String key, List<Object> values)
279 jsonObject.add(objectEntry(key, values));
282 private void addJsonValue(String key, String value)
284 jsonObject.add(objectEntry(key, value));
287 private void addJsonValue(String key, int value)
289 jsonObject.add(objectEntry(key, Integer.valueOf(value)));
292 private void addJsonValue(String key, boolean value)
294 jsonObject.add(objectEntry(key, Boolean.valueOf(value)));
297 private void addQueryStringValue(String key, String value)
299 queryStringValues.add(stringEntry(key, value));
302 private void addCookieValue(String key, String value)
304 cookieValues.add(stringEntry(key, value));
307 private void resetLists()
309 jsonObject = new ArrayList<>();
310 queryStringValues = new ArrayList<>();
311 cookieValues = new ArrayList<>();
314 public static Plausible getInstance()
316 if (instance == null)
318 instance = new Plausible();
323 public static void reset()
325 getInstance().resetLists();
328 private String buildQueryString()
330 StringBuilder sb = new StringBuilder();
331 for (Map.Entry<String, String> entry : queryStringValues)
339 sb.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
340 } catch (UnsupportedEncodingException e)
342 sb.append(entry.getKey());
347 sb.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
348 } catch (UnsupportedEncodingException e)
350 sb.append(entry.getValue());
353 return sb.toString();
356 private void buildCookieHeaders()
358 // TODO not needed yet
361 private String buildJson()
363 StringBuilder sb = new StringBuilder();
364 addJsonObject(sb, 0, jsonObject);
365 return sb.toString();
368 private void addJsonObject(StringBuilder sb, int indent,
369 List<Map.Entry<String, Object>> entries)
374 Iterator<Map.Entry<String, Object>> entriesI = entries.iterator();
375 while (entriesI.hasNext())
377 Map.Entry<String, Object> entry = entriesI.next();
378 String key = entry.getKey();
379 // TODO sensibly escape " characters in key
380 Object value = entry.getValue();
381 indent(sb, indent + 1);
382 sb.append('"').append(quoteEscape(key)).append('"').append(':');
384 if (value != null && value instanceof List)
388 addJsonValue(sb, indent + 2, value);
389 if (entriesI.hasNext())
399 private void addJsonValue(StringBuilder sb, int indent, Object value)
407 if (value instanceof Map.Entry)
409 Map.Entry<String, Object> entry = (Map.Entry<String, Object>) value;
410 List<Map.Entry<String, Object>> object = new ArrayList<>();
412 addJsonObject(sb, indent, object);
414 else if (value instanceof List)
416 // list of Map.Entries or list of values?
417 List<Object> valueList = (List<Object>) value;
418 if (valueList.size() > 0 && valueList.get(0) instanceof Map.Entry)
421 // indent(sb, indent);
422 List<Map.Entry<String, Object>> entryList = (List<Map.Entry<String, Object>>) value;
423 addJsonObject(sb, indent, entryList);
431 Iterator<Object> valueListI = valueList.iterator();
432 while (valueListI.hasNext())
434 Object v = valueListI.next();
435 addJsonValue(sb, indent + 1, v);
436 if (valueListI.hasNext())
446 else if (value instanceof String)
448 sb.append('"').append(quoteEscape((String) value)).append('"');
450 else if (value instanceof Integer)
452 sb.append(((Integer) value).toString());
454 else if (value instanceof Boolean)
456 sb.append('"').append(((Boolean) value).toString()).append('"');
458 } catch (ClassCastException e)
461 "Could not deal with type of json Object " + value.toString(),
466 private static String quoteEscape(String s)
472 // this escapes quotation marks (") that aren't already escaped (in the
473 // string) ready to go into a quoted JSON string value
474 return s.replaceAll("((?<!\\\\)(?:\\\\{2})*)\"", "$1\\\\\"");
477 private static void prettyWhitespace(StringBuilder sb, String whitespace,
480 // only add whitespace if we're in DEBUG mode
481 if (!Console.getLogger().isDebugEnabled())
485 if (repeat >= 0 && whitespace != null)
487 // sb.append(whitespace.repeat(repeat));
488 sb.append(String.join("", Collections.nCopies(repeat, whitespace)));
493 sb.append(whitespace);
497 private static void indent(StringBuilder sb, int indent)
499 prettyWhitespace(sb, " ", indent);
502 private static void newline(StringBuilder sb)
504 prettyWhitespace(sb, "\n", -1);
507 private static void space(StringBuilder sb)
509 prettyWhitespace(sb, " ", -1);
512 protected static Map.Entry<String, Object> objectEntry(String s, Object o)
514 return new AbstractMap.SimpleEntry<String, Object>(s, o);
517 protected static Map.Entry<String, String> stringEntry(String s, String v)
519 return new AbstractMap.SimpleEntry<String, String>(s, v);
522 private static String getAPIBaseURL()
526 URL url = new URL(CONFIG_API_BASE_URL);
527 URLConnection urlConnection = url.openConnection();
528 HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
529 httpURLConnection.setRequestMethod("GET");
530 httpURLConnection.setRequestProperty("User-Agent", USER_AGENT);
531 httpURLConnection.setConnectTimeout(5000);
532 httpURLConnection.setReadTimeout(3000);
533 httpURLConnection.connect();
534 int responseCode = httpURLConnection.getResponseCode();
535 String responseMessage = httpURLConnection.getResponseMessage();
537 if (responseCode < 200 || responseCode > 299)
539 Console.warn("Config URL connection to '" + CONFIG_API_BASE_URL
540 + "' failed: '" + responseCode + " " + responseMessage
544 BufferedReader br = new BufferedReader(
545 new InputStreamReader((httpURLConnection.getInputStream())));
546 StringBuilder sb = new StringBuilder();
548 while ((response = br.readLine()) != null)
552 if (sb.length() > 7 && sb.substring(0, 5).equals("https"))
554 return sb.toString();
557 } catch (MalformedURLException e)
559 Console.debug("Somehow the config URL is malformed: '"
560 + CONFIG_API_BASE_URL + "'", e);
561 } catch (IOException e)
563 Console.debug("Connection to Plausible BASE_URL '" + API_BASE_URL
565 } catch (ClassCastException e)
568 "Couldn't cast URLConnection to HttpURLConnection in Plausible.",
571 return DEFAULT_API_BASE_URL;