Made some changes

- Made command registration for other plugins more flexible
- Using logger instead of sysout
- Started moving plugin updater to the core
This commit is contained in:
Norbi Peti 2016-08-14 14:41:54 +02:00
parent 8e091beb33
commit 6d883ddbef
9 changed files with 65 additions and 66 deletions

View file

@ -1,6 +1,6 @@
package buttondevteam.thebuttonmcchat; package buttondevteam.thebuttonmcchat;
import java.util.ArrayList; import java.io.Serializable;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
@ -9,7 +9,8 @@ import org.bukkit.Bukkit;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
public class ChatPlayer { public class ChatPlayer implements Serializable {
private static final long serialVersionUID = 208589136914849018L;
public String PlayerName; public String PlayerName;
public String UserName; public String UserName;
public List<String> UserNames; public List<String> UserNames;

View file

@ -106,7 +106,8 @@ public class ChatProcessing {
.add(new ChatFormatter(Pattern.compile(sb.toString()), ChatFormatter.Color.Aqua, (String match) -> { .add(new ChatFormatter(Pattern.compile(sb.toString()), ChatFormatter.Color.Aqua, (String match) -> {
Player p = Bukkit.getPlayer(match); Player p = Bukkit.getPlayer(match);
if (p == null) { if (p == null) {
System.out.println("Error: Can't find player " + match + " but it was reported as online."); PluginMain.Instance.getLogger()
.warning("Error: Can't find player " + match + " but it was reported as online.");
return false; return false;
} }
ChatPlayer mpp = ChatPlayer.GetFromPlayer(p); ChatPlayer mpp = ChatPlayer.GetFromPlayer(p);
@ -139,7 +140,7 @@ public class ChatProcessing {
return false; // TODO return false; // TODO
Player p = Bukkit.getPlayer(PlayerListener.nicknames.get(n)); Player p = Bukkit.getPlayer(PlayerListener.nicknames.get(n));
if (p == null) { if (p == null) {
System.out.println( PluginMain.Instance.getLogger().warning(
"Error: Can't find player " + match + " but it was reported as online."); "Error: Can't find player " + match + " but it was reported as online.");
return false; return false;
} }

View file

@ -243,8 +243,9 @@ public class PlayerListener implements Listener {
ChatPlayer player = new ChatPlayer(); ChatPlayer player = new ChatPlayer();
player.UUID = p.UUID; player.UUID = p.UUID;
player.SetFlair(ChatPlayer.FlairTimeNone); player.SetFlair(ChatPlayer.FlairTimeNone);
player.FlairState = FlairStates.NoComment; //TODO: NullPointerException player.FlairState = FlairStates.NoComment; // TODO: NullPointerException
player.UserNames = new ArrayList<>(); //TODO: Move some code here from join? player.UserNames = new ArrayList<>(); // TODO: Move some code here from
// join?
ChatPlayer.OnlinePlayers.put(p.UUID, player); ChatPlayer.OnlinePlayers.put(p.UUID, player);
} }
@ -603,7 +604,7 @@ public class PlayerListener implements Listener {
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public void onVotifierEvent(VotifierEvent event) { public void onVotifierEvent(VotifierEvent event) {
Vote vote = event.getVote(); Vote vote = event.getVote();
System.out.println("Vote: " + vote); PluginMain.Instance.getLogger().info("Vote: " + vote);
org.bukkit.OfflinePlayer op = Bukkit.getOfflinePlayer(vote.getUsername()); org.bukkit.OfflinePlayer op = Bukkit.getOfflinePlayer(vote.getUsername());
Player p = Bukkit.getPlayer(vote.getUsername()); Player p = Bukkit.getPlayer(vote.getUsername());
if (op != null) { if (op != null) {
@ -676,7 +677,8 @@ public class PlayerListener implements Listener {
if (block.getType() == Material.ENDER_CHEST) { if (block.getType() == Material.ENDER_CHEST) {
e.setCancelled(true); e.setCancelled(true);
e.getPlayer().sendMessage("§You are not allowed to use enderchests here."); e.getPlayer().sendMessage("§You are not allowed to use enderchests here.");
System.out.println(e.getPlayer().getName() + " tried to use an enderchest in twohundred."); PluginMain.Instance.getLogger()
.warning(e.getPlayer().getName() + " tried to use an enderchest in twohundred.");
} }
} }
} }

View file

@ -55,7 +55,7 @@ public class PluginMain extends JavaPlugin { // Translated to Java: 2015.07.15.
@Override @Override
public void onEnable() { public void onEnable() {
try { try {
System.out.println("Extracting necessary libraries..."); PluginMain.Instance.getLogger().info("Extracting necessary libraries...");
final File[] libs = new File[] { new File(getDataFolder(), "htmlcleaner-2.16.jar"), final File[] libs = new File[] { new File(getDataFolder(), "htmlcleaner-2.16.jar"),
new File(getDataFolder(), "reflections-0.9.10.jar"), new File(getDataFolder(), "reflections-0.9.10.jar"),
new File(getDataFolder(), "javassist-3.19.0-GA.jar") }; new File(getDataFolder(), "javassist-3.19.0-GA.jar") };
@ -77,7 +77,7 @@ public class PluginMain extends JavaPlugin { // Translated to Java: 2015.07.15.
} }
getServer().getPluginManager().registerEvents(new PlayerListener(), this); getServer().getPluginManager().registerEvents(new PlayerListener(), this);
CommandCaller.RegisterCommands(this); CommandCaller.RegisterChatCommands(this);
Instance = this; Instance = this;
Console = this.getServer().getConsoleSender(); Console = this.getServer().getConsoleSender();
LoadFiles(false); LoadFiles(false);
@ -108,7 +108,7 @@ public class PluginMain extends JavaPlugin { // Translated to Java: 2015.07.15.
Runnable r = new Runnable() { Runnable r = new Runnable() {
public void run() { public void run() {
ThreadMethod(); FlairGetterThreadMethod();
} }
}; };
Thread t = new Thread(r); Thread t = new Thread(r);
@ -131,7 +131,7 @@ public class PluginMain extends JavaPlugin { // Translated to Java: 2015.07.15.
stop = true; stop = true;
} }
private void ThreadMethod() { private void FlairGetterThreadMethod() {
while (!stop) { while (!stop) {
try { try {
String body = DownloadString(FlairThreadURL + ".json?limit=1000"); String body = DownloadString(FlairThreadURL + ".json?limit=1000");
@ -141,11 +141,11 @@ public class PluginMain extends JavaPlugin { // Translated to Java: 2015.07.15.
String author = item.getJSONObject("data").getString("author"); String author = item.getJSONObject("data").getString("author");
String ign = item.getJSONObject("data").getString("body"); String ign = item.getJSONObject("data").getString("body");
int start = ign.indexOf("IGN:") + "IGN:".length(); int start = ign.indexOf("IGN:") + "IGN:".length();
if (start == -1 + "IGN:".length()) // +length: 2015.08.10. if (start == -1 + "IGN:".length())
continue; // 2015.08.09. continue;
int end = ign.indexOf(' ', start); int end = ign.indexOf(' ', start);
if (end == -1 || end == start) if (end == -1 || end == start)
end = ign.indexOf('\n', start); // 2015.07.15. end = ign.indexOf('\n', start);
if (end == -1 || end == start) if (end == -1 || end == start)
ign = ign.substring(start); ign = ign.substring(start);
else else
@ -174,8 +174,7 @@ public class PluginMain extends JavaPlugin { // Translated to Java: 2015.07.15.
Thread.currentThread().interrupt(); Thread.currentThread().interrupt();
} }
} catch (Exception e) { } catch (Exception e) {
// System.out.println("Error!\n" + e); LastException = e;
LastException = e; // 2015.08.09.
} }
} }
} }
@ -196,7 +195,7 @@ public class PluginMain extends JavaPlugin { // Translated to Java: 2015.07.15.
SetFlair(mp, flair, flairclass, mp.UserName); SetFlair(mp, flair, flairclass, mp.UserName);
} }
public static Exception LastException; // 2015.08.09. public static Exception LastException;
public String DownloadString(String urlstr) throws MalformedURLException, IOException { public String DownloadString(String urlstr) throws MalformedURLException, IOException {
URL url = new URL(urlstr); URL url = new URL(urlstr);
@ -295,11 +294,11 @@ public class PluginMain extends JavaPlugin { // Translated to Java: 2015.07.15.
public static void LoadFiles(boolean reload) { public static void LoadFiles(boolean reload) {
if (reload) { if (reload) {
System.out.println("TBMC chat plugin cleanup for reloading..."); PluginMain.Instance.getLogger().info("Cleanup for reloading...");
ChatPlayer.OnlinePlayers.clear(); ChatPlayer.OnlinePlayers.clear();
AnnounceMessages.clear(); AnnounceMessages.clear();
} }
System.out.println("Loading files for TBMC chat plugin..."); PluginMain.Instance.getLogger().info("Loading files...");
try { try {
File file = new File("thebuttonmc.yml"); // TODO File file = new File("thebuttonmc.yml"); // TODO
if (file.exists()) { if (file.exists()) {
@ -312,18 +311,18 @@ public class PluginMain extends JavaPlugin { // Translated to Java: 2015.07.15.
AnnounceMessages.addAll(yc.getStringList("announcements")); AnnounceMessages.addAll(yc.getStringList("announcements"));
PlayerListener.AlphaDeaths = yc.getInt("alphadeaths"); PlayerListener.AlphaDeaths = yc.getInt("alphadeaths");
} }
System.out.println("TBMC plugin loaded files!"); PluginMain.Instance.getLogger().info("Loaded files!");
} catch (IOException e) { } catch (IOException e) {
System.out.println("Error!\n" + e); PluginMain.Instance.getLogger().warning("Error!\n" + e);
LastException = e; LastException = e;
} catch (InvalidConfigurationException e) { } catch (InvalidConfigurationException e) {
System.out.println("Error!\n" + e); PluginMain.Instance.getLogger().warning("Error!\n" + e);
LastException = e; LastException = e;
} }
} }
public static void SaveFiles() { public static void SaveFiles() {
System.out.println("Saving files for The Button Minecraft plugin..."); PluginMain.Instance.getLogger().info("Saving files...");
try { try {
File file = new File("thebuttonmc.yml"); File file = new File("thebuttonmc.yml");
YamlConfiguration yc = new YamlConfiguration(); YamlConfiguration yc = new YamlConfiguration();
@ -333,9 +332,9 @@ public class PluginMain extends JavaPlugin { // Translated to Java: 2015.07.15.
yc.set("announcements", AnnounceMessages); yc.set("announcements", AnnounceMessages);
yc.set("alphadeaths", PlayerListener.AlphaDeaths); yc.set("alphadeaths", PlayerListener.AlphaDeaths);
yc.save(file); yc.save(file);
System.out.println("The Button Minecraft plugin saved files!"); PluginMain.Instance.getLogger().info("Saved files!");
} catch (IOException e) { } catch (IOException e) {
System.out.println("Error!\n" + e); PluginMain.Instance.getLogger().warning("Error!\n" + e);
LastException = e; LastException = e;
} }
} }

View file

@ -10,20 +10,24 @@ public class TBMCChatAPI {
/** /**
* <p> * <p>
* This method adds a command, adding it to help for example. * This method adds a plugin's commands to help and sets their executor.
* </p> * </p>
* <p> * <p>
* The command must be registered in the caller plugin's plugin.yml. * The <u>command must be registered</u> in the caller plugin's plugin.yml.
* Otherwise the plugin will output a messsage to console. * Otherwise the plugin will output a messsage to console.
* </p> * </p>
* *
* @param plugin * @param plugin
* The caller plugin * The caller plugin
* @param cmd * @param acmdclass
* The command to add * A command's class to get the package name for commands. The
* provided class's package and subpackages are scanned for
* commands.
*/ */
public void AddCommand(JavaPlugin plugin, TBMCCommandBase cmd) { public void AddCommands(JavaPlugin plugin, Class<? extends TBMCCommandBase> acmdclass) {
CommandCaller.AddCommand(plugin, cmd); CommandCaller.AddCommands(plugin, acmdclass); // TODO: Make it scan for
// all "buttondevteam"
// packages
} }
/** /**

View file

@ -33,19 +33,19 @@ public class CommandCaller implements CommandExecutor {
private static CommandCaller instance; private static CommandCaller instance;
public static void RegisterCommands(PluginMain plugin) { public static void RegisterChatCommands(PluginMain plugin) {
if (instance != null) { AddCommands(plugin, TBMCCommandBase.class);
new Exception("Only one instance of CommandCaller is allowed").printStackTrace(); }
return;
}
System.out.println("Registering commands...");
// TODO: Move plugin updater to the core
public static void AddCommands(JavaPlugin plugin, Class<? extends TBMCCommandBase> acmdclass) {
plugin.getLogger().info("Registering commands for " + plugin.getName());
if (instance == null) if (instance == null)
instance = new CommandCaller(); instance = new CommandCaller();
Reflections rf = new Reflections( Reflections rf = new Reflections(
new ConfigurationBuilder().setUrls(ClasspathHelper.forClassLoader(plugin.getClass().getClassLoader())) new ConfigurationBuilder().setUrls(ClasspathHelper.forClassLoader(plugin.getClass().getClassLoader()))
.addClassLoader(plugin.getClass().getClassLoader()).addScanners(new SubTypesScanner()) .addClassLoader(plugin.getClass().getClassLoader()).addScanners(new SubTypesScanner())
.filterInputsBy((String pkg) -> pkg.contains("buttondevteam.thebuttonmcchat.commands"))); .filterInputsBy((String pkg) -> pkg.contains(acmdclass.getPackage().getName())));
Set<Class<? extends TBMCCommandBase>> cmds = rf.getSubTypesOf(TBMCCommandBase.class); Set<Class<? extends TBMCCommandBase>> cmds = rf.getSubTypesOf(TBMCCommandBase.class);
for (Class<? extends TBMCCommandBase> cmd : cmds) { for (Class<? extends TBMCCommandBase> cmd : cmds) {
try { try {
@ -69,20 +69,6 @@ public class CommandCaller implements CommandExecutor {
} }
} }
public static void AddCommand(JavaPlugin plugin, TBMCCommandBase cmd) {
if (instance == null)
instance = new CommandCaller();
commands.put(cmd.GetCommandPath(), cmd);
if (!cmd.GetCommandPath().contains("/")) // Top-level command
{
PluginCommand pc = plugin.getCommand(cmd.GetCommandPath());
if (pc == null)
new Exception("Can't find top-level command: " + cmd.GetCommandPath()).printStackTrace();
else
pc.setExecutor(instance);
}
}
@Override @Override
public boolean onCommand(CommandSender sender, Command command, String alias, String[] args) { public boolean onCommand(CommandSender sender, Command command, String alias, String[] args) {
String path = command.getName(); String path = command.getName();

View file

@ -31,7 +31,7 @@ public class ConfirmCommand extends AdminCommandBase {
sender.sendMessage("§6-- Reloading done!§r"); sender.sendMessage("§6-- Reloading done!§r");
ReloadCommand.Reloader = null; ReloadCommand.Reloader = null;
} catch (Exception e) { } catch (Exception e) {
System.out.println("Error!\n" + e); PluginMain.Instance.getLogger().warning("Error!\n" + e);
if (sender != PluginMain.Console) if (sender != PluginMain.Console)
sender.sendMessage("§cAn error occured. See console for details.§r"); sender.sendMessage("§cAn error occured. See console for details.§r");
PluginMain.LastException = e; PluginMain.LastException = e;

View file

@ -2,6 +2,8 @@ package buttondevteam.thebuttonmcchat.commands.ucmds.admin;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import buttondevteam.thebuttonmcchat.PluginMain;
public class DebugCommand extends AdminCommandBase { public class DebugCommand extends AdminCommandBase {
private static boolean DebugMode = false; private static boolean DebugMode = false;
@ -25,6 +27,6 @@ public class DebugCommand extends AdminCommandBase {
public static void SendDebugMessage(String message) { public static void SendDebugMessage(String message) {
if (DebugMode) if (DebugMode)
System.out.println(message); PluginMain.Instance.getLogger().info(message);
} }
} }

View file

@ -15,26 +15,30 @@ public class UpdatePlugin extends AdminCommandBase {
@Override @Override
public String[] GetHelpText(String alias) { public String[] GetHelpText(String alias) {
return new String[] { "§6---- Update plugin ----", return new String[] { "§6---- Update plugin ----",
"This command downloads the latest version of the plugin from GitHub" }; "This command downloads the latest version of a TBMC plugin from GitHub",
"To update a plugin: /" + alias + " <plugin>", "To list the plugin names: /" + alias };
} }
@Override @Override
public boolean OnCommand(CommandSender sender, String alias, public boolean OnCommand(CommandSender sender, String alias, String[] args) {
String[] args) { if (args.length == 0)
sender.sendMessage("Updating Auto-Flair plugin..."); {
System.out.println("Forced updating of Auto-Flair plugin."); sender.sendMessage("§6---- Plugin names ----");
for(Plugin plugin : TBMC)
sender.sendMessage("");
}
sender.sendMessage("Updating plugin...");
PluginMain.Instance.getLogger().info("Forced updating of the plugin.");
URL url; URL url;
try { try {
url = new URL( url = new URL("https://github.com/NorbiPeti/thebuttonmcchat/raw/master/TheButtonMCChat.jar");
"https://github.com/NorbiPeti/thebuttonmcchat/raw/master/TheButtonMCChat.jar"); FileUtils.copyURLToFile(url, new File("plugins/TheButtonMCChat.jar"));
FileUtils.copyURLToFile(url, new File(
"plugins/TheButtonMCChat.jar"));
sender.sendMessage("Updating done!"); sender.sendMessage("Updating done!");
} catch (MalformedURLException e) { } catch (MalformedURLException e) {
System.out.println("Error!\n" + e); PluginMain.Instance.getLogger().warning("Error!\n" + e);
PluginMain.LastException = e; PluginMain.LastException = e;
} catch (IOException e) { } catch (IOException e) {
System.out.println("Error!\n" + e); PluginMain.Instance.getLogger().warning("Error!\n" + e);
PluginMain.LastException = e; PluginMain.LastException = e;
} }
return true; return true;