Use RegisteredServiceProvider to hook PlayerPoints

This commit is contained in:
Jakub Kolář 2016-12-12 13:22:59 +01:00
parent cace3a4a2d
commit 079550c5f7
4 changed files with 99 additions and 118 deletions

View File

@ -368,15 +368,6 @@ public class BoosCoolDown extends JavaPlugin implements Runnable {
} }
private boolean hookPlayerPoints() {
final Plugin plugin = this.getServer().getPluginManager().getPlugin("PlayerPoints");
playerPoints = PlayerPoints.class.cast(plugin);
if (playerPoints != null) {
log.info("[" + pdfFile.getName() + "]" + " found [PlayerPoints], enabling support.");
}
return playerPoints != null;
}
private void registerListeners() { private void registerListeners() {
HandlerList.unregisterAll(this); HandlerList.unregisterAll(this);
pm.registerEvents(new BoosCoolDownListener(this), this); pm.registerEvents(new BoosCoolDownListener(this), this);
@ -431,4 +422,15 @@ public class BoosCoolDown extends JavaPlugin implements Runnable {
} }
return false; return false;
} }
private boolean hookPlayerPoints() {
RegisteredServiceProvider<PlayerPoints> playerPointsProvider = getServer()
.getServicesManager()
.getRegistration(org.black_ixx.playerpoints.PlayerPoints.class);
if (playerPointsProvider != null) {
playerPoints = playerPointsProvider.getProvider();
log.info("[" + pdfFile.getName() + "]" + " found [PlayerPoints], enabling support.");
}
return playerPoints != null;
}
} }

View File

@ -35,10 +35,12 @@ import java.io.IOException;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.OutputStream; import java.io.OutputStream;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.Proxy; import java.net.Proxy;
import java.net.URL; import java.net.URL;
import java.net.URLConnection; import java.net.URLConnection;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.util.Collection;
import java.util.UUID; import java.util.UUID;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.zip.GZIPOutputStream; import java.util.zip.GZIPOutputStream;
@ -46,13 +48,11 @@ import java.util.zip.GZIPOutputStream;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.scheduler.BukkitTask; import org.bukkit.scheduler.BukkitTask;
import cz.boosik.boosCooldown.BoosCoolDown;
@SuppressWarnings("ALL")
public class MetricsLite { public class MetricsLite {
/** /**
@ -128,8 +128,7 @@ public class MetricsLite {
// Do we need to create the file? // Do we need to create the file?
if (configuration.get("guid", null) == null) { if (configuration.get("guid", null) == null) {
configuration.options().header("http://mcstats.org") configuration.options().header("http://mcstats.org").copyDefaults(true);
.copyDefaults(true);
configuration.save(configurationFile); configuration.save(configurationFile);
} }
@ -144,7 +143,7 @@ public class MetricsLite {
* @param input * @param input
* @return * @return
*/ */
private static byte[] gzip(String input) { public static byte[] gzip(String input) {
ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzos = null; GZIPOutputStream gzos = null;
@ -154,11 +153,9 @@ public class MetricsLite {
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
if (gzos != null) { if (gzos != null) try {
try { gzos.close();
gzos.close(); } catch (IOException ignore) {
} catch (IOException ignore) {
}
} }
} }
@ -173,8 +170,7 @@ public class MetricsLite {
* @param value * @param value
* @throws UnsupportedEncodingException * @throws UnsupportedEncodingException
*/ */
private static void appendJSONPair(StringBuilder json, String key, private static void appendJSONPair(StringBuilder json, String key, String value) throws UnsupportedEncodingException {
String value) throws UnsupportedEncodingException {
boolean isValueNumeric = false; boolean isValueNumeric = false;
try { try {
@ -252,16 +248,14 @@ public class MetricsLite {
* @param text the text to encode * @param text the text to encode
* @return the encoded text, as UTF-8 * @return the encoded text, as UTF-8
*/ */
private static String urlEncode(final String text) private static String urlEncode(final String text) throws UnsupportedEncodingException {
throws UnsupportedEncodingException {
return URLEncoder.encode(text, "UTF-8"); return URLEncoder.encode(text, "UTF-8");
} }
/** /**
* Start measuring statistics. This will immediately create an async * Start measuring statistics. This will immediately create an async repeating task as the plugin and send
* repeating task as the plugin and send the initial data to the metrics * the initial data to the metrics backend, and then after that it will post in increments of
* backend, and then after that it will post in increments of PING_INTERVAL * PING_INTERVAL * 1200 ticks.
* * 1200 ticks.
* *
* @return True if statistics measuring is running, otherwise false. * @return True if statistics measuring is running, otherwise false.
*/ */
@ -278,44 +272,36 @@ public class MetricsLite {
} }
// Begin hitting the server with glorious data // Begin hitting the server with glorious data
task = plugin.getServer().getScheduler() task = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, new Runnable() {
.runTaskTimerAsynchronously(plugin, new Runnable() {
private boolean firstPost = true; private boolean firstPost = true;
public void run() { public void run() {
try { try {
// This has to be synchronized or it can collide // This has to be synchronized or it can collide with the disable method.
// with the disable method. synchronized (optOutLock) {
synchronized (optOutLock) { // Disable Task, if it is running and the server owner decided to opt-out
// Disable Task, if it is running and the if (isOptOut() && task != null) {
// server owner decided to opt-out task.cancel();
if (isOptOut() && task != null) { task = null;
task.cancel();
task = null;
}
}
// We use the inverse of firstPost because if it
// is the first time we are posting,
// it is not a interval ping, so it evaluates to
// FALSE
// Each time thereafter it will evaluate to
// TRUE, i.e PING!
postPlugin(!firstPost);
// After the first post we set firstPost to
// false
// Each post thereafter will be a ping
firstPost = false;
} catch (IOException e) {
if (debug) {
Bukkit.getLogger().log(Level.INFO,
"[Metrics] " + e.getMessage());
}
} }
} }
}, 0, PING_INTERVAL * 1200);
// We use the inverse of firstPost because if it is the first time we are posting,
// it is not a interval ping, so it evaluates to FALSE
// Each time thereafter it will evaluate to TRUE, i.e PING!
postPlugin(!firstPost);
// After the first post we set firstPost to false
// Each post thereafter will be a ping
firstPost = false;
} catch (IOException e) {
if (debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage());
}
}
}
}, 0, PING_INTERVAL * 1200);
return true; return true;
} }
@ -326,21 +312,19 @@ public class MetricsLite {
* *
* @return true if metrics should be opted out of it * @return true if metrics should be opted out of it
*/ */
boolean isOptOut() { public boolean isOptOut() {
synchronized (optOutLock) { synchronized (optOutLock) {
try { try {
// Reload the metrics file // Reload the metrics file
configuration.load(getConfigFile()); configuration.load(getConfigFile());
} catch (IOException ex) { } catch (IOException ex) {
if (debug) { if (debug) {
Bukkit.getLogger().log(Level.INFO, Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage());
"[Metrics] " + ex.getMessage());
} }
return true; return true;
} catch (InvalidConfigurationException ex) { } catch (InvalidConfigurationException ex) {
if (debug) { if (debug) {
Bukkit.getLogger().log(Level.INFO, Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage());
"[Metrics] " + ex.getMessage());
} }
return true; return true;
} }
@ -349,17 +333,14 @@ public class MetricsLite {
} }
/** /**
* Enables metrics for the server by setting "opt-out" to false in the * Enables metrics for the server by setting "opt-out" to false in the config file and starting the metrics task.
* config file and starting the metrics task.
* *
* @throws java.io.IOException * @throws java.io.IOException
*/ */
public void enable() throws IOException { public void enable() throws IOException {
// This has to be synchronized or it can collide with the check in the // This has to be synchronized or it can collide with the check in the task.
// task.
synchronized (optOutLock) { synchronized (optOutLock) {
// Check if the server owner has already set opt-out, if not, set // Check if the server owner has already set opt-out, if not, set it.
// it.
if (isOptOut()) { if (isOptOut()) {
configuration.set("opt-out", false); configuration.set("opt-out", false);
configuration.save(configurationFile); configuration.save(configurationFile);
@ -373,17 +354,14 @@ public class MetricsLite {
} }
/** /**
* Disables metrics for the server by setting "opt-out" to true in the * Disables metrics for the server by setting "opt-out" to true in the config file and canceling the metrics task.
* config file and canceling the metrics task.
* *
* @throws java.io.IOException * @throws java.io.IOException
*/ */
public void disable() throws IOException { public void disable() throws IOException {
// This has to be synchronized or it can collide with the check in the // This has to be synchronized or it can collide with the check in the task.
// task.
synchronized (optOutLock) { synchronized (optOutLock) {
// Check if the server owner has already set opt-out, if not, set // Check if the server owner has already set opt-out, if not, set it.
// it.
if (!isOptOut()) { if (!isOptOut()) {
configuration.set("opt-out", true); configuration.set("opt-out", true);
configuration.save(configurationFile); configuration.save(configurationFile);
@ -398,14 +376,12 @@ public class MetricsLite {
} }
/** /**
* Gets the File object of the config file that should be used to store data * Gets the File object of the config file that should be used to store data such as the GUID and opt-out status
* such as the GUID and opt-out status
* *
* @return the File object for the config file * @return the File object for the config file
*/ */
File getConfigFile() { public File getConfigFile() {
// I believe the easiest way to get the base folder (e.g craftbukkit set // I believe the easiest way to get the base folder (e.g craftbukkit set via -P) for plugins to use
// via -P) for plugins to use
// is to abuse the plugin object we already have // is to abuse the plugin object we already have
// plugin.getDataFolder() => base/plugins/PluginA/ // plugin.getDataFolder() => base/plugins/PluginA/
// pluginsFolder => base/plugins/ // pluginsFolder => base/plugins/
@ -416,6 +392,28 @@ public class MetricsLite {
return new File(new File(pluginsFolder, "PluginMetrics"), "config.yml"); return new File(new File(pluginsFolder, "PluginMetrics"), "config.yml");
} }
/**
* Gets the online player (backwards compatibility)
*
* @return online player amount
*/
private int getOnlinePlayers() {
try {
Method onlinePlayerMethod = Bukkit.class.getMethod("getOnlinePlayers");
if (onlinePlayerMethod.getReturnType().equals(Collection.class)) {
return ((Collection<?>) onlinePlayerMethod.invoke(Bukkit.class)).size();
} else {
return ((Player[]) onlinePlayerMethod.invoke(Bukkit.class)).length;
}
} catch (Exception ex) {
if (debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage());
}
}
return 0;
}
/** /**
* Generic method that posts a plugin to the metrics website * Generic method that posts a plugin to the metrics website
*/ */
@ -423,31 +421,18 @@ public class MetricsLite {
// Server software specific section // Server software specific section
PluginDescriptionFile description = plugin.getDescription(); PluginDescriptionFile description = plugin.getDescription();
String pluginName = description.getName(); String pluginName = description.getName();
boolean onlineMode = Bukkit.getServer().getOnlineMode(); // TRUE if boolean onlineMode = Bukkit.getServer().getOnlineMode(); // TRUE if online mode is enabled
// online
// mode is
// enabled
String pluginVersion = description.getVersion(); String pluginVersion = description.getVersion();
String serverVersion = Bukkit.getVersion(); String serverVersion = Bukkit.getVersion();
int playersOnline = 0; int playersOnline = this.getOnlinePlayers();
try {
playersOnline = Bukkit.getServer().getOnlinePlayers().size();
} catch (Exception e) {
BoosCoolDown
.getLog()
.warning(
"[boosCooldowns] This error was caused because you are using old CraftBukkit version. Please update to 1.7.10 (1.7.9-R0.3).");
}
// END server software specific section -- all code below does not use // END server software specific section -- all code below does not use any code outside of this class / Java
// any code outside of this class / Java
// Construct the post data // Construct the post data
StringBuilder json = new StringBuilder(1024); StringBuilder json = new StringBuilder(1024);
json.append('{'); json.append('{');
// The plugin's description file containg all of the plugin data such as // The plugin's description file containg all of the plugin data such as name, version, author, etc
// name, version, author, etc
appendJSONPair(json, "guid", guid); appendJSONPair(json, "guid", guid);
appendJSONPair(json, "plugin_version", pluginVersion); appendJSONPair(json, "plugin_version", pluginVersion);
appendJSONPair(json, "server_version", serverVersion); appendJSONPair(json, "server_version", serverVersion);
@ -481,8 +466,7 @@ public class MetricsLite {
json.append('}'); json.append('}');
// Create the url // Create the url
URL url = new URL(BASE_URL URL url = new URL(BASE_URL + String.format(REPORT_URL, urlEncode(pluginName)));
+ String.format(REPORT_URL, urlEncode(pluginName)));
// Connect to the website // Connect to the website
URLConnection connection; URLConnection connection;
@ -495,6 +479,7 @@ public class MetricsLite {
connection = url.openConnection(); connection = url.openConnection();
} }
byte[] uncompressed = json.toString().getBytes(); byte[] uncompressed = json.toString().getBytes();
byte[] compressed = gzip(json.toString()); byte[] compressed = gzip(json.toString());
@ -502,17 +487,15 @@ public class MetricsLite {
connection.addRequestProperty("User-Agent", "MCStats/" + REVISION); connection.addRequestProperty("User-Agent", "MCStats/" + REVISION);
connection.addRequestProperty("Content-Type", "application/json"); connection.addRequestProperty("Content-Type", "application/json");
connection.addRequestProperty("Content-Encoding", "gzip"); connection.addRequestProperty("Content-Encoding", "gzip");
connection.addRequestProperty("Content-Length", connection.addRequestProperty("Content-Length", Integer.toString(compressed.length));
Integer.toString(compressed.length));
connection.addRequestProperty("Accept", "application/json"); connection.addRequestProperty("Accept", "application/json");
connection.addRequestProperty("Connection", "close"); connection.addRequestProperty("Connection", "close");
connection.setDoOutput(true); connection.setDoOutput(true);
if (debug) { if (debug) {
System.out.println("[Metrics] Prepared request for " + pluginName System.out.println("[Metrics] Prepared request for " + pluginName + " uncompressed=" + uncompressed.length + " compressed=" +
+ " uncompressed=" + uncompressed.length + " compressed=" compressed.length);
+ compressed.length);
} }
// Write the data // Write the data
@ -521,21 +504,18 @@ public class MetricsLite {
os.flush(); os.flush();
// Now read the response // Now read the response
final BufferedReader reader = new BufferedReader(new InputStreamReader( final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
connection.getInputStream()));
String response = reader.readLine(); String response = reader.readLine();
// close resources // close resources
os.close(); os.close();
reader.close(); reader.close();
if (response == null || response.startsWith("ERR") if (response == null || response.startsWith("ERR") || response.startsWith("7")) {
|| response.startsWith("7")) {
if (response == null) { if (response == null) {
response = "null"; response = "null";
} else if (response.startsWith("7")) { } else if (response.startsWith("7")) {
response = response response = response.substring(response.startsWith("7,") ? 2 : 1);
.substring(response.startsWith("7,") ? 2 : 1);
} }
throw new IOException(response); throw new IOException(response);
@ -543,8 +523,7 @@ public class MetricsLite {
} }
/** /**
* Check if mineshafter is present. If it is, we need to bypass it to send * Check if mineshafter is present. If it is, we need to bypass it to send POST requests
* POST requests
* *
* @return true if mineshafter is installed on the server * @return true if mineshafter is installed on the server
*/ */

View File

@ -1,6 +1,6 @@
name: boosCooldowns name: boosCooldowns
main: cz.boosik.boosCooldown.BoosCoolDown main: cz.boosik.boosCooldown.BoosCoolDown
version: 3.13.0 version: 3.13.1
authors: [LordBoos (boosik)] authors: [LordBoos (boosik)]
softdepend: [Vault, PlayerPoints] softdepend: [Vault, PlayerPoints]
description: > description: >

View File

@ -11,7 +11,7 @@
<packaging>pom</packaging> <packaging>pom</packaging>
<url>http://maven.apache.org</url> <url>http://maven.apache.org</url>
<properties> <properties>
<boosCooldowns.version>3.13.0</boosCooldowns.version> <boosCooldowns.version>3.13.1</boosCooldowns.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<minecraft.version>1.11</minecraft.version> <minecraft.version>1.11</minecraft.version>