Archiviert
13
0

Remove the updater for now

Dieser Commit ist enthalten in:
Dan Mulloy 2014-11-24 11:41:04 -05:00
Ursprung e1e0c4a05a
Commit e69832a82a
2 geänderte Dateien mit 197 neuen und 199 gelöschten Zeilen

Datei anzeigen

@ -2,16 +2,16 @@
* ProtocolLib - Bukkit server library that allows access to the Minecraft protocol. * ProtocolLib - Bukkit server library that allows access to the Minecraft protocol.
* Copyright (C) 2012 Kristian S. Stangeland * Copyright (C) 2012 Kristian S. Stangeland
* *
* This program is free software; you can redistribute it and/or modify it under the terms of the * This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of * GNU General Public License as published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version. * the License, or (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details. * See the GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License along with this program; * You should have received a copy of the GNU General Public License along with this program;
* if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA * if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA * 02111-1307 USA
*/ */
@ -33,7 +33,7 @@ import com.comphenix.protocol.timing.TimingReportGenerator;
/** /**
* Handles the "protocol" administration command. * Handles the "protocol" administration command.
* *
* @author Kristian * @author Kristian
*/ */
class CommandProtocol extends CommandBase { class CommandProtocol extends CommandBase {
@ -41,7 +41,7 @@ class CommandProtocol extends CommandBase {
* Name of this command. * Name of this command.
*/ */
public static final String NAME = "protocol"; public static final String NAME = "protocol";
private Plugin plugin; private Plugin plugin;
private Updater updater; private Updater updater;
private ProtocolConfig config; private ProtocolConfig config;
@ -52,18 +52,18 @@ class CommandProtocol extends CommandBase {
this.updater = updater; this.updater = updater;
this.config = config; this.config = config;
} }
@Override @Override
protected boolean handleCommand(CommandSender sender, String[] args) { protected boolean handleCommand(CommandSender sender, String[] args) {
String subCommand = args[0]; String subCommand = args[0];
// Only return TRUE if we executed the correct command // Only return TRUE if we executed the correct command
if (subCommand.equalsIgnoreCase("config") || subCommand.equalsIgnoreCase("reload")) if (subCommand.equalsIgnoreCase("config") || subCommand.equalsIgnoreCase("reload"))
reloadConfiguration(sender); reloadConfiguration(sender);
else if (subCommand.equalsIgnoreCase("check")) else if (subCommand.equalsIgnoreCase("check"))
checkVersion(sender); checkVersion(sender);
else if (subCommand.equalsIgnoreCase("update")) // else if (subCommand.equalsIgnoreCase("update"))
updateVersion(sender); // updateVersion(sender);
else if (subCommand.equalsIgnoreCase("timings")) else if (subCommand.equalsIgnoreCase("timings"))
toggleTimings(sender, args); toggleTimings(sender, args);
else if (subCommand.equalsIgnoreCase("listeners")) else if (subCommand.equalsIgnoreCase("listeners"))
@ -72,19 +72,19 @@ class CommandProtocol extends CommandBase {
return false; return false;
return true; return true;
} }
public void checkVersion(final CommandSender sender) { public void checkVersion(final CommandSender sender) {
performUpdate(sender, UpdateType.NO_DOWNLOAD); performUpdate(sender, UpdateType.NO_DOWNLOAD);
} }
public void updateVersion(final CommandSender sender) { public void updateVersion(final CommandSender sender) {
performUpdate(sender, UpdateType.DEFAULT); performUpdate(sender, UpdateType.DEFAULT);
} }
// Display every listener on the server // Display every listener on the server
private void printListeners(final CommandSender sender, String[] args) { private void printListeners(final CommandSender sender, String[] args) {
ProtocolManager manager = ProtocolLibrary.getProtocolManager(); ProtocolManager manager = ProtocolLibrary.getProtocolManager();
for (PacketListener listener : manager.getPacketListeners()) { for (PacketListener listener : manager.getPacketListeners()) {
sender.sendMessage(ChatColor.GOLD + "Packet listeners:"); sender.sendMessage(ChatColor.GOLD + "Packet listeners:");
sender.sendMessage(ChatColor.GOLD + " " + listener); sender.sendMessage(ChatColor.GOLD + " " + listener);
@ -95,19 +95,19 @@ class CommandProtocol extends CommandBase {
sender.sendMessage(ChatColor.GOLD + " " + listener); sender.sendMessage(ChatColor.GOLD + " " + listener);
} }
} }
private void performUpdate(final CommandSender sender, UpdateType type) { private void performUpdate(final CommandSender sender, UpdateType type) {
if (updater.isChecking()) { if (updater.isChecking()) {
sender.sendMessage(ChatColor.RED + "Already checking for an update."); sender.sendMessage(ChatColor.RED + "Already checking for an update.");
return; return;
} }
// Perform on an async thread // Perform on an async thread
Runnable notify = new Runnable() { Runnable notify = new Runnable() {
@Override @Override
public void run() { public void run() {
sender.sendMessage(ChatColor.YELLOW + "[ProtocolLib] " + updater.getResult()); sender.sendMessage(ChatColor.YELLOW + "[ProtocolLib] " + updater.getResult());
updater.removeListener(this); updater.removeListener(this);
updateFinished(); updateFinished();
} }
@ -115,15 +115,15 @@ class CommandProtocol extends CommandBase {
updater.start(type); updater.start(type);
updater.addListener(notify); updater.addListener(notify);
} }
private void toggleTimings(CommandSender sender, String[] args) { private void toggleTimings(CommandSender sender, String[] args) {
TimedListenerManager manager = TimedListenerManager.getInstance(); TimedListenerManager manager = TimedListenerManager.getInstance();
boolean state = !manager.isTiming(); // toggle boolean state = !manager.isTiming(); // toggle
// Parse the boolean parameter // Parse the boolean parameter
if (args.length == 2) { if (args.length == 2) {
Boolean parsed = parseBoolean(toQueue(args, 2), "start"); Boolean parsed = parseBoolean(toQueue(args, 2), "start");
if (parsed != null) { if (parsed != null) {
state = parsed; state = parsed;
} else { } else {
@ -134,7 +134,7 @@ class CommandProtocol extends CommandBase {
sender.sendMessage(ChatColor.RED + "Too many parameters."); sender.sendMessage(ChatColor.RED + "Too many parameters.");
return; return;
} }
// Now change the state // Now change the state
if (state) { if (state) {
if (manager.startTiming()) if (manager.startTiming())
@ -150,21 +150,21 @@ class CommandProtocol extends CommandBase {
} }
} }
} }
private void saveTimings(TimedListenerManager manager) { private void saveTimings(TimedListenerManager manager) {
try { try {
File destination = new File(plugin.getDataFolder(), "Timings - " + System.currentTimeMillis() + ".txt"); File destination = new File(plugin.getDataFolder(), "Timings - " + System.currentTimeMillis() + ".txt");
TimingReportGenerator generator = new TimingReportGenerator(); TimingReportGenerator generator = new TimingReportGenerator();
// Print to a text file // Print to a text file
generator.saveTo(destination, manager); generator.saveTo(destination, manager);
manager.clear(); manager.clear();
} catch (IOException e) { } catch (IOException e) {
reporter.reportMinimal(plugin, "saveTimings()", e); reporter.reportMinimal(plugin, "saveTimings()", e);
} }
} }
/** /**
* Prevent further automatic updates until the next delay. * Prevent further automatic updates until the next delay.
*/ */
@ -174,7 +174,7 @@ class CommandProtocol extends CommandBase {
config.setAutoLastTime(currentTime); config.setAutoLastTime(currentTime);
config.saveAll(); config.saveAll();
} }
public void reloadConfiguration(CommandSender sender) { public void reloadConfiguration(CommandSender sender) {
plugin.reloadConfig(); plugin.reloadConfig();
sender.sendMessage(ChatColor.YELLOW + "Reloaded configuration!"); sender.sendMessage(ChatColor.YELLOW + "Reloaded configuration!");

Datei anzeigen

@ -2,16 +2,16 @@
* ProtocolLib - Bukkit server library that allows access to the Minecraft protocol. * ProtocolLib - Bukkit server library that allows access to the Minecraft protocol.
* Copyright (C) 2012 Kristian S. Stangeland * Copyright (C) 2012 Kristian S. Stangeland
* *
* This program is free software; you can redistribute it and/or modify it under the terms of the * This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of * GNU General Public License as published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version. * the License, or (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details. * See the GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License along with this program; * You should have received a copy of the GNU General Public License along with this program;
* if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA * if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA * 02111-1307 USA
*/ */
@ -46,9 +46,6 @@ import com.comphenix.protocol.injector.InternalManager;
import com.comphenix.protocol.injector.PacketFilterManager; import com.comphenix.protocol.injector.PacketFilterManager;
import com.comphenix.protocol.injector.PacketFilterManager.PlayerInjectHooks; import com.comphenix.protocol.injector.PacketFilterManager.PlayerInjectHooks;
import com.comphenix.protocol.metrics.Statistics; import com.comphenix.protocol.metrics.Statistics;
import com.comphenix.protocol.metrics.Updater;
import com.comphenix.protocol.metrics.Updater.UpdateResult;
import com.comphenix.protocol.metrics.Updater.UpdateType;
import com.comphenix.protocol.reflect.compiler.BackgroundCompiler; import com.comphenix.protocol.reflect.compiler.BackgroundCompiler;
import com.comphenix.protocol.utility.ChatExtensions; import com.comphenix.protocol.utility.ChatExtensions;
import com.comphenix.protocol.utility.EnhancerFactory; import com.comphenix.protocol.utility.EnhancerFactory;
@ -60,7 +57,7 @@ import com.google.common.util.concurrent.ListeningScheduledExecutorService;
/** /**
* The main entry point for ProtocolLib. * The main entry point for ProtocolLib.
* *
* @author Kristian * @author Kristian
*/ */
public class ProtocolLibrary extends JavaPlugin { public class ProtocolLibrary extends JavaPlugin {
@ -68,117 +65,117 @@ public class ProtocolLibrary extends JavaPlugin {
public static final ReportType REPORT_CANNOT_LOAD_CONFIG = new ReportType("Cannot load configuration"); public static final ReportType REPORT_CANNOT_LOAD_CONFIG = new ReportType("Cannot load configuration");
public static final ReportType REPORT_CANNOT_DELETE_CONFIG = new ReportType("Cannot delete old ProtocolLib configuration."); public static final ReportType REPORT_CANNOT_DELETE_CONFIG = new ReportType("Cannot delete old ProtocolLib configuration.");
public static final ReportType REPORT_CANNOT_PARSE_INJECTION_METHOD = new ReportType("Cannot parse injection method. Using default."); public static final ReportType REPORT_CANNOT_PARSE_INJECTION_METHOD = new ReportType("Cannot parse injection method. Using default.");
public static final ReportType REPORT_PLUGIN_LOAD_ERROR = new ReportType("Cannot load ProtocolLib."); public static final ReportType REPORT_PLUGIN_LOAD_ERROR = new ReportType("Cannot load ProtocolLib.");
public static final ReportType REPORT_PLUGIN_ENABLE_ERROR = new ReportType("Cannot enable ProtocolLib."); public static final ReportType REPORT_PLUGIN_ENABLE_ERROR = new ReportType("Cannot enable ProtocolLib.");
public static final ReportType REPORT_METRICS_IO_ERROR = new ReportType("Unable to enable metrics due to network problems."); public static final ReportType REPORT_METRICS_IO_ERROR = new ReportType("Unable to enable metrics due to network problems.");
public static final ReportType REPORT_METRICS_GENERIC_ERROR = new ReportType("Unable to enable metrics due to network problems."); public static final ReportType REPORT_METRICS_GENERIC_ERROR = new ReportType("Unable to enable metrics due to network problems.");
public static final ReportType REPORT_CANNOT_PARSE_MINECRAFT_VERSION = new ReportType("Unable to retrieve current Minecraft version. Assuming %s"); public static final ReportType REPORT_CANNOT_PARSE_MINECRAFT_VERSION = new ReportType("Unable to retrieve current Minecraft version. Assuming %s");
public static final ReportType REPORT_CANNOT_DETECT_CONFLICTING_PLUGINS = new ReportType("Unable to detect conflicting plugin versions."); public static final ReportType REPORT_CANNOT_DETECT_CONFLICTING_PLUGINS = new ReportType("Unable to detect conflicting plugin versions.");
public static final ReportType REPORT_CANNOT_REGISTER_COMMAND = new ReportType("Cannot register command %s: %s"); public static final ReportType REPORT_CANNOT_REGISTER_COMMAND = new ReportType("Cannot register command %s: %s");
public static final ReportType REPORT_CANNOT_CREATE_TIMEOUT_TASK = new ReportType("Unable to create packet timeout task."); public static final ReportType REPORT_CANNOT_CREATE_TIMEOUT_TASK = new ReportType("Unable to create packet timeout task.");
public static final ReportType REPORT_CANNOT_UPDATE_PLUGIN = new ReportType("Cannot perform automatic updates."); public static final ReportType REPORT_CANNOT_UPDATE_PLUGIN = new ReportType("Cannot perform automatic updates.");
/** /**
* The minimum version ProtocolLib has been tested with. * The minimum version ProtocolLib has been tested with.
*/ */
public static final String MINIMUM_MINECRAFT_VERSION = "1.0.0"; public static final String MINIMUM_MINECRAFT_VERSION = "1.0.0";
/** /**
* The maximum version ProtocolLib has been tested with, * The maximum version ProtocolLib has been tested with,
*/ */
public static final String MAXIMUM_MINECRAFT_VERSION = "1.7.4"; public static final String MAXIMUM_MINECRAFT_VERSION = "1.7.10";
/** /**
* The date (with ISO 8601 or YYYY-MM-DD) when the most recent version was released. * The date (with ISO 8601 or YYYY-MM-DD) when the most recent version was released.
*/ */
public static final String MINECRAFT_LAST_RELEASE_DATE = "2013-12-10"; public static final String MINECRAFT_LAST_RELEASE_DATE = "2013-12-10";
// Update information // Update information
static final String BUKKIT_DEV_SLUG = "protocollib"; // static final String BUKKIT_DEV_SLUG = "protocollib";
static final int BUKKIT_DEV_ID = 45564; // static final int BUKKIT_DEV_ID = 45564;
// Different commands // Different commands
private enum ProtocolCommand { private enum ProtocolCommand {
FILTER, FILTER,
PACKET, PACKET,
PROTOCOL PROTOCOL
} }
/** /**
* The number of milliseconds per second. * The number of milliseconds per second.
*/ */
static final long MILLI_PER_SECOND = 1000; static final long MILLI_PER_SECOND = 1000;
private static final String PERMISSION_INFO = "protocol.info"; private static final String PERMISSION_INFO = "protocol.info";
// There should only be one protocol manager, so we'll make it static // There should only be one protocol manager, so we'll make it static
private static InternalManager protocolManager; private static InternalManager protocolManager;
// Error reporter // Error reporter
private static ErrorReporter reporter = new BasicErrorReporter(); private static ErrorReporter reporter = new BasicErrorReporter();
// Strongly typed configuration // Strongly typed configuration
private static ProtocolConfig config; private static ProtocolConfig config;
// Metrics and statistisc // Metrics and statistics
private Statistics statistisc; private Statistics statistics;
// Executors // Executors
private static ListeningScheduledExecutorService executorAsync; private static ListeningScheduledExecutorService executorAsync;
private static ListeningScheduledExecutorService executorSync; private static ListeningScheduledExecutorService executorSync;
// Structure compiler // Structure compiler
private BackgroundCompiler backgroundCompiler; private BackgroundCompiler backgroundCompiler;
// Used to clean up server packets that have expired. But mostly required to simulate // Used to clean up server packets that have expired. But mostly required to simulate
// recieving client packets. // recieving client packets.
private int packetTask = -1; private int packetTask = -1;
private int tickCounter = 0; private int tickCounter = 0;
private static final int ASYNC_MANAGER_DELAY = 1; private static final int ASYNC_MANAGER_DELAY = 1;
// Used to unhook players after a delay // Used to unhook players after a delay
private DelayedSingleTask unhookTask; private DelayedSingleTask unhookTask;
// Settings/options // Settings/options
private int configExpectedMod = -1; private int configExpectedMod = -1;
// Updater // Updater
private Updater updater; // private Updater updater;
private static boolean UPDATES_DISABLED; // private static boolean UPDATES_DISABLED;
// Logger // Logger
private Logger logger; private Logger logger;
private Handler redirectHandler; private Handler redirectHandler;
// Commands // Commands
private CommandProtocol commandProtocol; private CommandProtocol commandProtocol;
private CommandPacket commandPacket; private CommandPacket commandPacket;
private CommandFilter commandFilter; private CommandFilter commandFilter;
// Whether or not disable is not needed // Whether or not disable is not needed
private boolean skipDisable; private boolean skipDisable;
@Override @Override
public void onLoad() { public void onLoad() {
// Load configuration // Load configuration
logger = getLoggerSafely(); logger = getLoggerSafely();
Application.registerPrimaryThread(); Application.registerPrimaryThread();
// Initialize enhancer factory // Initialize enhancer factory
EnhancerFactory.getInstance().setClassLoader(getClassLoader()); EnhancerFactory.getInstance().setClassLoader(getClassLoader());
// Initialize executors // Initialize executors
executorAsync = BukkitExecutors.newAsynchronous(this); executorAsync = BukkitExecutors.newAsynchronous(this);
executorSync = BukkitExecutors.newSynchronous(this); executorSync = BukkitExecutors.newSynchronous(this);
// Add global parameters // Add global parameters
DetailedErrorReporter detailedReporter = new DetailedErrorReporter(this); DetailedErrorReporter detailedReporter = new DetailedErrorReporter(this);
reporter = getFilteredReporter(detailedReporter); reporter = getFilteredReporter(detailedReporter);
try { try {
config = new ProtocolConfig(this); config = new ProtocolConfig(this);
} catch (Exception e) { } catch (Exception e) {
@ -191,7 +188,7 @@ public class ProtocolLibrary extends JavaPlugin {
reporter.reportWarning(this, Report.newBuilder(REPORT_CANNOT_DELETE_CONFIG)); reporter.reportWarning(this, Report.newBuilder(REPORT_CANNOT_DELETE_CONFIG));
} }
} }
// Print the state of the debug mode // Print the state of the debug mode
if (config.isDebug()) { if (config.isDebug()) {
logger.warning("Debug mode is enabled!"); logger.warning("Debug mode is enabled!");
@ -201,17 +198,18 @@ public class ProtocolLibrary extends JavaPlugin {
detailedReporter.setDetailedReporting(true); detailedReporter.setDetailedReporting(true);
logger.warning("Detailed error reporting enabled!"); logger.warning("Detailed error reporting enabled!");
} }
try { try {
// Check for other versions // Check for other versions
checkConflictingVersions(); checkConflictingVersions();
// Handle unexpected Minecraft versions // Handle unexpected Minecraft versions
MinecraftVersion version = verifyMinecraftVersion(); MinecraftVersion version = verifyMinecraftVersion();
// TODO: Redo the update mechanism for Spigot?
// Set updater - this will not perform any update automatically // Set updater - this will not perform any update automatically
updater = new Updater(this, BUKKIT_DEV_ID, getFile(), UpdateType.NO_DOWNLOAD, true); // updater = new Updater(this, BUKKIT_DEV_ID, getFile(), UpdateType.NO_DOWNLOAD, true);
unhookTask = new DelayedSingleTask(this); unhookTask = new DelayedSingleTask(this);
protocolManager = PacketFilterManager.newBuilder(). protocolManager = PacketFilterManager.newBuilder().
classLoader(getClassLoader()). classLoader(getClassLoader()).
@ -220,11 +218,11 @@ public class ProtocolLibrary extends JavaPlugin {
minecraftVersion(version). minecraftVersion(version).
unhookTask(unhookTask). unhookTask(unhookTask).
reporter(reporter). reporter(reporter).
build(); build();
// Setup error reporter // Setup error reporter
detailedReporter.addGlobalParameter("manager", protocolManager); detailedReporter.addGlobalParameter("manager", protocolManager);
// Update injection hook // Update injection hook
try { try {
PlayerInjectHooks hook = config.getInjectionMethod(); PlayerInjectHooks hook = config.getInjectionMethod();
@ -237,11 +235,11 @@ public class ProtocolLibrary extends JavaPlugin {
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
reporter.reportWarning(config, Report.newBuilder(REPORT_CANNOT_PARSE_INJECTION_METHOD).error(e)); reporter.reportWarning(config, Report.newBuilder(REPORT_CANNOT_PARSE_INJECTION_METHOD).error(e));
} }
// Send logging information to player listeners too // Send logging information to player listeners too
initializeCommands(); initializeCommands();
setupBroadcastUsers(PERMISSION_INFO); setupBroadcastUsers(PERMISSION_INFO);
} catch (OutOfMemoryError e) { } catch (OutOfMemoryError e) {
throw e; throw e;
} catch (ThreadDeath e) { } catch (ThreadDeath e) {
@ -260,9 +258,9 @@ public class ProtocolLibrary extends JavaPlugin {
for (ProtocolCommand command : ProtocolCommand.values()) { for (ProtocolCommand command : ProtocolCommand.values()) {
try { try {
switch (command) { switch (command) {
case PROTOCOL: case PROTOCOL:
commandProtocol = new CommandProtocol(reporter, this, updater, config); break; commandProtocol = new CommandProtocol(reporter, this, null, config); break;
case FILTER: case FILTER:
commandFilter = new CommandFilter(reporter, this, config); break; commandFilter = new CommandFilter(reporter, this, config); break;
case PACKET: case PACKET:
commandPacket = new CommandPacket(reporter, this, logger, commandFilter, protocolManager); break; commandPacket = new CommandPacket(reporter, this, logger, commandFilter, protocolManager); break;
@ -277,32 +275,32 @@ public class ProtocolLibrary extends JavaPlugin {
} }
} }
} }
/** /**
* Retrieve a error reporter that may be filtered by the configuration. * Retrieve a error reporter that may be filtered by the configuration.
* @return The new default error reporter. * @return The new default error reporter.
*/ */
private ErrorReporter getFilteredReporter(ErrorReporter reporter) { private ErrorReporter getFilteredReporter(ErrorReporter reporter) {
return new DelegatedErrorReporter(reporter) { return new DelegatedErrorReporter(reporter) {
private int lastModCount = -1; private int lastModCount = -1;
private Set<String> reports = Sets.newHashSet(); private Set<String> reports = Sets.newHashSet();
@Override @Override
protected Report filterReport(Object sender, Report report, boolean detailed) { protected Report filterReport(Object sender, Report report, boolean detailed) {
try { try {
String canonicalName = ReportType.getReportName(sender, report.getType()); String canonicalName = ReportType.getReportName(sender, report.getType());
String reportName = Iterables.getLast(Splitter.on("#").split(canonicalName)).toUpperCase(); String reportName = Iterables.getLast(Splitter.on("#").split(canonicalName)).toUpperCase();
if (config != null && config.getModificationCount() != lastModCount) { if (config != null && config.getModificationCount() != lastModCount) {
// Update our cached set again // Update our cached set again
reports = Sets.newHashSet(config.getSuppressedReports()); reports = Sets.newHashSet(config.getSuppressedReports());
lastModCount = config.getModificationCount(); lastModCount = config.getModificationCount();
} }
// Cancel reports either on the full canonical name, or just the report name // Cancel reports either on the full canonical name, or just the report name
if (reports.contains(canonicalName) || reports.contains(reportName)) if (reports.contains(canonicalName) || reports.contains(reportName))
return null; return null;
} catch (Exception e) { } catch (Exception e) {
// Only report this with a minor message // Only report this with a minor message
logger.warning("Error filtering reports: " + e.toString()); logger.warning("Error filtering reports: " + e.toString());
@ -312,26 +310,26 @@ public class ProtocolLibrary extends JavaPlugin {
} }
}; };
} }
private boolean deleteConfig() { private boolean deleteConfig() {
return config.getFile().delete(); return config.getFile().delete();
} }
@Override @Override
public void reloadConfig() { public void reloadConfig() {
super.reloadConfig(); super.reloadConfig();
// Reload configuration // Reload configuration
if (config != null) { if (config != null) {
config.reloadConfig(); config.reloadConfig();
} }
} }
private void setupBroadcastUsers(final String permission) { private void setupBroadcastUsers(final String permission) {
// Guard against multiple calls // Guard against multiple calls
if (redirectHandler != null) if (redirectHandler != null)
return; return;
// Broadcast information to every user too // Broadcast information to every user too
redirectHandler = new Handler() { redirectHandler = new Handler() {
@Override @Override
@ -341,12 +339,12 @@ public class ProtocolLibrary extends JavaPlugin {
commandPacket.broadcastMessageSilently(record.getMessage(), permission); commandPacket.broadcastMessageSilently(record.getMessage(), permission);
} }
} }
@Override @Override
public void flush() { public void flush() {
// Not needed. // Not needed.
} }
@Override @Override
public void close() throws SecurityException { public void close() throws SecurityException {
// Do nothing. // Do nothing.
@ -355,24 +353,24 @@ public class ProtocolLibrary extends JavaPlugin {
logger.addHandler(redirectHandler); logger.addHandler(redirectHandler);
} }
@Override @Override
public void onEnable() { public void onEnable() {
try { try {
Server server = getServer(); Server server = getServer();
PluginManager manager = server.getPluginManager(); PluginManager manager = server.getPluginManager();
// Don't do anything else! // Don't do anything else!
if (manager == null) if (manager == null)
return; return;
// Silly plugin reloaders! // Silly plugin reloaders!
if (protocolManager == null) { if (protocolManager == null) {
Logger directLogging = Logger.getLogger("Minecraft"); Logger directLogging = Logger.getLogger("Minecraft");
String[] message = new String[] { String[] message = new String[] {
" PROTOCOLLIB DOES NOT SUPPORT PLUGIN RELOADERS. ", " PROTOCOLLIB DOES NOT SUPPORT PLUGIN RELOADERS. ",
" PLEASE USE THE BUILT-IN RELOAD COMMAND. ", " PLEASE USE THE BUILT-IN RELOAD COMMAND. ",
}; };
// Print as severe // Print as severe
for (String line : ChatExtensions.toFlowerBox(message, "*", 3, 1)) { for (String line : ChatExtensions.toFlowerBox(message, "*", 3, 1)) {
directLogging.severe(line); directLogging.severe(line);
@ -380,29 +378,29 @@ public class ProtocolLibrary extends JavaPlugin {
disablePlugin(); disablePlugin();
return; return;
} }
// Initialize background compiler // Initialize background compiler
if (backgroundCompiler == null && config.isBackgroundCompilerEnabled()) { if (backgroundCompiler == null && config.isBackgroundCompilerEnabled()) {
backgroundCompiler = new BackgroundCompiler(getClassLoader(), reporter); backgroundCompiler = new BackgroundCompiler(getClassLoader(), reporter);
BackgroundCompiler.setInstance(backgroundCompiler); BackgroundCompiler.setInstance(backgroundCompiler);
logger.info("Started structure compiler thread."); logger.info("Started structure compiler thread.");
} else { } else {
logger.info("Structure compiler thread has been disabled."); logger.info("Structure compiler thread has been disabled.");
} }
// Set up command handlers // Set up command handlers
registerCommand(CommandProtocol.NAME, commandProtocol); registerCommand(CommandProtocol.NAME, commandProtocol);
registerCommand(CommandPacket.NAME, commandPacket); registerCommand(CommandPacket.NAME, commandPacket);
registerCommand(CommandFilter.NAME, commandFilter); registerCommand(CommandFilter.NAME, commandFilter);
// Player login and logout events // Player login and logout events
protocolManager.registerEvents(manager, this); protocolManager.registerEvents(manager, this);
// Worker that ensures that async packets are eventually sent // Worker that ensures that async packets are eventually sent
// It also performs the update check. // It also performs the update check.
createPacketTask(server); createPacketTask(server);
} catch (OutOfMemoryError e) { } catch (OutOfMemoryError e) {
throw e; throw e;
} catch (ThreadDeath e) { } catch (ThreadDeath e) {
@ -412,28 +410,28 @@ public class ProtocolLibrary extends JavaPlugin {
disablePlugin(); disablePlugin();
return; return;
} }
// Try to enable statistics // Try to enable statistics
try { try {
if (config.isMetricsEnabled()) { if (config.isMetricsEnabled()) {
statistisc = new Statistics(this); statistics = new Statistics(this);
} }
} catch (OutOfMemoryError e) { } catch (OutOfMemoryError e) {
throw e; throw e;
} catch (ThreadDeath e) { } catch (ThreadDeath e) {
throw e; throw e;
} catch (IOException e) { } catch (IOException e) {
reporter.reportDetailed(this, Report.newBuilder(REPORT_METRICS_IO_ERROR).error(e).callerParam(statistisc)); reporter.reportDetailed(this, Report.newBuilder(REPORT_METRICS_IO_ERROR).error(e).callerParam(statistics));
} catch (Throwable e) { } catch (Throwable e) {
reporter.reportDetailed(this, Report.newBuilder(REPORT_METRICS_GENERIC_ERROR).error(e).callerParam(statistisc)); reporter.reportDetailed(this, Report.newBuilder(REPORT_METRICS_GENERIC_ERROR).error(e).callerParam(statistics));
} }
} }
// Used to check Minecraft version // Used to check Minecraft version
private MinecraftVersion verifyMinecraftVersion() { private MinecraftVersion verifyMinecraftVersion() {
MinecraftVersion minimum = new MinecraftVersion(MINIMUM_MINECRAFT_VERSION); MinecraftVersion minimum = new MinecraftVersion(MINIMUM_MINECRAFT_VERSION);
MinecraftVersion maximum = new MinecraftVersion(MAXIMUM_MINECRAFT_VERSION); MinecraftVersion maximum = new MinecraftVersion(MAXIMUM_MINECRAFT_VERSION);
try { try {
MinecraftVersion current = new MinecraftVersion(getServer()); MinecraftVersion current = new MinecraftVersion(getServer());
@ -448,9 +446,9 @@ public class ProtocolLibrary extends JavaPlugin {
return current; return current;
} catch (Exception e) { } catch (Exception e) {
reporter.reportWarning(this, reporter.reportWarning(this,
Report.newBuilder(REPORT_CANNOT_PARSE_MINECRAFT_VERSION).error(e).messageParam(maximum)); Report.newBuilder(REPORT_CANNOT_PARSE_MINECRAFT_VERSION).error(e).messageParam(maximum));
// Unknown version - just assume it is the latest // Unknown version - just assume it is the latest
return maximum; return maximum;
} }
@ -463,15 +461,15 @@ public class ProtocolLibrary extends JavaPlugin {
// Skip the file that contains this current instance however // Skip the file that contains this current instance however
File loadedFile = getFile(); File loadedFile = getFile();
try { try {
// Scan the plugin folder for newer versions of ProtocolLib // Scan the plugin folder for newer versions of ProtocolLib
File pluginFolder = new File("plugins/"); File pluginFolder = new File("plugins/");
for (File candidate : pluginFolder.listFiles()) { for (File candidate : pluginFolder.listFiles()) {
if (candidate.isFile() && !candidate.equals(loadedFile)) { if (candidate.isFile() && !candidate.equals(loadedFile)) {
Matcher match = ourPlugin.matcher(candidate.getName()); Matcher match = ourPlugin.matcher(candidate.getName());
if (match.matches()) { if (match.matches()) {
MinecraftVersion version = new MinecraftVersion(match.group(1)); MinecraftVersion version = new MinecraftVersion(match.group(1));
@ -488,73 +486,73 @@ public class ProtocolLibrary extends JavaPlugin {
} catch (Exception e) { } catch (Exception e) {
reporter.reportWarning(this, Report.newBuilder(REPORT_CANNOT_DETECT_CONFLICTING_PLUGINS).error(e)); reporter.reportWarning(this, Report.newBuilder(REPORT_CANNOT_DETECT_CONFLICTING_PLUGINS).error(e));
} }
// See if the newest version is actually higher // See if the newest version is actually higher
if (newestVersion != null && currentVersion.compareTo(newestVersion) < 0) { if (newestVersion != null && currentVersion.compareTo(newestVersion) < 0) {
// We don't need to set internal classes or instances to NULL - that would break the other loaded plugin // We don't need to set internal classes or instances to NULL - that would break the other loaded plugin
skipDisable = true; skipDisable = true;
throw new IllegalStateException( throw new IllegalStateException(
String.format("Detected a newer version of ProtocolLib (%s) in plugin folder than the current (%s). Disabling.", String.format("Detected a newer version of ProtocolLib (%s) in plugin folder than the current (%s). Disabling.",
newestVersion.getVersion(), currentVersion.getVersion()) newestVersion.getVersion(), currentVersion.getVersion())
); );
} }
} }
private void registerCommand(String name, CommandExecutor executor) { private void registerCommand(String name, CommandExecutor executor) {
try { try {
// Ignore these - they must have printed an error already // Ignore these - they must have printed an error already
if (executor == null) if (executor == null)
return; return;
PluginCommand command = getCommand(name); PluginCommand command = getCommand(name);
// Try to load the command // Try to load the command
if (command != null) if (command != null)
command.setExecutor(executor); command.setExecutor(executor);
else else
throw new RuntimeException("plugin.yml might be corrupt."); throw new RuntimeException("plugin.yml might be corrupt.");
} catch (RuntimeException e) { } catch (RuntimeException e) {
reporter.reportWarning(this, reporter.reportWarning(this,
Report.newBuilder(REPORT_CANNOT_REGISTER_COMMAND).messageParam(name, e.getMessage()).error(e) Report.newBuilder(REPORT_CANNOT_REGISTER_COMMAND).messageParam(name, e.getMessage()).error(e)
); );
} }
} }
/** /**
* Disable the current plugin. * Disable the current plugin.
*/ */
private void disablePlugin() { private void disablePlugin() {
getServer().getPluginManager().disablePlugin(this); getServer().getPluginManager().disablePlugin(this);
} }
private void createPacketTask(Server server) { private void createPacketTask(Server server) {
try { try {
if (packetTask >= 0) if (packetTask >= 0)
throw new IllegalStateException("Packet task has already been created"); throw new IllegalStateException("Packet task has already been created");
// Attempt to create task // Attempt to create task
packetTask = server.getScheduler().scheduleSyncRepeatingTask(this, new Runnable() { packetTask = server.getScheduler().scheduleSyncRepeatingTask(this, new Runnable() {
@Override @Override
public void run() { public void run() {
AsyncFilterManager manager = (AsyncFilterManager) protocolManager.getAsynchronousManager(); AsyncFilterManager manager = (AsyncFilterManager) protocolManager.getAsynchronousManager();
// We KNOW we're on the main thread at the moment // We KNOW we're on the main thread at the moment
manager.sendProcessedPackets(tickCounter++, true); manager.sendProcessedPackets(tickCounter++, true);
// House keeping // House keeping
updateConfiguration(); updateConfiguration();
// Check for updates too // Check for updates too
if (!UPDATES_DISABLED && (tickCounter % 20) == 0) { // if (!UPDATES_DISABLED && (tickCounter % 20) == 0) {
checkUpdates(); // checkUpdates();
} // }
} }
}, ASYNC_MANAGER_DELAY, ASYNC_MANAGER_DELAY); }, ASYNC_MANAGER_DELAY, ASYNC_MANAGER_DELAY);
} catch (OutOfMemoryError e) { } catch (OutOfMemoryError e) {
throw e; throw e;
} catch (ThreadDeath e) { } catch (ThreadDeath e) {
throw e; throw e;
} catch (Throwable e) { } catch (Throwable e) {
@ -563,89 +561,89 @@ public class ProtocolLibrary extends JavaPlugin {
} }
} }
} }
private void updateConfiguration() { private void updateConfiguration() {
if (config != null && config.getModificationCount() != configExpectedMod) { if (config != null && config.getModificationCount() != configExpectedMod) {
configExpectedMod = config.getModificationCount(); configExpectedMod = config.getModificationCount();
// Update the debug flag // Update the debug flag
protocolManager.setDebug(config.isDebug()); protocolManager.setDebug(config.isDebug());
} }
} }
private void checkUpdates() {
// Ignore milliseconds - it's pointless
long currentTime = System.currentTimeMillis() / MILLI_PER_SECOND;
try {
long updateTime = config.getAutoLastTime() + config.getAutoDelay();
// Should we update? // private void checkUpdates() {
if (currentTime > updateTime && !updater.isChecking()) { // // Ignore milliseconds - it's pointless
// Initiate the update as if it came from the console // long currentTime = System.currentTimeMillis() / MILLI_PER_SECOND;
if (config.isAutoDownload()) //
commandProtocol.updateVersion(getServer().getConsoleSender()); // try {
else if (config.isAutoNotify()) // long updateTime = config.getAutoLastTime() + config.getAutoDelay();
commandProtocol.checkVersion(getServer().getConsoleSender()); //
else // // Should we update?
commandProtocol.updateFinished(); // if (currentTime > updateTime && !updater.isChecking()) {
} // // Initiate the update as if it came from the console
} catch (Exception e) { // if (config.isAutoDownload())
reporter.reportDetailed(this, Report.newBuilder(REPORT_CANNOT_UPDATE_PLUGIN).error(e)); // commandProtocol.updateVersion(getServer().getConsoleSender());
UPDATES_DISABLED = true; // else if (config.isAutoNotify())
} // commandProtocol.checkVersion(getServer().getConsoleSender());
} // else
// commandProtocol.updateFinished();
// }
// } catch (Exception e) {
// reporter.reportDetailed(this, Report.newBuilder(REPORT_CANNOT_UPDATE_PLUGIN).error(e));
// UPDATES_DISABLED = true;
// }
// }
@Override @Override
public void onDisable() { public void onDisable() {
if (skipDisable) { if (skipDisable) {
return; return;
} }
// Bukkit will shut down tasks on our executors // Bukkit will shut down tasks on our executors
// ... // ...
// Disable compiler // Disable compiler
if (backgroundCompiler != null) { if (backgroundCompiler != null) {
backgroundCompiler.shutdownAll(); backgroundCompiler.shutdownAll();
backgroundCompiler = null; backgroundCompiler = null;
BackgroundCompiler.setInstance(null); BackgroundCompiler.setInstance(null);
} }
// Clean up // Clean up
if (packetTask >= 0) { if (packetTask >= 0) {
getServer().getScheduler().cancelTask(packetTask); getServer().getScheduler().cancelTask(packetTask);
packetTask = -1; packetTask = -1;
} }
// And redirect handler too // And redirect handler too
if (redirectHandler != null) { if (redirectHandler != null) {
logger.removeHandler(redirectHandler); logger.removeHandler(redirectHandler);
} }
if (protocolManager != null) if (protocolManager != null)
protocolManager.close(); protocolManager.close();
else else
return; // Plugin reloaders! return; // Plugin reloaders!
if (unhookTask != null) if (unhookTask != null)
unhookTask.close(); unhookTask.close();
protocolManager = null; protocolManager = null;
statistisc = null; statistics = null;
// To clean up global parameters // To clean up global parameters
reporter = new BasicErrorReporter(); reporter = new BasicErrorReporter();
// Leaky ClassLoader begone! // Leaky ClassLoader begone!
if (updater == null || updater.getResult() != UpdateResult.SUCCESS) { // if (updater == null || updater.getResult() != UpdateResult.SUCCESS) {
CleanupStaticMembers cleanup = new CleanupStaticMembers(getClassLoader(), reporter); // CleanupStaticMembers cleanup = new CleanupStaticMembers(getClassLoader(), reporter);
cleanup.resetAll(); // cleanup.resetAll();
} // }
} }
// Get the Bukkit logger first, before we try to create our own // Get the Bukkit logger first, before we try to create our own
private Logger getLoggerSafely() { private Logger getLoggerSafely() {
Logger log = null; Logger log = null;
try { try {
log = getLogger(); log = getLogger();
} catch (OutOfMemoryError e) { } catch (OutOfMemoryError e) {
@ -661,7 +659,7 @@ public class ProtocolLibrary extends JavaPlugin {
log = Logger.getLogger("Minecraft"); log = Logger.getLogger("Minecraft");
return log; return log;
} }
/** /**
* Retrieve the current error reporter. * Retrieve the current error reporter.
* <p> * <p>
@ -671,7 +669,7 @@ public class ProtocolLibrary extends JavaPlugin {
public static ErrorReporter getErrorReporter() { public static ErrorReporter getErrorReporter() {
return reporter; return reporter;
} }
/** /**
* Retrieve the current strongly typed configuration. * Retrieve the current strongly typed configuration.
* @return The configuration, or NULL if ProtocolLib hasn't loaded yet. * @return The configuration, or NULL if ProtocolLib hasn't loaded yet.
@ -679,7 +677,7 @@ public class ProtocolLibrary extends JavaPlugin {
public static ProtocolConfig getConfiguration() { public static ProtocolConfig getConfiguration() {
return config; return config;
} }
/** /**
* Retrieves the packet protocol manager. * Retrieves the packet protocol manager.
* @return Packet protocol manager, or NULL if it has been disabled. * @return Packet protocol manager, or NULL if it has been disabled.
@ -687,7 +685,7 @@ public class ProtocolLibrary extends JavaPlugin {
public static ProtocolManager getProtocolManager() { public static ProtocolManager getProtocolManager() {
return protocolManager; return protocolManager;
} }
/** /**
* Retrieve the metrics instance used to measure users of this library. * Retrieve the metrics instance used to measure users of this library.
* <p> * <p>
@ -696,9 +694,9 @@ public class ProtocolLibrary extends JavaPlugin {
* @return Metrics instance container. * @return Metrics instance container.
*/ */
public Statistics getStatistics() { public Statistics getStatistics() {
return statistisc; return statistics;
} }
/** /**
* Retrieve an executor service for performing asynchronous tasks on the behalf of ProtocolLib. * Retrieve an executor service for performing asynchronous tasks on the behalf of ProtocolLib.
* <p> * <p>
@ -708,7 +706,7 @@ public class ProtocolLibrary extends JavaPlugin {
public static ListeningScheduledExecutorService getExecutorAsync() { public static ListeningScheduledExecutorService getExecutorAsync() {
return executorAsync; return executorAsync;
} }
/** /**
* Retrieve an executor service for performing synchronous tasks (main thread) on the behalf of ProtocolLib. * Retrieve an executor service for performing synchronous tasks (main thread) on the behalf of ProtocolLib.
* <p> * <p>