loadConfig(); } catch (IOException e) { Class<?> usedMetricsClass = getFirstBStatsClass(); if (usedMetricsClass == null) { linkMetrics(this); startSubmitting(); } else {
/** * Collects the data and sends it afterwards. */ private void submitData() { final JsonObject data = getServerData(); JsonArray pluginData = new JsonArray(); // Search for all other bStats Metrics classes to get their plugin data for (Object metrics : knownMetricsInstances) { try { Object plugin = metrics.getClass().getMethod("getPluginData").invoke(metrics); if (plugin instanceof JsonObject) { pluginData.add((JsonObject) plugin); } } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { } } data.add("plugins", pluginData); // Create a new thread for the connection to the bStats server new Thread(() -> { try { // Send the data sendData(data); } catch (Exception e) { // Something went wrong! :( if (logFailedRequests) { logger.warn("Could not submit plugin stats!", e); } } }).start(); }
/** * Gets the first bStat Metrics class. * * @return The first bStats metrics class. */ private Class<?> getFirstBStatsClass() { Path configPath = configDir.resolve("bStats"); configPath.toFile().mkdirs(); File tempFile = new File(configPath.toFile(), "temp.txt"); try { String className = readFile(tempFile); if (className != null) { try { // Let's check if a class with the given name exists. return Class.forName(className); } catch (ClassNotFoundException ignored) { } } writeFile(tempFile, getClass().getName()); return getClass(); } catch (IOException e) { if (logFailedRequests) { logger.warn("Failed to get first bStats class!", e); } return null; } }
/** * Sends the data to the bStats server. * * @param data The data to send. * @throws Exception If the request failed. */ private static void sendData(JsonObject data) throws Exception { Validate.notNull(data, "Data cannot be null"); HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection(); // Compress the data to save bandwidth byte[] compressedData = compress(data.toString()); // Add headers connection.setRequestMethod("POST"); connection.addRequestProperty("Accept", "application/json"); connection.addRequestProperty("Connection", "close"); connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION); // Send data connection.setDoOutput(true); DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); outputStream.write(compressedData); outputStream.flush(); outputStream.close(); connection.getInputStream().close(); // We don't care about the response - Just send our data :) }