Rewrote ServiceChecker, fixed NPE there

Formatting
This commit is contained in:
Jerome van der Sar
2013-11-30 20:44:08 +01:00
parent 6fca19fa41
commit 7ce052900e
7 changed files with 393 additions and 261 deletions

View File

@ -54,70 +54,61 @@ import java.util.UUID;
import java.util.logging.Level;
import java.util.zip.GZIPOutputStream;
public class Metrics {
public class Metrics
{
/**
* The current revision number
*/
private final static int REVISION = 7;
/**
* The base url of the metrics domain
*/
private static final String BASE_URL = "http://report.mcstats.org";
/**
* The url used to report a server's status
*/
private static final String REPORT_URL = "/plugin/%s";
/**
* Interval of time to ping (in minutes)
*/
private static final int PING_INTERVAL = 15;
/**
* The plugin this metrics submits for
*/
private final Plugin plugin;
/**
* All of the custom graphs to submit to metrics
*/
private final Set<Graph> graphs = Collections.synchronizedSet(new HashSet<Graph>());
/**
* The plugin configuration file
*/
private final YamlConfiguration configuration;
/**
* The plugin configuration file
*/
private final File configurationFile;
/**
* Unique server id
*/
private final String guid;
/**
* Debug mode
*/
private final boolean debug;
/**
* Lock for synchronization
*/
private final Object optOutLock = new Object();
/**
* The scheduled task
*/
private volatile BukkitTask task = null;
public Metrics(final Plugin plugin) throws IOException {
if (plugin == null) {
public Metrics(final Plugin plugin) throws IOException
{
if (plugin == null)
{
throw new IllegalArgumentException("Plugin cannot be null");
}
@ -133,7 +124,8 @@ public class Metrics {
configuration.addDefault("debug", false);
// 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").copyDefaults(true);
configuration.save(configurationFile);
}
@ -150,8 +142,10 @@ public class Metrics {
* @param name The name of the graph
* @return Graph object created. Will never return NULL under normal circumstances unless bad parameters are given
*/
public Graph createGraph(final String name) {
if (name == null) {
public Graph createGraph(final String name)
{
if (name == null)
{
throw new IllegalArgumentException("Graph name cannot be null");
}
@ -170,8 +164,10 @@ public class Metrics {
*
* @param graph The name of the graph
*/
public void addGraph(final Graph graph) {
if (graph == null) {
public void addGraph(final Graph graph)
{
if (graph == null)
{
throw new IllegalArgumentException("Graph cannot be null");
}
@ -185,33 +181,42 @@ public class Metrics {
*
* @return True if statistics measuring is running, otherwise false.
*/
public boolean start() {
synchronized (optOutLock) {
public boolean start()
{
synchronized (optOutLock)
{
// Did we opt out?
if (isOptOut()) {
if (isOptOut())
{
return false;
}
// Is metrics already running?
if (task != null) {
if (task != null)
{
return true;
}
// Begin hitting the server with glorious data
task = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, new Runnable() {
task = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, new Runnable()
{
private boolean firstPost = true;
public void run() {
try {
public void run()
{
try
{
// This has to be synchronized or it can collide with the disable method.
synchronized (optOutLock) {
synchronized (optOutLock)
{
// Disable Task, if it is running and the server owner decided to opt-out
if (isOptOut() && task != null) {
if (isOptOut() && task != null)
{
task.cancel();
task = null;
// Tell all plotters to stop gathering information.
for (Graph graph : graphs) {
for (Graph graph : graphs)
{
graph.onOptOut();
}
}
@ -225,8 +230,11 @@ public class Metrics {
// After the first post we set firstPost to false
// Each post thereafter will be a ping
firstPost = false;
} catch (IOException e) {
if (debug) {
}
catch (IOException e)
{
if (debug)
{
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage());
}
}
@ -242,18 +250,27 @@ public class Metrics {
*
* @return true if metrics should be opted out of it
*/
public boolean isOptOut() {
synchronized (optOutLock) {
try {
public boolean isOptOut()
{
synchronized (optOutLock)
{
try
{
// Reload the metrics file
configuration.load(getConfigFile());
} catch (IOException ex) {
if (debug) {
}
catch (IOException ex)
{
if (debug)
{
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage());
}
return true;
} catch (InvalidConfigurationException ex) {
if (debug) {
}
catch (InvalidConfigurationException ex)
{
if (debug)
{
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage());
}
return true;
@ -267,17 +284,21 @@ public class Metrics {
*
* @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 task.
synchronized (optOutLock) {
synchronized (optOutLock)
{
// Check if the server owner has already set opt-out, if not, set it.
if (isOptOut()) {
if (isOptOut())
{
configuration.set("opt-out", false);
configuration.save(configurationFile);
}
// Enable Task, if it is not running
if (task == null) {
if (task == null)
{
start();
}
}
@ -288,17 +309,21 @@ public class Metrics {
*
* @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 task.
synchronized (optOutLock) {
synchronized (optOutLock)
{
// Check if the server owner has already set opt-out, if not, set it.
if (!isOptOut()) {
if (!isOptOut())
{
configuration.set("opt-out", true);
configuration.save(configurationFile);
}
// Disable Task, if it is running
if (task != null) {
if (task != null)
{
task.cancel();
task = null;
}
@ -310,7 +335,8 @@ public class Metrics {
*
* @return the File object for the config file
*/
public File getConfigFile() {
public File getConfigFile()
{
// I believe the easiest way to get the base folder (e.g craftbukkit set via -P) for plugins to use
// is to abuse the plugin object we already have
// plugin.getDataFolder() => base/plugins/PluginA/
@ -325,7 +351,8 @@ public class Metrics {
/**
* Generic method that posts a plugin to the metrics website
*/
private void postPlugin(final boolean isPing) throws IOException {
private void postPlugin(final boolean isPing) throws IOException
{
// Server software specific section
PluginDescriptionFile description = plugin.getDescription();
String pluginName = description.getName();
@ -354,7 +381,8 @@ public class Metrics {
int coreCount = Runtime.getRuntime().availableProcessors();
// normalize os arch .. amd64 -> x86_64
if (osarch.equals("amd64")) {
if (osarch.equals("amd64"))
{
osarch = "x86_64";
}
@ -366,12 +394,15 @@ public class Metrics {
appendJSONPair(json, "java_version", java_version);
// If we're pinging, append it
if (isPing) {
if (isPing)
{
appendJSONPair(json, "ping", "1");
}
if (graphs.size() > 0) {
synchronized (graphs) {
if (graphs.size() > 0)
{
synchronized (graphs)
{
json.append(',');
json.append('"');
json.append("graphs");
@ -383,19 +414,22 @@ public class Metrics {
final Iterator<Graph> iter = graphs.iterator();
while (iter.hasNext()) {
while (iter.hasNext())
{
Graph graph = iter.next();
StringBuilder graphJson = new StringBuilder();
graphJson.append('{');
for (Plotter plotter : graph.getPlotters()) {
for (Plotter plotter : graph.getPlotters())
{
appendJSONPair(graphJson, plotter.getColumnName(), Integer.toString(plotter.getValue()));
}
graphJson.append('}');
if (!firstGraph) {
if (!firstGraph)
{
json.append(',');
}
@ -421,9 +455,12 @@ public class Metrics {
// Mineshafter creates a socks proxy, so we can safely bypass it
// It does not reroute POST requests so we need to go around it
if (isMineshafterPresent()) {
if (isMineshafterPresent())
{
connection = url.openConnection(Proxy.NO_PROXY);
} else {
}
else
{
connection = url.openConnection();
}
@ -441,7 +478,8 @@ public class Metrics {
connection.setDoOutput(true);
if (debug) {
if (debug)
{
System.out.println("[Metrics] Prepared request for " + pluginName + " uncompressed=" + uncompressed.length + " compressed=" + compressed.length);
}
@ -458,24 +496,34 @@ public class Metrics {
os.close();
reader.close();
if (response == null || response.startsWith("ERR") || response.startsWith("7")) {
if (response == null) {
if (response == null || response.startsWith("ERR") || response.startsWith("7"))
{
if (response == null)
{
response = "null";
} else if (response.startsWith("7")) {
}
else if (response.startsWith("7"))
{
response = response.substring(response.startsWith("7,") ? 2 : 1);
}
throw new IOException(response);
} else {
}
else
{
// Is this the first update this hour?
if (response.equals("1") || response.contains("This is your first update this hour")) {
synchronized (graphs) {
if (response.equals("1") || response.contains("This is your first update this hour"))
{
synchronized (graphs)
{
final Iterator<Graph> iter = graphs.iterator();
while (iter.hasNext()) {
while (iter.hasNext())
{
final Graph graph = iter.next();
for (Plotter plotter : graph.getPlotters()) {
for (Plotter plotter : graph.getPlotters())
{
plotter.reset();
}
}
@ -490,19 +538,31 @@ public class Metrics {
* @param input
* @return
*/
public static byte[] gzip(String input) {
public static byte[] gzip(String input)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzos = null;
try {
try
{
gzos = new GZIPOutputStream(baos);
gzos.write(input.getBytes("UTF-8"));
} catch (IOException e) {
}
catch (IOException e)
{
e.printStackTrace();
} finally {
if (gzos != null) try {
gzos.close();
} catch (IOException ignore) {
}
finally
{
if (gzos != null)
{
try
{
gzos.close();
}
catch (IOException ignore)
{
}
}
}
@ -514,11 +574,15 @@ public class Metrics {
*
* @return true if mineshafter is installed on the server
*/
private boolean isMineshafterPresent() {
try {
private boolean isMineshafterPresent()
{
try
{
Class.forName("mineshafter.MineServer");
return true;
} catch (Exception e) {
}
catch (Exception e)
{
return false;
}
}
@ -531,28 +595,37 @@ public class Metrics {
* @param value
* @throws UnsupportedEncodingException
*/
private static void appendJSONPair(StringBuilder json, String key, String value) throws UnsupportedEncodingException {
private static void appendJSONPair(StringBuilder json, String key, String value) throws UnsupportedEncodingException
{
boolean isValueNumeric = false;
try {
if (value.equals("0") || !value.endsWith("0")) {
try
{
if (value.equals("0") || !value.endsWith("0"))
{
Double.parseDouble(value);
isValueNumeric = true;
}
} catch (NumberFormatException e) {
}
catch (NumberFormatException e)
{
isValueNumeric = false;
}
if (json.charAt(json.length() - 1) != '{') {
if (json.charAt(json.length() - 1) != '{')
{
json.append(',');
}
json.append(escapeJSON(key));
json.append(':');
if (isValueNumeric) {
if (isValueNumeric)
{
json.append(value);
} else {
}
else
{
json.append(escapeJSON(value));
}
}
@ -563,14 +636,17 @@ public class Metrics {
* @param text
* @return
*/
private static String escapeJSON(String text) {
private static String escapeJSON(String text)
{
StringBuilder builder = new StringBuilder();
builder.append('"');
for (int index = 0; index < text.length(); index++) {
for (int index = 0; index < text.length(); index++)
{
char chr = text.charAt(index);
switch (chr) {
switch (chr)
{
case '"':
case '\\':
builder.append('\\');
@ -589,10 +665,13 @@ public class Metrics {
builder.append("\\r");
break;
default:
if (chr < ' ') {
if (chr < ' ')
{
String t = "000" + Integer.toHexString(chr);
builder.append("\\u" + t.substring(t.length() - 4));
} else {
}
else
{
builder.append(chr);
}
break;
@ -609,27 +688,28 @@ public class Metrics {
* @param text the text to encode
* @return the encoded text, as UTF-8
*/
private static String urlEncode(final String text) throws UnsupportedEncodingException {
private static String urlEncode(final String text) throws UnsupportedEncodingException
{
return URLEncoder.encode(text, "UTF-8");
}
/**
* Represents a custom graph on the website
*/
public static class Graph {
public static class Graph
{
/**
* The graph's name, alphanumeric and spaces only :) If it does not comply to the above when submitted, it is
* rejected
*/
private final String name;
/**
* The set of plotters that are contained within this graph
*/
private final Set<Plotter> plotters = new LinkedHashSet<Plotter>();
private Graph(final String name) {
private Graph(final String name)
{
this.name = name;
}
@ -638,7 +718,8 @@ public class Metrics {
*
* @return the Graph's name
*/
public String getName() {
public String getName()
{
return name;
}
@ -647,7 +728,8 @@ public class Metrics {
*
* @param plotter the plotter to add to the graph
*/
public void addPlotter(final Plotter plotter) {
public void addPlotter(final Plotter plotter)
{
plotters.add(plotter);
}
@ -656,7 +738,8 @@ public class Metrics {
*
* @param plotter the plotter to remove from the graph
*/
public void removePlotter(final Plotter plotter) {
public void removePlotter(final Plotter plotter)
{
plotters.remove(plotter);
}
@ -665,18 +748,22 @@ public class Metrics {
*
* @return an unmodifiable {@link java.util.Set} of the plotter objects
*/
public Set<Plotter> getPlotters() {
public Set<Plotter> getPlotters()
{
return Collections.unmodifiableSet(plotters);
}
@Override
public int hashCode() {
public int hashCode()
{
return name.hashCode();
}
@Override
public boolean equals(final Object object) {
if (!(object instanceof Graph)) {
public boolean equals(final Object object)
{
if (!(object instanceof Graph))
{
return false;
}
@ -687,15 +774,16 @@ public class Metrics {
/**
* Called when the server owner decides to opt-out of BukkitMetrics while the server is running.
*/
protected void onOptOut() {
protected void onOptOut()
{
}
}
/**
* Interface used to collect custom data for a plugin
*/
public static abstract class Plotter {
public static abstract class Plotter
{
/**
* The plot's name
*/
@ -704,7 +792,8 @@ public class Metrics {
/**
* Construct a plotter with the default plot name
*/
public Plotter() {
public Plotter()
{
this("Default");
}
@ -713,7 +802,8 @@ public class Metrics {
*
* @param name the name of the plotter to use, which will show up on the website
*/
public Plotter(final String name) {
public Plotter(final String name)
{
this.name = name;
}
@ -731,24 +821,29 @@ public class Metrics {
*
* @return the plotted point's column name
*/
public String getColumnName() {
public String getColumnName()
{
return name;
}
/**
* Called after the website graphs have been updated
*/
public void reset() {
public void reset()
{
}
@Override
public int hashCode() {
public int hashCode()
{
return getColumnName().hashCode();
}
@Override
public boolean equals(final Object object) {
if (!(object instanceof Plotter)) {
public boolean equals(final Object object)
{
if (!(object instanceof Plotter))
{
return false;
}