From 7ca3bc7379215b7726480ebb14c3dd07fe521f62 Mon Sep 17 00:00:00 2001 From: Logan Fick Date: Fri, 8 Feb 2019 18:49:51 -0500 Subject: Reformatted code. --- .../annotations/AutoRegisterListener.java | 17 +- .../java/com/redstoner/annotations/Commands.java | 11 +- .../java/com/redstoner/annotations/Version.java | 43 +- .../coremods/moduleLoader/ModuleLoader.java | 708 +++++++++------------ .../exceptions/MissingVersionException.java | 23 +- .../exceptions/NonSaveableConfigException.java | 10 +- .../java/com/redstoner/logging/Log4JFilter.java | 86 +-- .../com/redstoner/logging/PrivateLogManager.java | 81 ++- .../java/com/redstoner/misc/BroadcastFilter.java | 16 +- .../java/com/redstoner/misc/CommandHolderType.java | 5 +- src/main/java/com/redstoner/misc/JsonManager.java | 165 +++-- src/main/java/com/redstoner/misc/Main.java | 31 +- src/main/java/com/redstoner/misc/ModuleInfo.java | 66 +- src/main/java/com/redstoner/misc/Utils.java | 235 ++++--- .../java/com/redstoner/misc/VersionHelper.java | 188 +++--- src/main/java/com/redstoner/misc/mysql/Config.java | 261 +++----- .../java/com/redstoner/misc/mysql/JSONManager.java | 115 ++-- .../com/redstoner/misc/mysql/MysqlHandler.java | 105 ++- .../redstoner/misc/mysql/MysqlQueryHandler.java | 14 +- .../misc/mysql/elements/ConstraintOperator.java | 2 +- .../misc/mysql/elements/MysqlConstraint.java | 2 +- .../misc/mysql/elements/MysqlDatabase.java | 92 +-- .../redstoner/misc/mysql/elements/MysqlField.java | 14 +- .../redstoner/misc/mysql/elements/MysqlResult.java | 4 +- .../redstoner/misc/mysql/elements/MysqlTable.java | 162 +++-- .../com/redstoner/misc/mysql/types/MysqlType.java | 44 +- .../com/redstoner/misc/mysql/types/number/Int.java | 4 +- .../com/redstoner/misc/mysql/types/text/Char.java | 4 +- .../com/redstoner/misc/mysql/types/text/Enum.java | 12 +- .../com/redstoner/misc/mysql/types/text/Set.java | 12 +- .../redstoner/misc/mysql/types/text/VarChar.java | 4 +- .../java/com/redstoner/modules/CoreModule.java | 21 +- src/main/java/com/redstoner/modules/Module.java | 77 ++- .../java/com/redstoner/modules/ModuleLogger.java | 78 +-- 34 files changed, 1202 insertions(+), 1510 deletions(-) diff --git a/src/main/java/com/redstoner/annotations/AutoRegisterListener.java b/src/main/java/com/redstoner/annotations/AutoRegisterListener.java index fabdb5f..7e36c9e 100644 --- a/src/main/java/com/redstoner/annotations/AutoRegisterListener.java +++ b/src/main/java/com/redstoner/annotations/AutoRegisterListener.java @@ -5,11 +5,12 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -/** The auto register annotation, to be put onto Classes that implement listener when you are too lazy to register the events yourself. - * - * @author Pepich */ -@Target(ElementType.TYPE) -@Retention(RetentionPolicy.RUNTIME) -@Version(major = 1, minor = 0, revision = 1, compatible = 1) -public @interface AutoRegisterListener -{} +/** + * The auto register annotation, to be put onto Classes that implement listener when you are too lazy to register the events yourself. + * + * @author Pepich + */ +@Target (ElementType.TYPE) +@Retention (RetentionPolicy.RUNTIME) +@Version (major = 1, minor = 0, revision = 1, compatible = 1) +public @interface AutoRegisterListener {} diff --git a/src/main/java/com/redstoner/annotations/Commands.java b/src/main/java/com/redstoner/annotations/Commands.java index 537bff0..d5ea130 100644 --- a/src/main/java/com/redstoner/annotations/Commands.java +++ b/src/main/java/com/redstoner/annotations/Commands.java @@ -1,15 +1,14 @@ package com.redstoner.annotations; +import com.redstoner.misc.CommandHolderType; + import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import com.redstoner.misc.CommandHolderType; - -@Target(ElementType.TYPE) -@Retention(RetentionPolicy.RUNTIME) -public @interface Commands -{ +@Target (ElementType.TYPE) +@Retention (RetentionPolicy.RUNTIME) +public @interface Commands { CommandHolderType value(); } diff --git a/src/main/java/com/redstoner/annotations/Version.java b/src/main/java/com/redstoner/annotations/Version.java index 52d5145..2137c3f 100644 --- a/src/main/java/com/redstoner/annotations/Version.java +++ b/src/main/java/com/redstoner/annotations/Version.java @@ -1,32 +1,33 @@ package com.redstoner.annotations; -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; +import java.lang.annotation.*; -/** The Version annotation, to be applied to all Classes that are part of the project. - * - * @author Pepich */ -@Target(ElementType.TYPE) +/** + * The Version annotation, to be applied to all Classes that are part of the project. + * + * @author Pepich + */ +@Target (ElementType.TYPE) @Documented -@Retention(RetentionPolicy.RUNTIME) -public @interface Version -{ - /** The major indicator of the version. Will be used for compatibility detection. - * - * @return the major version as an int */ +@Retention (RetentionPolicy.RUNTIME) +public @interface Version { + /** + * The major indicator of the version. Will be used for compatibility detection. + * + * @return the major version as an int + */ int major(); - + int minor(); - + int revision(); - - /** The compatibility part of the version number. Will be used for compatibility detection.
+ + /** + * The compatibility part of the version number. Will be used for compatibility detection.
* Set to -1 if it is supposed to be always compatible.
* Defaults to 1. - * - * @return the smallest compatible version as an int. */ + * + * @return the smallest compatible version as an int. + */ int compatible() default 1; } diff --git a/src/main/java/com/redstoner/coremods/moduleLoader/ModuleLoader.java b/src/main/java/com/redstoner/coremods/moduleLoader/ModuleLoader.java index 3886dd1..0397f59 100644 --- a/src/main/java/com/redstoner/coremods/moduleLoader/ModuleLoader.java +++ b/src/main/java/com/redstoner/coremods/moduleLoader/ModuleLoader.java @@ -1,26 +1,5 @@ package com.redstoner.coremods.moduleLoader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; - -import org.bukkit.Bukkit; -import org.bukkit.command.CommandSender; -import org.bukkit.configuration.InvalidConfigurationException; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.event.HandlerList; -import org.bukkit.event.Listener; -import org.bukkit.plugin.java.JavaPlugin; - import com.nemez.cmdmgr.Command; import com.nemez.cmdmgr.Command.AsyncType; import com.nemez.cmdmgr.CommandManager; @@ -34,243 +13,216 @@ import com.redstoner.misc.VersionHelper; import com.redstoner.modules.CoreModule; import com.redstoner.modules.Module; import com.redstoner.modules.ModuleLogger; - import net.nemez.chatapi.click.Message; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.event.HandlerList; +import org.bukkit.event.Listener; +import org.bukkit.plugin.java.JavaPlugin; + +import java.io.*; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; + +/** + * The module loader, mother of all modules. Responsible for loading and taking care of all modules. + * + * @author Pepich + */ +@Version (major = 5, minor = 2, revision = 0, compatible = 5) +public final class ModuleLoader implements CoreModule { + private static final HashMap modules = new HashMap<>(); + private static ModuleLoader instance; + private static HashMap moduleInfos = new HashMap<>(); + private static HashMap> categorizes = new HashMap<>(); + private static URL[] urls; + private static URLClassLoader mainLoader; + private static HashMap loaders = new HashMap<>(); + private static File configFile; + private static FileConfiguration config; + private static boolean debugMode = false; + private static HashMap loggers = new HashMap<>(); -/** The module loader, mother of all modules. Responsible for loading and taking care of all modules. - * - * @author Pepich */ -@Version(major = 5, minor = 2, revision = 0, compatible = 5) -public final class ModuleLoader implements CoreModule -{ - private static ModuleLoader instance; - private static final HashMap modules = new HashMap<>(); - private static HashMap moduleInfos = new HashMap<>(); - private static HashMap> categorizes = new HashMap<>(); - private static URL[] urls; - private static URLClassLoader mainLoader; - private static HashMap loaders = new HashMap<>(); - private static File configFile; - private static FileConfiguration config; - private static boolean debugMode = false; - private static HashMap loggers = new HashMap<>(); - - private ModuleLoader() - { - try - { + private ModuleLoader() { + try { config = Main.plugin.getConfig(); configFile = new File(Main.plugin.getDataFolder(), "config.yml"); - urls = new URL[] {(new File(Main.plugin.getDataFolder(), "classes")).toURI().toURL()}; + urls = new URL[] { (new File(Main.plugin.getDataFolder(), "classes")).toURI().toURL() }; mainLoader = new URLClassLoader(urls, this.getClass().getClassLoader()); - } - catch (MalformedURLException e) - { + } catch (MalformedURLException e) { System.out.println("Sumtin is wong with ya filesüstem m8. Fix eeeet or I won't werk!"); Bukkit.getPluginManager().disablePlugin(Main.plugin); } } - - public static void init() - { + + public static void init() { if (instance == null) instance = new ModuleLoader(); ModuleInfo info = new ModuleInfo(ModuleLoader.class.getResourceAsStream("module.info"), instance); moduleInfos.put(instance, info); loggers.put(instance, new ModuleLogger(info.getDisplayName())); CommandManager.registerCommand(ModuleLoader.class.getResourceAsStream("ModuleLoader.cmd"), instance, - Main.plugin); + Main.plugin + ); } - - public static final void loadFromConfig() - { - try - { - if (!configFile.exists()) - { + + public static final void loadFromConfig() { + try { + if (!configFile.exists()) { configFile.getParentFile().mkdirs(); configFile.createNewFile(); } config.load(configFile); - } - catch (FileNotFoundException e) - {} - catch (IOException e) - { + } catch (FileNotFoundException e) { + } catch (IOException e) { e.printStackTrace(); - } - catch (InvalidConfigurationException e) - { + } catch (InvalidConfigurationException e) { configFile.delete(); - try - { + try { configFile.createNewFile(); - } - catch (IOException e1) - { + } catch (IOException e1) { e1.printStackTrace(); } instance.getLogger().error("Invalid config file! Creating new, blank file!"); } List coremods = config.getStringList("coremods"); - if (coremods == null || coremods.isEmpty()) - { - config.set("coremods", new String[] {"# Add the coremodules here!"}); + if (coremods == null || coremods.isEmpty()) { + config.set("coremods", new String[] { "# Add the coremodules here!" }); Main.plugin.saveConfig(); - try - { + try { config.save(configFile); - } - catch (IOException e) - { + } catch (IOException e) { e.printStackTrace(); } } List autoload = config.getStringList("autoload"); - if (autoload == null || autoload.isEmpty()) - { - config.set("autoload", new String[] {"# Add the modules here!"}); + if (autoload == null || autoload.isEmpty()) { + config.set("autoload", new String[] { "# Add the modules here!" }); Main.plugin.saveConfig(); - try - { + try { config.save(configFile); - } - catch (IOException e) - { + } catch (IOException e) { e.printStackTrace(); } } - if (!config.contains("debugMode")) - { + if (!config.contains("debugMode")) { config.set("debugMode", false); - try - { + try { config.save(configFile); - } - catch (IOException e) - { + } catch (IOException e) { e.printStackTrace(); } } debugMode = config.getBoolean("debugMode"); - for (String s : coremods) + for (String s : coremods) { if (!s.startsWith("#")) - if (!ModuleLoader.addDynamicModule(s)) - { + if (!ModuleLoader.addDynamicModule(s)) { instance.getLogger().error("Couldn't autocomplete path for module name: " + s - + "! If you're on a case sensitive filesystem, please take note that case correction does not work. Make sure that the classname has proper capitalisation."); - + + "! If you're on a case sensitive filesystem, please take note that case correction does not work. Make sure that the classname has proper capitalisation."); + } - for (String s : autoload) + } + for (String s : autoload) { if (!s.startsWith("#")) - if (!ModuleLoader.addDynamicModule(s)) - { + if (!ModuleLoader.addDynamicModule(s)) { instance.getLogger().error("Couldn't autocomplete path for module name: " + s - + "! If you're on a case sensitive filesystem, please take note that case correction does not work. Make sure that the classname has proper capitalisation."); - + + "! If you're on a case sensitive filesystem, please take note that case correction does not work. Make sure that the classname has proper capitalisation."); + } + } updateConfig(); } - - /** This method enables a specific module. If no module with that name is known to the loader yet it will be added to the list.
+ + /** + * This method enables a specific module. If no module with that name is known to the loader yet it will be added to the list.
* This method is deprecated, use enableDynamicModule instead. When using this method, dynamic reloading of the module will not be supported. - * + * * @param clazz The class of the module to be enabled. - * @return true, when the module was successfully enabled. */ + * + * @return true, when the module was successfully enabled. + */ @Deprecated - public static final boolean enableModule(Class clazz) - { - for (Module module : modules.keySet()) - { - if (module.getClass().equals(clazz)) - { - if (modules.get(module)) - { + public static final boolean enableModule(Class clazz) { + for (Module module : modules.keySet()) { + if (module.getClass().equals(clazz)) { + if (modules.get(module)) { instance.getLogger().info("Module was already enabled! Ignoring module.!"); return true; } - if (module.onEnable()) - { + if (module.onEnable()) { if (module.getClass().isAnnotationPresent(AutoRegisterListener.class) - && (module instanceof Listener)) - { + && (module instanceof Listener)) { Bukkit.getPluginManager().registerEvents((Listener) module, Main.plugin); } instance.getLogger().info("Enabled module " + module.getClass().getName()); instance.getLogger().info("Loaded module " + module.getClass().getName()); modules.put(module, true); return true; - } - else - { + } else { instance.getLogger().error("Failed to enable module " + module.getClass().getName()); return false; } } } - try - { + try { Module m = clazz.newInstance(); modules.put(m, false); - if (m.onEnable()) - { - if (m.getClass().isAnnotationPresent(AutoRegisterListener.class) && (m instanceof Listener)) - { + if (m.onEnable()) { + if (m.getClass().isAnnotationPresent(AutoRegisterListener.class) && (m instanceof Listener)) { Bukkit.getPluginManager().registerEvents((Listener) m, Main.plugin); } instance.getLogger().info("Loaded and enabled module " + m.getClass().getName()); instance.getLogger().info("Loaded module " + m.getClass().getName()); return true; - } - else - { + } else { instance.getLogger().error("Failed to enable module " + m.getClass().getName()); return false; } - } - catch (InstantiationException | IllegalAccessException e) - { + } catch (InstantiationException | IllegalAccessException e) { instance.getLogger() - .error("Could not add " + clazz.getName() + " to the list, constructor not accessible."); + .error("Could not add " + clazz.getName() + " to the list, constructor not accessible."); return false; } } - - private static final void enableLoadedModule(Module module, Version oldVersion) - { - try - { + + private static final void enableLoadedModule(Module module, Version oldVersion) { + try { InputStream infoFile = null; - + if (VersionHelper.isCompatible(VersionHelper.create(5, 0, 0, 5), module.getClass())) { - String basePath = "plugins/ModuleLoader/classes/" + module.getClass().getName().replace(".", "/"); - + String basePath = "plugins/ModuleLoader/classes/" + module.getClass().getName().replace(".", "/"); + try { infoFile = new FileInputStream( - new File(basePath.substring(0, basePath.lastIndexOf('/')+1) + "module.info")); - } - catch(Exception e) { + new File(basePath.substring(0, basePath.lastIndexOf('/') + 1) + "module.info")); + } catch (Exception e) { infoFile = null; } } ModuleInfo info = new ModuleInfo(infoFile, module); - + moduleInfos.put(module, info); - + String category = info.getCategory(); - if (!categorizes.containsKey(category)) + if (!categorizes.containsKey(category)) categorizes.put(category, new ArrayList<>(Arrays.asList(module))); else { List modsInCat = categorizes.get(category); modsInCat.add(module); categorizes.put(category, modsInCat); } - - loggers.put(module, new ModuleLogger(info.getDisplayName())); - - - if (module.onEnable()) - { + + loggers.put(module, new ModuleLogger(info.getDisplayName())); + + + if (module.onEnable()) { modules.put(module, true); if (VersionHelper.getString(oldVersion).equals("0.0.0.0")) module.firstLoad(); @@ -278,21 +230,18 @@ public final class ModuleLoader implements CoreModule module.migrate(oldVersion); if (VersionHelper.isCompatible(VersionHelper.create(5, 0, 0, 3), module.getClass())) module.postEnable(); - if (VersionHelper.isCompatible(VersionHelper.create(5, 0, 0, 4), module.getClass())) - { + if (VersionHelper.isCompatible(VersionHelper.create(5, 0, 0, 4), module.getClass())) { Commands ann = module.getClass().getAnnotation(Commands.class); - if (ann != null) - { - switch (ann.value()) - { + if (ann != null) { + switch (ann.value()) { case File: File f = new File("plugins/ModuleLoader/classes/" - + module.getClass().getName().replace(".", "/") + ".cmd"); + + module.getClass().getName().replace(".", "/") + ".cmd"); CommandManager.registerCommand(f, module, Main.plugin); break; case Stream: InputStream stream = module.getClass() - .getResourceAsStream(module.getClass().getSimpleName() + ".cmd"); + .getResourceAsStream(module.getClass().getSimpleName() + ".cmd"); CommandManager.registerCommand(stream, module, Main.plugin); case String: CommandManager.registerCommand(module.getCommandString(), module, Main.plugin); @@ -305,189 +254,97 @@ public final class ModuleLoader implements CoreModule instance.getLogger().info("Loaded module " + module.getClass().getName()); if (module.getClass().isAnnotationPresent(AutoRegisterListener.class) && (module instanceof Listener)) Bukkit.getPluginManager().registerEvents((Listener) module, Main.plugin); - } - else + } else instance.getLogger().error("Failed to load module " + module.getClass().getName()); - } - catch (Exception e) - { + } catch (Exception e) { instance.getLogger().error("Failed to load module " + module.getClass().getName()); e.printStackTrace(); } } - - /** This method lists all modules to the specified CommandSender. The modules will be color coded correspondingly to their enabled status. - * - * @param sender The person to send the info to, usually the issuer of the command or the console sender. - * @return true. */ - @Command(hook = "list", async = AsyncType.ALWAYS) - public boolean listModulesCommand(CommandSender sender) - { - boolean hasCategorys = hasCategories(); - Message m = new Message(sender, null); - ModuleInfo ml_info = moduleInfos.get(instance); - - m.appendText("§2--=[ ") - .appendTextHover("§2" + ml_info.getDisplayName(), ml_info.getModuleInfoHover()) - .appendText("§2 ]=--\nModules:\n"); - - for (String cat: categorizes.keySet()) { - if (hasCategorys) - m.appendText("\n&7" + cat + ":\n"); - - int curModule = 1; - List mods = categorizes.get(cat); - for (Module mod : mods) { - - ModuleInfo info = moduleInfos.get(mod); - m.appendTextHover((modules.get(mod) ? "§a" : "§c") + info.getDisplayName(), info.getModuleInfoHover()); - - if (curModule != mods.size()) - m.appendText("&7, "); - curModule++; - } - m.appendText("\n"); - - } - m.send(); - return true; - } - - public static void disableModules() - { - for (Module module : modules.keySet()) - { + + public static void disableModules() { + for (Module module : modules.keySet()) { disableModule(module); } } - - public static void disableModule(Module module) - { - if (modules.get(module)) - { + + public static void disableModule(Module module) { + if (modules.get(module)) { module.onDisable(); - if (module.getClass().isAnnotationPresent(AutoRegisterListener.class) && (module instanceof Listener)) - { + if (module.getClass().isAnnotationPresent(AutoRegisterListener.class) && (module instanceof Listener)) { HandlerList.unregisterAll((Listener) module); } CommandManager.unregisterAllWithFallback(module.getClass().getSimpleName()); PrivateLogManager.unregister(module); - try - { + try { URLClassLoader loader = loaders.get(module); if (loader != null) loader.close(); - } - catch (IOException e) - {} - finally - { + } catch (IOException e) { + } finally { loaders.remove(module); } } } - - @Command(hook = "load") - public boolean loadModule(CommandSender sender, String name) - { - if (!addDynamicModule(name)) - { - instance.getLogger().message(sender, true, "Couldn't autocomplete path for module name: " + name - + "! If you're on a case sensitive filesystem, please take note that case correction does not work. Make sure that the classname has proper capitalisation."); - - } - updateConfig(); - return true; - } - - @Command(hook = "unload") - public boolean unloadModule(CommandSender sender, String name) - { - if (!removeDynamicModule(name)) - instance.getLogger().error("Couldn't find module! Couldn't disable nonexisting module!"); - return true; - } - - public static final boolean addDynamicModule(String raw_name) - { - String[] raw = raw_name.split(" "); - String name = raw[0]; - Version oldVersion; + + public static final boolean addDynamicModule(String raw_name) { + String[] raw = raw_name.split(" "); + String name = raw[0]; + Version oldVersion; if (raw.length > 1) oldVersion = VersionHelper.getVersion(raw[1]); else oldVersion = VersionHelper.create(0, 0, 0, 0); - for (Module m : modules.keySet()) - { - if (m.getClass().getName().equals(name)) - { + for (Module m : modules.keySet()) { + if (m.getClass().getName().equals(name)) { instance.getLogger().info( "Found existing module, attempting override. WARNING! This operation will halt the main thread until it is completed."); instance.getLogger() - .info("Attempting to load new class definition before disabling and removing the old module"); + .info("Attempting to load new class definition before disabling and removing the old module"); boolean differs = false; instance.getLogger().info("Old class definition: Class@" + m.getClass().hashCode()); - ClassLoader delegateParent = mainLoader.getParent(); - Class newClass = null; - URLClassLoader cl = new URLClassLoader(urls, delegateParent); - try - { + ClassLoader delegateParent = mainLoader.getParent(); + Class newClass = null; + URLClassLoader cl = new URLClassLoader(urls, delegateParent); + try { newClass = cl.loadClass(m.getClass().getName()); instance.getLogger().info("Found new class definition: Class@" + newClass.hashCode()); differs = m.getClass() != newClass; - } - catch (ClassNotFoundException e) - { + } catch (ClassNotFoundException e) { instance.getLogger().error("Could not find a class definition, aborting now!"); e.printStackTrace(); - try - { + try { cl.close(); - } - catch (IOException e1) - { + } catch (IOException e1) { e1.printStackTrace(); } return false; } - if (!differs) - { - if (!debugMode) - { + if (!differs) { + if (!debugMode) { instance.getLogger().warn( "New class definition equals old definition, are you sure you did everything right?"); instance.getLogger().info("Aborting now..."); - try - { + try { cl.close(); - } - catch (IOException e) - { + } catch (IOException e) { e.printStackTrace(); } return false; - } - else + } else instance.getLogger().warn( "New class definition equals old definition, but debugMode is enabled. Loading anyways."); - } - else + } else instance.getLogger().info("Found new class definition, attempting to instantiate:"); Module module = null; - try - { + try { module = (Module) newClass.newInstance(); - } - catch (InstantiationException | IllegalAccessException e) - { + } catch (InstantiationException | IllegalAccessException e) { instance.getLogger().error("Could not instantiate the module, aborting!"); e.printStackTrace(); - try - { + try { cl.close(); - } - catch (IOException e1) - { + } catch (IOException e1) { e1.printStackTrace(); } return false; @@ -497,45 +354,34 @@ public final class ModuleLoader implements CoreModule instance.getLogger().info("Current version: " + VersionHelper.getString(oldVersion)); Version newVersion = module.getClass().getAnnotation(Version.class); instance.getLogger().info("Version of remote class: " + VersionHelper.getString(newVersion)); - if (oldVersion.equals(newVersion)) - { - if (!debugMode) - { + if (oldVersion.equals(newVersion)) { + if (!debugMode) { instance.getLogger().error("Detected equal module versions, " + (debugMode - ? " aborting now... Set debugMode to true in your config if you want to continue!" - : " continueing anyways.")); - if (!debugMode) - { - try - { + ? " aborting now... Set debugMode to true in your config if you want to continue!" + : " continueing anyways.")); + if (!debugMode) { + try { cl.close(); - } - catch (IOException e) - { + } catch (IOException e) { e.printStackTrace(); } return false; } - } - else + } else instance.getLogger() - .warn("New version equals old version, but debugMode is enabled. Loading anyways."); - } - else + .warn("New version equals old version, but debugMode is enabled. Loading anyways."); + } else instance.getLogger().info("Versions differ, disabling old module"); disableModule(m); instance.getLogger().info("Disabled module, overriding the implementation"); modules.remove(m); categorizes.get(moduleInfos.get(m).getCategory()).remove(m); moduleInfos.remove(m); - - try - { + + try { if (loaders.containsKey(m)) loaders.remove(m).close(); - } - catch (IOException e) - { + } catch (IOException e) { e.printStackTrace(); } modules.put(module, false); @@ -545,61 +391,50 @@ public final class ModuleLoader implements CoreModule return true; } } - ClassLoader delegateParent = mainLoader.getParent(); - URLClassLoader cl = new URLClassLoader(urls, delegateParent); - try - { - Class clazz = cl.loadClass(name); - Module module = (Module) clazz.newInstance(); + ClassLoader delegateParent = mainLoader.getParent(); + URLClassLoader cl = new URLClassLoader(urls, delegateParent); + try { + Class clazz = cl.loadClass(name); + Module module = (Module) clazz.newInstance(); modules.put(module, false); loaders.put(module, cl); enableLoadedModule(module, oldVersion); return true; - } - catch (NoClassDefFoundError | ClassNotFoundException | InstantiationException | IllegalAccessException e) - { - try - { + } catch (NoClassDefFoundError | ClassNotFoundException | InstantiationException | IllegalAccessException e) { + try { cl.close(); + } catch (IOException e1) { } - catch (IOException e1) - {} - if (e instanceof NoClassDefFoundError) - { + if (e instanceof NoClassDefFoundError) { NoClassDefFoundError exception = (NoClassDefFoundError) e; - String[] exMessage = exception.getMessage().split(" "); + String[] exMessage = exception.getMessage().split(" "); String moduleName = exMessage[exMessage.length - 1] .substring(0, exMessage[exMessage.length - 1].length() - - (exMessage[exMessage.length - 1].endsWith(")") ? 1 : 0)) + - (exMessage[exMessage.length - 1].endsWith(")") ? 1 : 0)) .replace("/", "."); - if (!moduleName.equalsIgnoreCase(name)) - { + if (!moduleName.equalsIgnoreCase(name)) { instance.getLogger() - .error("Class &e" + moduleName + "&r couldn't be found! Suspecting a missing dependency!"); + .error("Class &e" + moduleName + "&r couldn't be found! Suspecting a missing dependency!"); return false; - } - else + } else instance.getLogger().warn( "Couldn't find class definition, attempting to get proper classname from thrown Exception."); if (addDynamicModule(moduleName)) return true; } - if (name.endsWith(".class")) - { + if (name.endsWith(".class")) { instance.getLogger().warn( "Couldn't find class definition, but path ends with .class -> Attempting again with removed file suffix."); if (addDynamicModule(name.replaceAll(".class$", ""))) return true; } - if (!name.contains(".")) - { + if (!name.contains(".")) { instance.getLogger().warn( "Couldn't find class definition, suspecting incomplete path. Attempting autocompletion of path by adding a package name and trying again."); if (addDynamicModule(name.toLowerCase() + "." + name)) return true; } - if (!name.startsWith("com.redstoner.modules.") && name.contains(".")) - { + if (!name.startsWith("com.redstoner.modules.") && name.contains(".")) { instance.getLogger().warn( "Couldn't find class definition, suspecting incomplete path. Attempting autocompletion of package name and trying again."); if (addDynamicModule("com.redstoner.modules." + name)) @@ -608,13 +443,10 @@ public final class ModuleLoader implements CoreModule } return false; } - - public static final boolean removeDynamicModule(String name) - { - for (Module m : modules.keySet()) - { - if (m.getClass().getName().equals(name)) - { + + public static final boolean removeDynamicModule(String name) { + for (Module m : modules.keySet()) { + if (m.getClass().getName().equals(name)) { instance.getLogger().info( "Found existing module, attempting unload. WARNING! This operation will halt the main thread until it is completed."); instance.getLogger().info("Attempting to disable module properly:"); @@ -626,24 +458,20 @@ public final class ModuleLoader implements CoreModule return true; } } - if (!name.startsWith("com.redstoner.modules.")) - { - if (name.endsWith(".class")) - { + if (!name.startsWith("com.redstoner.modules.")) { + if (name.endsWith(".class")) { instance.getLogger().warn( "Couldn't find class definition, but path ends with .class -> Attempting again with removed file suffix."); if (removeDynamicModule(name.replaceAll(".class$", ""))) return true; } - if (!name.contains(".")) - { + if (!name.contains(".")) { instance.getLogger().warn( "Couldn't find class definition, suspecting incomplete path. Attempting autocompletion of path by adding a package name and trying again."); if (removeDynamicModule(name.toLowerCase() + "." + name)) return true; } - if (!name.startsWith("com.redstoner.modules.")) - { + if (!name.startsWith("com.redstoner.modules.")) { instance.getLogger().warn( "Couldn't find class definition, suspecting incomplete path. Attempting autocompletion of package name and trying again."); if (removeDynamicModule("com.redstoner.modules." + name)) @@ -652,101 +480,145 @@ public final class ModuleLoader implements CoreModule } return false; } - - /** Finds a module by name for other modules to reference it. - * + + /** + * Finds a module by name for other modules to reference it. + * * @param name the name of the module. Use the full path if you are not sure about the module's SimpleClassName being unique. - * @return the instance of the module or @null it none could be found */ - public static Module getModule(String name) - { - for (Module m : modules.keySet()) + * + * @return the instance of the module or @null it none could be found + */ + public static Module getModule(String name) { + for (Module m : modules.keySet()) { if (m.getClass().getSimpleName().equalsIgnoreCase(name) || m.getClass().getName().equalsIgnoreCase(name)) return m; + } return null; } - - /** Finds a module by name for other modules to reference it. - * + + /** + * Finds a module by name for other modules to reference it. + * * @param name the name of the module. Use the full path if you are not sure about the module's SimpleClassName being unique. - * @return the instance of the module or @null it none could be found */ - public static boolean exists(String name) - { - for (Module m : modules.keySet()) + * + * @return the instance of the module or @null it none could be found + */ + public static boolean exists(String name) { + for (Module m : modules.keySet()) { if (m.getClass().getSimpleName().equals(name) || m.getClass().getName().equals(name)) return true; + } return false; } - - public static ModuleLogger getModuleLogger(Module module) - { + + public static ModuleLogger getModuleLogger(Module module) { return loggers.get(module); } - - public static void updateConfig() - { - List coremods = config.getStringList("coremods"); + + public static void updateConfig() { + List coremods = config.getStringList("coremods"); ArrayList new_coremods = new ArrayList<>(); - List autoload = config.getStringList("autoload"); + List autoload = config.getStringList("autoload"); ArrayList new_autoload = new ArrayList<>(); - - for (String s : coremods) - { - if (s.startsWith("#")) - { + + for (String s : coremods) { + if (s.startsWith("#")) { new_coremods.add(s); - } - else - { + } else { s = s.split(" ")[0]; - try - { + try { new_coremods.add(getModule(s).getClass().getName() + " " - + VersionHelper.getVersion(getModule(s).getClass())); - } - catch (Exception e) - { + + VersionHelper.getVersion(getModule(s).getClass())); + } catch (Exception e) { new_coremods.add(s + " " + VersionHelper.getString(VersionHelper.create(0, 0, 0, 0))); } } } - for (String s : autoload) - { - if (s.startsWith("#")) - { + for (String s : autoload) { + if (s.startsWith("#")) { new_autoload.add(s); - } - else - { + } else { s = s.split(" ")[0]; - try - { + try { new_autoload.add(getModule(s).getClass().getName() + " " - + VersionHelper.getVersion(getModule(s).getClass())); - } - catch (Exception e) - { + + VersionHelper.getVersion(getModule(s).getClass())); + } catch (Exception e) { new_autoload.add(s + " " + VersionHelper.getString(VersionHelper.create(0, 0, 0, 0))); } } } - + config.set("coremods", new_coremods); config.set("autoload", new_autoload); - try - { + try { config.save(configFile); - } - catch (IOException e) - { + } catch (IOException e) { e.printStackTrace(); } } - + public static JavaPlugin getPlugin() { return Main.plugin; } - + + /** + * This method lists all modules to the specified CommandSender. The modules will be color coded correspondingly to their enabled status. + * + * @param sender The person to send the info to, usually the issuer of the command or the console sender. + * + * @return true. + */ + @Command (hook = "list", async = AsyncType.ALWAYS) + public boolean listModulesCommand(CommandSender sender) { + boolean hasCategorys = hasCategories(); + Message m = new Message(sender, null); + ModuleInfo ml_info = moduleInfos.get(instance); + + m.appendText("§2--=[ ") + .appendTextHover("§2" + ml_info.getDisplayName(), ml_info.getModuleInfoHover()) + .appendText("§2 ]=--\nModules:\n"); + + for (String cat : categorizes.keySet()) { + if (hasCategorys) + m.appendText("\n&7" + cat + ":\n"); + + int curModule = 1; + List mods = categorizes.get(cat); + for (Module mod : mods) { + + ModuleInfo info = moduleInfos.get(mod); + m.appendTextHover((modules.get(mod) ? "§a" : "§c") + info.getDisplayName(), info.getModuleInfoHover()); + + if (curModule != mods.size()) + m.appendText("&7, "); + curModule++; + } + m.appendText("\n"); + + } + m.send(); + return true; + } + public static boolean hasCategories() { return !(categorizes.size() == 1 && categorizes.containsKey("Other")); } + + @Command (hook = "load") + public boolean loadModule(CommandSender sender, String name) { + if (!addDynamicModule(name)) { + instance.getLogger().message(sender, true, "Couldn't autocomplete path for module name: " + name + + "! If you're on a case sensitive filesystem, please take note that case correction does not work. Make sure that the classname has proper capitalisation."); + + } + updateConfig(); + return true; + } + + @Command (hook = "unload") + public boolean unloadModule(CommandSender sender, String name) { + if (!removeDynamicModule(name)) + instance.getLogger().error("Couldn't find module! Couldn't disable nonexisting module!"); + return true; + } } diff --git a/src/main/java/com/redstoner/exceptions/MissingVersionException.java b/src/main/java/com/redstoner/exceptions/MissingVersionException.java index 62032b6..3ea1f17 100644 --- a/src/main/java/com/redstoner/exceptions/MissingVersionException.java +++ b/src/main/java/com/redstoner/exceptions/MissingVersionException.java @@ -2,21 +2,20 @@ package com.redstoner.exceptions; import com.redstoner.annotations.Version; -/** To be thrown when a module is not annotated with its version. If this gets thrown, then oh boy, you're in trouble now. - * - * @author Pepich */ -@Version(major = 1, minor = 0, revision = 0, compatible = -1) -public class MissingVersionException extends Exception -{ +/** + * To be thrown when a module is not annotated with its version. If this gets thrown, then oh boy, you're in trouble now. + * + * @author Pepich + */ +@Version (major = 1, minor = 0, revision = 0, compatible = -1) +public class MissingVersionException extends Exception { private static final long serialVersionUID = 4940161335512222539L; - - public MissingVersionException() - { + + public MissingVersionException() { super(); } - - public MissingVersionException(String message) - { + + public MissingVersionException(String message) { super(message); } } diff --git a/src/main/java/com/redstoner/exceptions/NonSaveableConfigException.java b/src/main/java/com/redstoner/exceptions/NonSaveableConfigException.java index df33bff..926e9b2 100644 --- a/src/main/java/com/redstoner/exceptions/NonSaveableConfigException.java +++ b/src/main/java/com/redstoner/exceptions/NonSaveableConfigException.java @@ -1,9 +1,9 @@ package com.redstoner.exceptions; public class NonSaveableConfigException extends Exception { - private static final long serialVersionUID = -7271481973389455510L; - - public NonSaveableConfigException() { - super("This config does not support saving!"); - } + private static final long serialVersionUID = -7271481973389455510L; + + public NonSaveableConfigException() { + super("This config does not support saving!"); + } } diff --git a/src/main/java/com/redstoner/logging/Log4JFilter.java b/src/main/java/com/redstoner/logging/Log4JFilter.java index 1ebed09..bdc94d4 100644 --- a/src/main/java/com/redstoner/logging/Log4JFilter.java +++ b/src/main/java/com/redstoner/logging/Log4JFilter.java @@ -1,5 +1,5 @@ package com.redstoner.logging; - + import org.apache.logging.log4j.Level; import org.apache.logging.log4j.Marker; import org.apache.logging.log4j.core.LogEvent; @@ -9,46 +9,46 @@ import org.apache.logging.log4j.message.Message; public class Log4JFilter extends AbstractFilter { - private static final long serialVersionUID = -5594073755007974254L; - - private static Result validateMessage(Message message) { - if (message == null) { - return Result.NEUTRAL; - } - return validateMessage(message.getFormattedMessage()); - } - - private static Result validateMessage(String message) { - return PrivateLogManager.isHidden(message) - ? Result.DENY - : Result.NEUTRAL; - } - - @Override - public Result filter(LogEvent event) { - Message candidate = null; - if (event != null) { - candidate = event.getMessage(); - } - return validateMessage(candidate); - } - - @Override - public Result filter(Logger logger, Level level, Marker marker, Message msg, Throwable t) { - return validateMessage(msg); - } - - @Override - public Result filter(Logger logger, Level level, Marker marker, String msg, Object... params) { - return validateMessage(msg); - } - - @Override - public Result filter(Logger logger, Level level, Marker marker, Object msg, Throwable t) { - String candidate = null; - if (msg != null) { - candidate = msg.toString(); - } - return validateMessage(candidate); - } + private static final long serialVersionUID = -5594073755007974254L; + + @Override + public Result filter(LogEvent event) { + Message candidate = null; + if (event != null) { + candidate = event.getMessage(); + } + return validateMessage(candidate); + } + + private static Result validateMessage(Message message) { + if (message == null) { + return Result.NEUTRAL; + } + return validateMessage(message.getFormattedMessage()); + } + + private static Result validateMessage(String message) { + return PrivateLogManager.isHidden(message) + ? Result.DENY + : Result.NEUTRAL; + } + + @Override + public Result filter(Logger logger, Level level, Marker marker, Message msg, Throwable t) { + return validateMessage(msg); + } + + @Override + public Result filter(Logger logger, Level level, Marker marker, String msg, Object... params) { + return validateMessage(msg); + } + + @Override + public Result filter(Logger logger, Level level, Marker marker, Object msg, Throwable t) { + String candidate = null; + if (msg != null) { + candidate = msg.toString(); + } + return validateMessage(candidate); + } } \ No newline at end of file diff --git a/src/main/java/com/redstoner/logging/PrivateLogManager.java b/src/main/java/com/redstoner/logging/PrivateLogManager.java index e8451e0..ce6a68c 100644 --- a/src/main/java/com/redstoner/logging/PrivateLogManager.java +++ b/src/main/java/com/redstoner/logging/PrivateLogManager.java @@ -1,44 +1,41 @@ package com.redstoner.logging; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import org.apache.logging.log4j.LogManager; - import com.redstoner.misc.Utils; import com.redstoner.modules.Module; import com.redstoner.modules.ModuleLogger; +import org.apache.logging.log4j.LogManager; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; public class PrivateLogManager { + private static final String ISSUED_COMMAND_TEXT = "issued server command: /"; + private static final int ISSUED_COMMAND_TEXT_LENGTH = ISSUED_COMMAND_TEXT.length(); private static Map registrar = new HashMap<>(); - private static Map commands = new HashMap<>(); - - private static final String ISSUED_COMMAND_TEXT = "issued server command: /"; - private static final int ISSUED_COMMAND_TEXT_LENGTH = ISSUED_COMMAND_TEXT.length(); - + private static Map commands = new HashMap<>(); private static ModuleLogger logger; - + public static void initialize() { org.apache.logging.log4j.core.Logger logger; - logger = (org.apache.logging.log4j.core.Logger) LogManager.getRootLogger(); - logger.addFilter(new Log4JFilter()); - PrivateLogManager.logger = new ModuleLogger("PrivateLogManager"); + logger = (org.apache.logging.log4j.core.Logger) LogManager.getRootLogger(); + logger.addFilter(new Log4JFilter()); + PrivateLogManager.logger = new ModuleLogger("PrivateLogManager"); } - + public static void register(Module module, String command, String replacement) { command = command.toLowerCase(); registrar.put(command, module); commands.put(command, replacement); logger.info(module.getClass().getSimpleName() + " registered &e/" + command - + (replacement.equals("")? "&7. Command will not be logged!" - : "&7, using replacement, &e" + replacement + "&7.")); + + (replacement.equals("") ? "&7. Command will not be logged!" + : "&7, using replacement, &e" + replacement + "&7.")); } - + public static void unregister(Module module) { - String unregestered = ""; - Iterator> i = registrar.entrySet().iterator(); + String unregestered = ""; + Iterator> i = registrar.entrySet().iterator(); while (i.hasNext()) { Map.Entry entry = i.next(); if (entry.getValue() == module) { @@ -50,7 +47,7 @@ public class PrivateLogManager { if (!unregestered.equals("")) logger.info("Unregistered " + unregestered.substring(0, unregestered.length() - 2) + "&7 for module, " + module.getClass().getSimpleName() + "."); } - + public static void unregister(Module module, String... toRemove) { String unregestered = ""; for (int i = 0; i < toRemove.length; i++) { @@ -62,27 +59,27 @@ public class PrivateLogManager { if (!unregestered.equals("")) logger.info(module.getClass().getSimpleName() + " unregistered " + unregestered.substring(0, unregestered.length() - 2) + "&7."); } - + public static boolean isHidden(String message) { - if (message == null) - return false; - - int index = message.indexOf(ISSUED_COMMAND_TEXT); - if (index == -1) - return false; - - String command = message.substring(index + ISSUED_COMMAND_TEXT_LENGTH); - - int spaceIndex = command.indexOf(" "); - command = spaceIndex == -1? command.toLowerCase() : command.substring(0, spaceIndex).toLowerCase(); - - String replacement = commands.get(command); - if (replacement == null) - return false; - if (replacement.equals("")) - return true; - - String player = message.substring(0, message.indexOf(" ")); + if (message == null) + return false; + + int index = message.indexOf(ISSUED_COMMAND_TEXT); + if (index == -1) + return false; + + String command = message.substring(index + ISSUED_COMMAND_TEXT_LENGTH); + + int spaceIndex = command.indexOf(" "); + command = spaceIndex == -1 ? command.toLowerCase() : command.substring(0, spaceIndex).toLowerCase(); + + String replacement = commands.get(command); + if (replacement == null) + return false; + if (replacement.equals("")) + return true; + + String player = message.substring(0, message.indexOf(" ")); Utils.run(() -> System.out.println(replacement.replace("$s", player))); return true; } diff --git a/src/main/java/com/redstoner/misc/BroadcastFilter.java b/src/main/java/com/redstoner/misc/BroadcastFilter.java index 1f0ce04..a0098b6 100644 --- a/src/main/java/com/redstoner/misc/BroadcastFilter.java +++ b/src/main/java/com/redstoner/misc/BroadcastFilter.java @@ -1,14 +1,14 @@ package com.redstoner.misc; -import org.bukkit.command.CommandSender; - import com.redstoner.annotations.Version; +import org.bukkit.command.CommandSender; -/** Classes implementing this interface can be used to define a filter for the Utils.broadcast method for sending a message to more than one, but less than all users. - * - * @author Pepich */ -@Version(major = 1, minor = 0, revision = 0, compatible = 1) -public interface BroadcastFilter -{ +/** + * Classes implementing this interface can be used to define a filter for the Utils.broadcast method for sending a message to more than one, but less than all users. + * + * @author Pepich + */ +@Version (major = 1, minor = 0, revision = 0, compatible = 1) +public interface BroadcastFilter { public boolean sendTo(CommandSender recipient); } diff --git a/src/main/java/com/redstoner/misc/CommandHolderType.java b/src/main/java/com/redstoner/misc/CommandHolderType.java index 7c4383e..3c64127 100644 --- a/src/main/java/com/redstoner/misc/CommandHolderType.java +++ b/src/main/java/com/redstoner/misc/CommandHolderType.java @@ -3,9 +3,8 @@ package com.redstoner.misc; import com.redstoner.annotations.Version; /** @author Pepich */ -@Version(major = 4, minor = 0, revision = 0, compatible = -1) -public enum CommandHolderType -{ +@Version (major = 4, minor = 0, revision = 0, compatible = -1) +public enum CommandHolderType { Stream, File, String, diff --git a/src/main/java/com/redstoner/misc/JsonManager.java b/src/main/java/com/redstoner/misc/JsonManager.java index 13b51b6..498933f 100644 --- a/src/main/java/com/redstoner/misc/JsonManager.java +++ b/src/main/java/com/redstoner/misc/JsonManager.java @@ -1,149 +1,144 @@ package com.redstoner.misc; -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; - +import com.redstoner.annotations.Version; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; -import com.redstoner.annotations.Version; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; -/** This class provides simple JSON handling, like storing and loading from and to files. - * - * @author Pepich */ -@Version(major = 1, minor = 0, revision = 2, compatible = -1) -public class JsonManager -{ - private JsonManager() - {} - - /** Loads a JSONObject from a file. - * +/** + * This class provides simple JSON handling, like storing and loading from and to files. + * + * @author Pepich + */ +@Version (major = 1, minor = 0, revision = 2, compatible = -1) +public class JsonManager { + private JsonManager() {} + + /** + * Loads a JSONObject from a file. + * * @param source the file to load from. - * @return the JSONObject or null if the source does not contain a valid JSONObject. */ - public static JSONObject getObject(File source) - { + * + * @return the JSONObject or null if the source does not contain a valid JSONObject. + */ + public static JSONObject getObject(File source) { if (!source.exists()) return null; JSONParser parser = new JSONParser(); - try - { - FileReader reader = new FileReader(source); - Object rawObject = parser.parse(reader); + try { + FileReader reader = new FileReader(source); + Object rawObject = parser.parse(reader); reader.close(); JSONObject jsonObject = (JSONObject) rawObject; return jsonObject; + } catch (IOException | ParseException e) { } - catch (IOException | ParseException e) - {} return null; } - - /** Saves a JSONObject to a file. Will create the necessary FileStructure like folders and the file itself.
+ + /** + * Saves a JSONObject to a file. Will create the necessary FileStructure like folders and the file itself.
* Note that this operation will be run on a different thread and you do not need to take care of that yourself. - * - * @param object the JSONObject to save. - * @param destination the file to write to. */ - public static void save(JSONObject object, File destination) - { - Thread t = new Thread(new Runnable() - { + * + * @param object the JSONObject to save. + * @param destination the file to write to. + */ + public static void save(JSONObject object, File destination) { + Thread t = new Thread(new Runnable() { @Override - public void run() - { + public void run() { saveSync(object, destination); } }); t.start(); } - - /** Saves a JSONObject to a file. Will create the necessary FileStructure like folders and the file itself.
+ + /** + * Saves a JSONObject to a file. Will create the necessary FileStructure like folders and the file itself.
* Note that this operation will be run on the same thread that you are calling it from! - * - * @param object the JSONObject to save. - * @param destination the file to write to. */ - public static void saveSync(JSONObject object, File destination) - { + * + * @param object the JSONObject to save. + * @param destination the file to write to. + */ + public static void saveSync(JSONObject object, File destination) { if (destination.exists()) destination.delete(); else if (!destination.getParentFile().exists()) destination.getParentFile().mkdirs(); - try - { + try { destination.createNewFile(); - FileWriter writer = new FileWriter(destination); - String json_string = object.toJSONString(); + FileWriter writer = new FileWriter(destination); + String json_string = object.toJSONString(); writer.write(json_string); writer.flush(); writer.close(); + } catch (IOException e) { } - catch (IOException e) - {} } - - /** Loads a JSONArray from a file. - * + + /** + * Loads a JSONArray from a file. + * * @param source the file to load from. - * @return the JSONArray or null if the source does not contain a valid JSONArray. */ - public static JSONArray getArray(File source) - { + * + * @return the JSONArray or null if the source does not contain a valid JSONArray. + */ + public static JSONArray getArray(File source) { if (!source.exists()) return null; JSONParser parser = new JSONParser(); - try - { - Object rawObject = parser.parse(new FileReader(source)); + try { + Object rawObject = parser.parse(new FileReader(source)); JSONArray jsonArray = (JSONArray) rawObject; return jsonArray; + } catch (IOException | ParseException e) { } - catch (IOException | ParseException e) - {} return null; } - - /** Saves a JSONArray to a file. Will create the necessary FileStructure like folders and the file itself.
+ + /** + * Saves a JSONArray to a file. Will create the necessary FileStructure like folders and the file itself.
* Note that this operation will be run on a different thread and you do not need to take care of that yourself. - * - * @param object the JSONArray to save. - * @param destination the file to write to. */ - public static void save(JSONArray array, File destination) - { - Thread t = new Thread(new Runnable() - { + * + * @param object the JSONArray to save. + * @param destination the file to write to. + */ + public static void save(JSONArray array, File destination) { + Thread t = new Thread(new Runnable() { @Override - public void run() - { + public void run() { saveSync(array, destination); } }); t.start(); } - - /** Saves a JSONArray to a file. Will create the necessary FileStructure like folders and the file itself.
+ + /** + * Saves a JSONArray to a file. Will create the necessary FileStructure like folders and the file itself.
* Note that this operation will be run on the same thread that you are calling it from! - * - * @param object the JSONArray to save. - * @param destination the file to write to. */ - public static void saveSync(JSONArray array, File destination) - { + * + * @param object the JSONArray to save. + * @param destination the file to write to. + */ + public static void saveSync(JSONArray array, File destination) { if (destination.exists()) destination.delete(); else if (!destination.getParentFile().exists()) destination.getParentFile().mkdirs(); - try - { + try { destination.createNewFile(); - FileWriter writer = new FileWriter(destination); - String json_string = array.toJSONString(); + FileWriter writer = new FileWriter(destination); + String json_string = array.toJSONString(); writer.write(json_string); writer.flush(); writer.close(); + } catch (IOException e) { } - catch (IOException e) - {} } } diff --git a/src/main/java/com/redstoner/misc/Main.java b/src/main/java/com/redstoner/misc/Main.java index 40894ee..e6de0d0 100644 --- a/src/main/java/com/redstoner/misc/Main.java +++ b/src/main/java/com/redstoner/misc/Main.java @@ -1,29 +1,27 @@ package com.redstoner.misc; -import org.bukkit.plugin.java.JavaPlugin; - import com.redstoner.annotations.Version; import com.redstoner.coremods.moduleLoader.ModuleLoader; import com.redstoner.logging.PrivateLogManager; import com.redstoner.misc.mysql.MysqlHandler; - import net.nemez.chatapi.ChatAPI; +import org.bukkit.plugin.java.JavaPlugin; -/** Main class. Duh. - * - * @author Pepich */ -@Version(major = 5, minor = 1, revision = 0, compatible = -1) -public class Main extends JavaPlugin -{ +/** + * Main class. Duh. + * + * @author Pepich + */ +@Version (major = 5, minor = 1, revision = 0, compatible = -1) +public class Main extends JavaPlugin { public static JavaPlugin plugin; - + @Override - public void onEnable() - { + public void onEnable() { plugin = this; - + PrivateLogManager.initialize(); - + ChatAPI.initialize(this); // Configger.init(); MysqlHandler.init(); @@ -31,10 +29,9 @@ public class Main extends JavaPlugin // Load modules from config ModuleLoader.loadFromConfig(); } - + @Override - public void onDisable() - { + public void onDisable() { ModuleLoader.disableModules(); } } diff --git a/src/main/java/com/redstoner/misc/ModuleInfo.java b/src/main/java/com/redstoner/misc/ModuleInfo.java index e96e813..0b670b9 100644 --- a/src/main/java/com/redstoner/misc/ModuleInfo.java +++ b/src/main/java/com/redstoner/misc/ModuleInfo.java @@ -1,14 +1,13 @@ package com.redstoner.misc; -import java.io.InputStream; -import java.io.InputStreamReader; - -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; - import com.redstoner.coremods.moduleLoader.ModuleLoader; import com.redstoner.exceptions.MissingVersionException; import com.redstoner.modules.Module; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.io.InputStream; +import java.io.InputStreamReader; public class ModuleInfo { @@ -17,65 +16,64 @@ public class ModuleInfo { private String category; private String description; private String version; - + private String warning; - + public ModuleInfo(InputStream descriptor, Module module) { try { InputStreamReader reader = new InputStreamReader(descriptor); FileConfiguration config = YamlConfiguration.loadConfiguration(reader); - + displayName = config.getString("displayName"); category = config.getString("category"); description = config.getString("description"); - } - catch (Exception e) { + } catch (Exception e) { warning = "Descriptor file could not be loaded, using the class's name."; } - + simpleName = module.getClass().getSimpleName(); - + if (displayName == null) displayName = simpleName; - + if (category == null) category = "Other"; - + try { version = VersionHelper.getVersion(module.getClass()); } catch (MissingVersionException e) {} } - public String getSimpleName() { - return simpleName; - } - public String getDisplayName() { return displayName; } - public String getCategory() { - return category; + public String getWarning() { + return warning; } - public String getDescription() { - return description; + public String getModuleInfoHover() { + return "&8&o" + getSimpleName() + "\n" + + "&r&e" + (getVersion() == null ? "&cVersion Missing" : getVersion()) + + "&r&9" + (ModuleLoader.hasCategories() ? "\n" + getCategory() : "") + + "&r&7" + (getDescription() == null ? "" : "\n\n" + getDescription()); } - public String getWarning() { - return warning; + public String getSimpleName() { + return simpleName; } - + public String getVersion() { return version; } - - public String getModuleInfoHover() { - return "&8&o" + getSimpleName() + "\n" - + "&r&e" + (getVersion() == null? "&cVersion Missing" : getVersion()) - + "&r&9" + (ModuleLoader.hasCategories()? "\n" + getCategory() : "") - + "&r&7" + (getDescription() == null? "" : "\n\n" + getDescription()); + + public String getCategory() { + return category; } - - + + public String getDescription() { + return description; + } + + } diff --git a/src/main/java/com/redstoner/misc/Utils.java b/src/main/java/com/redstoner/misc/Utils.java index e3fd68c..d53a39e 100644 --- a/src/main/java/com/redstoner/misc/Utils.java +++ b/src/main/java/com/redstoner/misc/Utils.java @@ -1,177 +1,172 @@ package com.redstoner.misc; +import com.redstoner.annotations.Version; +import com.redstoner.coremods.moduleLoader.ModuleLoader; +import net.nemez.chatapi.ChatAPI; +import net.nemez.chatapi.click.Message; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.regex.Pattern; -import org.bukkit.Bukkit; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import com.redstoner.annotations.Version; -import com.redstoner.coremods.moduleLoader.ModuleLoader; - -import net.nemez.chatapi.ChatAPI; -import net.nemez.chatapi.click.Message; - -/** The utils class containing utility functions. Those include but are not limited to sending formatted messages, broadcasts and more. - * - * @author Pepich */ -@Version(major = 4, minor = 0, revision = 2, compatible = 1) -public final class Utils -{ +/** + * The utils class containing utility functions. Those include but are not limited to sending formatted messages, broadcasts and more. + * + * @author Pepich + */ +@Version (major = 4, minor = 0, revision = 2, compatible = 1) +public final class Utils { + /** The Pattern for a UUID */ + private static final Pattern UUID_pattern = Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"); + private static final Pattern Class_pattern = Pattern.compile(".*\\."); + private static final Pattern NoDolarSign_pattern = Pattern.compile("\\$\\d*"); /** The @SimpleDateFormat used for getting the current date. */ public static SimpleDateFormat dateFormat = new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss]"); - - /** The Pattern for a UUID*/ - private static final Pattern UUID_pattern = Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"); - private static final Pattern Class_pattern = Pattern.compile(".*\\."); - private static final Pattern NoDolarSign_pattern = Pattern.compile("\\$\\d*"); - + /** Hidden constructor. Do not instantiate UTILS classes! :) */ - private Utils() - {} - - /** This method broadcasts a message to all players and console that are allowed by the filter. Set the filter to NULL to broadcast to everyone.
+ private Utils() {} + + /** + * This method broadcasts a message to all players and console that are allowed by the filter. Set the filter to NULL to broadcast to everyone.
* If you want to, you can set a message that will be logged to console. Set to null to not log anything.
* You can still allow console in the filter to log the original message. - * - * @param prefix The prefix for the message. Set to NULL to let it auto generate. - * @param message the message to be sent around - * @param filter the BroadcastFilter to be applied.
- * Write a class implementing the interface and pass it to this method, the "sendTo()" method will be called for each recipient. + * + * @param prefix The prefix for the message. Set to NULL to let it auto generate. + * @param message the message to be sent around + * @param filter the BroadcastFilter to be applied.
+ * Write a class implementing the interface and pass it to this method, the "sendTo()" method will be called for each recipient. * @param logmessage the log message to appear in console. Set to null to not log this (you can still log the original message by returning true in the filter). - * @return the amount of people that received the message. */ - public static int broadcast(String prefix, String message, BroadcastFilter filter) - { + * + * @return the amount of people that received the message. + */ + public static int broadcast(String prefix, String message, BroadcastFilter filter) { if (prefix == null) prefix = "§8[§2" + getCaller() + "§8]: "; - if (filter == null) - { - for (Player p : Bukkit.getOnlinePlayers()) - p.sendMessage(prefix + message); + if (filter == null) { + for (Player p : Bukkit.getOnlinePlayers()) { p.sendMessage(prefix + message); } Bukkit.getConsoleSender().sendMessage(prefix + message); return Bukkit.getOnlinePlayers().size() + 1; - } - else - { + } else { int count = 0; - for (Player p : Bukkit.getOnlinePlayers()) - if (filter.sendTo(p)) - { + for (Player p : Bukkit.getOnlinePlayers()) { + if (filter.sendTo(p)) { p.sendMessage(prefix + message); count++; } - if (filter.sendTo(Bukkit.getConsoleSender())) - { + } + if (filter.sendTo(Bukkit.getConsoleSender())) { Bukkit.getConsoleSender().sendMessage(prefix + message); count++; } return count; } } - - /** This method broadcasts a message to all players and console that are allowed by the filter. Set the filter to NULL to broadcast to everyone.
+ + /** + * This method will find the next parent caller and return their class name, omitting package names. + * + * @return the Name of the calling class. + */ + private static final String getCaller() { + StackTraceElement[] stackTrace = (new Exception()).getStackTrace(); + String classname = "Utils"; + for (int i = 0; classname.equals("Utils"); i++) { + classname = Class_pattern.matcher(stackTrace[i].getClassName()).replaceAll(""); + } + return classname; + } + + /** + * This method broadcasts a message to all players and console that are allowed by the filter. Set the filter to NULL to broadcast to everyone.
* If you want to, you can set a message that will be logged to console. Set to null to not log anything.
* You can still allow console in the filter to log the original message. - * - * @param prefix The prefix for the message. Set to NULL to let it auto generate. - * @param message the message to be sent around - * @param filter the BroadcastFilter to be applied.
- * Write a class implementing the interface and pass it to this method, the "sendTo()" method will be called for each recipient. + * + * @param prefix The prefix for the message. Set to NULL to let it auto generate. + * @param message the message to be sent around + * @param filter the BroadcastFilter to be applied.
+ * Write a class implementing the interface and pass it to this method, the "sendTo()" method will be called for each recipient. * @param logmessage the log message to appear in console. Set to null to not log this (you can still log the original message by returning true in the filter). */ - public static int broadcast(String prefix, Message message, BroadcastFilter filter) - { + public static int broadcast(String prefix, Message message, BroadcastFilter filter) { if (prefix == null) prefix = "§8[§2" + getCaller() + "§8]: "; - if (filter == null) - { - for (Player p : Bukkit.getOnlinePlayers()) - ChatAPI.createMessage(p).appendText(prefix).appendMessage(message).send(); + if (filter == null) { + for (Player p : Bukkit.getOnlinePlayers()) { ChatAPI.createMessage(p).appendText(prefix).appendMessage(message).send(); } Bukkit.getConsoleSender().sendMessage(prefix + message.getRawMessage()); return Bukkit.getOnlinePlayers().size() + 1; - } - else - { + } else { int count = 0; - for (Player p : Bukkit.getOnlinePlayers()) - if (filter.sendTo(p)) - { + for (Player p : Bukkit.getOnlinePlayers()) { + if (filter.sendTo(p)) { ChatAPI.createMessage(p).appendText(prefix).appendMessage(message).send(); count++; } - if (filter.sendTo(Bukkit.getConsoleSender())) - { + } + if (filter.sendTo(Bukkit.getConsoleSender())) { Bukkit.getConsoleSender().sendMessage(prefix + message.getRawMessage()); count++; } return count; } } - - /** This method will find the next parent caller and return their class name, omitting package names. - * - * @return the Name of the calling class. */ - private static final String getCaller() - { - StackTraceElement[] stackTrace = (new Exception()).getStackTrace(); - String classname = "Utils"; - for (int i = 0; classname.equals("Utils"); i++) - { - classname = Class_pattern.matcher(stackTrace[i].getClassName()).replaceAll(""); - } - return classname; - } - - /** This method will find the next parent caller and return their class name, omitting package names. - * + + /** + * This method will find the next parent caller and return their class name, omitting package names. + * * @param directCaller used to prevent this method from returning the caller itself. Null if supposed to be ignored. - * @return the name of the calling class. */ - public static final String getCaller(String... directCaller) - { + * + * @return the name of the calling class. + */ + public static final String getCaller(String... directCaller) { if (directCaller == null || directCaller.length == 0) return getCaller(); StackTraceElement[] stackTrace = (new Exception()).getStackTrace(); - String classname = "Utils"; - List callers = Arrays.asList(directCaller); - for (int i = 0; callers.contains(classname) || classname.equals("Utils"); i++) - { + String classname = "Utils"; + List callers = Arrays.asList(directCaller); + for (int i = 0; callers.contains(classname) || classname.equals("Utils"); i++) { classname = Class_pattern.matcher(stackTrace[i].getClassName()).replaceAll(""); } classname = NoDolarSign_pattern.matcher(classname).replaceAll(""); return classname; } - - /** Provides a uniform way of getting the date for all modules. - * - * @return The current date in the format "[dd-mm-yyyy hh:mm:ss]" */ - public static String getDate() - { + + /** + * Provides a uniform way of getting the date for all modules. + * + * @return The current date in the format "[dd-mm-yyyy hh:mm:ss]" + */ + public static String getDate() { Date date = new Date(System.currentTimeMillis()); return dateFormat.format(date); } - - /** Provides a uniform way of getting the (display)name of a @CommandSender. - * + + /** + * Provides a uniform way of getting the (display)name of a @CommandSender. + * * @param sender The @CommandSender to get the name of. - * @return The DisplayName of the @CommandSender or if not a @Player, the name in blue. */ - public static String getName(CommandSender sender) - { + * + * @return The DisplayName of the @CommandSender or if not a @Player, the name in blue. + */ + public static String getName(CommandSender sender) { if (sender instanceof Player) return ((Player) sender).getDisplayName(); else return "§9" + sender.getName(); } - - /** Provides a uniform way of getting the UUID of a @CommandSender. - * + + /** + * Provides a uniform way of getting the UUID of a @CommandSender. + * * @param sender The @CommandSender to get the UUID of. - * @return The UUID of the @CommandSender or if not a player, "CONSOLE" in blue. */ - public static String getID(CommandSender sender) - { + * + * @return The UUID of the @CommandSender or if not a player, "CONSOLE" in blue. + */ + public static String getID(CommandSender sender) { String id; if (sender instanceof Player) id = ((Player) sender).getUniqueId().toString(); @@ -179,25 +174,25 @@ public final class Utils id = "CONSOLE"; return id; } - - /** Checks if the string is a UUID. - * + + /** + * Checks if the string is a UUID. + * * @param toCheck String to check. + * * @return if the string is a UUID. */ - public static boolean isUUID(String toCheck) - { - return UUID_pattern.matcher(toCheck).matches(); + public static boolean isUUID(String toCheck) { + return UUID_pattern.matcher(toCheck).matches(); } - + public static void run(Runnable r) { run(r, 0); } - + public static void run(Runnable r, int delay) { Bukkit.getScheduler().scheduleSyncDelayedTask(ModuleLoader.getPlugin(), r, delay); } - - - + + } diff --git a/src/main/java/com/redstoner/misc/VersionHelper.java b/src/main/java/com/redstoner/misc/VersionHelper.java index e4a9403..6cfc872 100644 --- a/src/main/java/com/redstoner/misc/VersionHelper.java +++ b/src/main/java/com/redstoner/misc/VersionHelper.java @@ -1,27 +1,30 @@ package com.redstoner.misc; -import java.lang.annotation.Annotation; - import com.redstoner.annotations.Version; import com.redstoner.exceptions.MissingVersionException; -/** This class can be used to compare modules against the loader version or against each other to prevent dependency issues. - * - * @author Pepich */ -@Version(major = 2, minor = 1, revision = 3, compatible = 0) -public final class VersionHelper -{ - private VersionHelper() - {} - - /** Checks two classes versions for compatibility. - * - * @param base The API to compare to. +import java.lang.annotation.Annotation; + +/** + * This class can be used to compare modules against the loader version or against each other to prevent dependency issues. + * + * @author Pepich + */ +@Version (major = 2, minor = 1, revision = 3, compatible = 0) +public final class VersionHelper { + private VersionHelper() {} + + /** + * Checks two classes versions for compatibility. + * + * @param base The API to compare to. * @param module The module to compare. + * * @return true, when the module is up to date with the API, or the API supports outdated modules. - * @throws MissingVersionException When one of the parameters is not annotated with a @Version annotation. */ - public static boolean isCompatible(Class api, Class module) throws MissingVersionException - { + * + * @throws MissingVersionException When one of the parameters is not annotated with a @Version annotation. + */ + public static boolean isCompatible(Class api, Class module) throws MissingVersionException { if (!api.isAnnotationPresent(Version.class)) throw new MissingVersionException("The API is not annotated with a version."); if (!module.isAnnotationPresent(Version.class)) @@ -30,120 +33,129 @@ public final class VersionHelper Version moduleVersion = module.getAnnotation(Version.class); return isCompatible(apiVersion, moduleVersion); } - - /** Checks two classes versions for compatibility. - * - * @param base The API to compare to. + + /** + * Checks two versions for compatibility. + * + * @param base The API version to compare to. + * @param module The module version to compare. + * + * @return true, when the module is up to date with the API, or the API supports outdated modules. + */ + public static boolean isCompatible(Version apiVersion, Version moduleVersion) { + if (apiVersion.major() >= moduleVersion.compatible()) + return true; + if (apiVersion.compatible() == -1) + return false; + if (apiVersion.compatible() <= moduleVersion.major()) + return true; + return false; + } + + /** + * Checks two classes versions for compatibility. + * + * @param base The API to compare to. * @param module The module to compare. + * * @return true, when the module is up to date with the API, or the API supports outdated modules. - * @throws MissingVersionException When one of the parameters is not annotated with a @Version annotation. */ - public static boolean isCompatible(Version apiVersion, Class module) throws MissingVersionException - { + * + * @throws MissingVersionException When one of the parameters is not annotated with a @Version annotation. + */ + public static boolean isCompatible(Version apiVersion, Class module) throws MissingVersionException { if (!module.isAnnotationPresent(Version.class)) throw new MissingVersionException("The module is not annotated with a version."); Version moduleVersion = module.getAnnotation(Version.class); return isCompatible(apiVersion, moduleVersion); } - - /** Checks two classes versions for compatibility. - * - * @param base The API to compare to. + + /** + * Checks two classes versions for compatibility. + * + * @param base The API to compare to. * @param module The module to compare. + * * @return true, when the module is up to date with the API, or the API supports outdated modules. - * @throws MissingVersionException When one of the parameters is not annotated with a @Version annotation. */ - public static boolean isCompatible(Class api, Version moduleVersion) throws MissingVersionException - { + * + * @throws MissingVersionException When one of the parameters is not annotated with a @Version annotation. + */ + public static boolean isCompatible(Class api, Version moduleVersion) throws MissingVersionException { if (!api.isAnnotationPresent(Version.class)) throw new MissingVersionException("The API is not annotated with a version."); Version apiVersion = api.getAnnotation(Version.class); return isCompatible(apiVersion, moduleVersion); } - - /** Checks two versions for compatibility. - * - * @param base The API version to compare to. - * @param module The module version to compare. - * @return true, when the module is up to date with the API, or the API supports outdated modules. */ - public static boolean isCompatible(Version apiVersion, Version moduleVersion) - { - if (apiVersion.major() >= moduleVersion.compatible()) - return true; - if (apiVersion.compatible() == -1) - return false; - if (apiVersion.compatible() <= moduleVersion.major()) - return true; - return false; - } - - /** Returns the version of a given class as a String. - * + + /** + * Returns the version of a given class as a String. + * * @param clazz The class to grab the version number from. + * * @return The version number of the class in format major.minor.revision.compatible. - * @throws MissingVersionException If the class is not annotated with @Version. */ - public static String getVersion(Class clazz) throws MissingVersionException - { + * + * @throws MissingVersionException If the class is not annotated with @Version. + */ + public static String getVersion(Class clazz) throws MissingVersionException { if (!clazz.isAnnotationPresent(Version.class)) throw new MissingVersionException("The given class is not associated with a version."); Version ver = clazz.getAnnotation(Version.class); return getString(ver); } - - /** Returns the String representation of a version. - * + + /** + * Returns the String representation of a version. + * * @param ver The version to be represented. - * @return The String representation. */ - public static String getString(Version ver) - { + * + * @return The String representation. + */ + public static String getString(Version ver) { return ver.major() + "." + ver.minor() + "." + ver.revision() + "." + ver.compatible(); } - - public static Version getVersion(String ver) - { + + public static Version getVersion(String ver) { String[] raw = ver.split("\\."); if (raw.length != 4) return null; return VersionHelper.create(Integer.parseInt(raw[0]), Integer.parseInt(raw[1]), Integer.parseInt(raw[2]), - Integer.parseInt(raw[3])); + Integer.parseInt(raw[3]) + ); } - - /** This method creates a new Version to use for compatibility checks. - * - * @param major The major version - * @param minor The minor version - * @param revision The revision + + /** + * This method creates a new Version to use for compatibility checks. + * + * @param major The major version + * @param minor The minor version + * @param revision The revision * @param compatible The compatibility tag - * @return */ - public static Version create(int major, int minor, int revision, int compatible) - { - return new Version() - { + * + * @return + */ + public static Version create(int major, int minor, int revision, int compatible) { + return new Version() { @Override - public Class annotationType() - { + public Class annotationType() { return Version.class; } - + @Override - public int revision() - { + public int revision() { return revision; } - + @Override - public int minor() - { + public int minor() { return minor; } - + @Override - public int major() - { + public int major() { return major; } - + @Override - public int compatible() - { + public int compatible() { return compatible; } }; diff --git a/src/main/java/com/redstoner/misc/mysql/Config.java b/src/main/java/com/redstoner/misc/mysql/Config.java index 519b20a..b88b0c2 100644 --- a/src/main/java/com/redstoner/misc/mysql/Config.java +++ b/src/main/java/com/redstoner/misc/mysql/Config.java @@ -1,215 +1,170 @@ package com.redstoner.misc.mysql; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - +import com.redstoner.exceptions.NonSaveableConfigException; +import com.redstoner.misc.Main; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; -import com.redstoner.exceptions.NonSaveableConfigException; -import com.redstoner.misc.Main; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.PrintWriter; +import java.util.*; +import java.util.Map.Entry; -public class Config -{ - private File file; +public class Config { + private File file; private JSONObject config; private JSONParser parser; - - public Config() - { + + public Config() { file = null; parser = new JSONParser(); config = new JSONObject(); } - - public Config(JSONObject config) - { + + public Config(JSONObject config) { this.file = null; this.parser = new JSONParser(); this.config = config; } - - private Config(File file) throws IOException, ParseException - { + + private Config(File file) throws IOException, ParseException { this.file = file; parser = new JSONParser(); - if (file.exists()) - { + if (file.exists()) { config = loadConfig(file); - } - else - { + } else { config = new JSONObject(); } } - - public static final Config getConfig(String fileName) throws IOException, ParseException - { - return new Config(new File(Main.plugin.getDataFolder(), fileName)); - } - - public static final Config getConfig(File file) throws IOException, ParseException - { - return new Config(file); - } - - private JSONObject loadConfig(File file) throws IOException, ParseException - { + + private JSONObject loadConfig(File file) throws IOException, ParseException { FileReader reader = new FileReader(file); JSONObject object = (JSONObject) parser.parse(reader); reader.close(); return object; } - + + public static final Config getConfig(String fileName) throws IOException, ParseException { + return new Config(new File(Main.plugin.getDataFolder(), fileName)); + } + + public static final Config getConfig(File file) throws IOException, ParseException { + return new Config(file); + } + @Override - public String toString() - { + public String toString() { return config.toJSONString(); } - - public JSONObject asObject() - { + + public JSONObject asObject() { return config; } - - public void save() throws IOException, NonSaveableConfigException - { - if (file == null) - { + + public void save() throws IOException, NonSaveableConfigException { + if (file == null) { throw new NonSaveableConfigException(); } PrintWriter writer = new PrintWriter(file); writer.write(config.toJSONString()); writer.close(); } - - public void refresh() throws IOException, ParseException, NonSaveableConfigException - { - if (file == null) - { + + public void refresh() throws IOException, ParseException, NonSaveableConfigException { + if (file == null) { throw new NonSaveableConfigException(); } loadConfig(file); } - - public void setFile(String fileName) - { + + public void setFile(String fileName) { file = new File(Main.plugin.getDataFolder(), fileName); } - - public void setFile(File file) - { + + public void setFile(File file) { this.file = file; } - - @SuppressWarnings("unchecked") - public void put(String key, String value) - { + + @SuppressWarnings ("unchecked") + public void put(String key, String value) { config.put(key, value); } - - @SuppressWarnings("unchecked") - public void put(String key, List value) - { + + @SuppressWarnings ("unchecked") + public void put(String key, List value) { JSONArray array = new JSONArray(); - for (String entry : value) - { + for (String entry : value) { array.add(entry); } config.put(key, array); } - - @SuppressWarnings("unchecked") - public void putArray(String key, JSONArray value) - { + + @SuppressWarnings ("unchecked") + public void putArray(String key, JSONArray value) { config.put(key, value); } - - @SuppressWarnings("unchecked") - public void put(String key, Map value) - { + + @SuppressWarnings ("unchecked") + public void put(String key, Map value) { JSONObject object = new JSONObject(); - for (String valKey : value.keySet()) - { + for (String valKey : value.keySet()) { String valVal = value.get(valKey); object.put(valKey, valVal); } config.put(key, object); } - - @SuppressWarnings("unchecked") - public void put(String key, JSONObject value) - { + + @SuppressWarnings ("unchecked") + public void put(String key, JSONObject value) { config.put(key, value); } - - @SuppressWarnings("unchecked") - public void putAll(Map entry) - { - for (String key : entry.keySet()) - { + + @SuppressWarnings ("unchecked") + public void putAll(Map entry) { + for (String key : entry.keySet()) { String value = entry.get(key); config.put(key, value); } } - - public boolean containsKey(String key) - { - return config.containsKey(key); - } - - public String get(String key) - { - if (containsKey(key)) - { + + public String get(String key) { + if (containsKey(key)) { Object value = config.get(key); - if (value instanceof String) - { + if (value instanceof String) { return (String) value; } } return null; } - - public String getOrDefault(String key, String defaultValue) - { - if (containsKey(key)) - { + + public boolean containsKey(String key) { + return config.containsKey(key); + } + + public String getOrDefault(String key, String defaultValue) { + if (containsKey(key)) { Object value = config.get(key); - if (value instanceof String) - { + if (value instanceof String) { return (String) value; } return null; - } - else - { + } else { return defaultValue; } } - - @SuppressWarnings("unchecked") - public List getList(String key) - { - if (containsKey(key)) - { + + @SuppressWarnings ("unchecked") + public List getList(String key) { + if (containsKey(key)) { Object value = config.get(key); - if (value instanceof JSONArray) - { - JSONArray array = (JSONArray) value; + if (value instanceof JSONArray) { + JSONArray array = (JSONArray) value; List output = new ArrayList(); - for (String entry : (String[]) array.toArray(new String[0])) - { + for (String entry : (String[]) array.toArray(new String[0])) { output.add(entry); } return output; @@ -217,34 +172,27 @@ public class Config } return null; } - - public JSONArray getArray(String key) - { - if (containsKey(key)) - { + + public JSONArray getArray(String key) { + if (containsKey(key)) { Object value = config.get(key); - if (value instanceof JSONArray) - { + if (value instanceof JSONArray) { JSONArray array = (JSONArray) value; return array; } } return null; } - - public Map getMap(String key) - { - if (containsKey(key)) - { + + public Map getMap(String key) { + if (containsKey(key)) { Object value = config.get(key); - if (value instanceof JSONObject) - { + if (value instanceof JSONObject) { JSONObject object = (JSONObject) value; - @SuppressWarnings("unchecked") + @SuppressWarnings ("unchecked") Set> entrySet = object.entrySet(); Map output = new HashMap(); - for (Map.Entry entry : entrySet) - { + for (Map.Entry entry : entrySet) { output.put(entry.getKey(), entry.getValue()); } return output; @@ -252,29 +200,24 @@ public class Config } return null; } - - public JSONObject getObject(String key) - { - if (containsKey(key)) - { + + public JSONObject getObject(String key) { + if (containsKey(key)) { Object value = config.get(key); - if (value instanceof JSONObject) - { + if (value instanceof JSONObject) { JSONObject object = (JSONObject) value; return object; } } return null; } - - public void remove(String key) - { + + public void remove(String key) { config.remove(key); } - - @SuppressWarnings("unchecked") - public Set> getAll() - { + + @SuppressWarnings ("unchecked") + public Set> getAll() { return config.entrySet(); } } diff --git a/src/main/java/com/redstoner/misc/mysql/JSONManager.java b/src/main/java/com/redstoner/misc/mysql/JSONManager.java index ae248d5..6084e8d 100644 --- a/src/main/java/com/redstoner/misc/mysql/JSONManager.java +++ b/src/main/java/com/redstoner/misc/mysql/JSONManager.java @@ -1,107 +1,80 @@ package com.redstoner.misc.mysql; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.io.PrintWriter; -import java.io.Serializable; -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import com.redstoner.misc.Main; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; -import com.redstoner.misc.Main; +import java.io.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; -public class JSONManager -{ - public static Map getConfiguration(String fileName) - { +public class JSONManager { + public static Map getConfiguration(String fileName) { File file = new File(Main.plugin.getDataFolder(), fileName); - if (!file.exists()) - { - try - { + if (!file.exists()) { + try { PrintWriter writer = new PrintWriter(file.getAbsolutePath(), "UTF-8"); writer.println("{}"); writer.close(); - } - catch (FileNotFoundException | UnsupportedEncodingException e) - { + } catch (FileNotFoundException | UnsupportedEncodingException e) { e.printStackTrace(); } } - try - { + try { return loadMap(file); - } - catch (IOException | ParseException e) - { + } catch (IOException | ParseException e) { e.printStackTrace(); return null; } } - - public static void saveConfiguration(Map config, String fileName) - { - try - { - saveMap(new File(Main.plugin.getDataFolder(), fileName), config); + + public static Map loadMap(File file) throws IOException, ParseException { + FileReader reader = new FileReader(file); + JSONObject map = (JSONObject) new JSONParser().parse(reader); + Map entries = new HashMap<>(); + for (Object o : map.keySet()) { + entries.put((Serializable) o, (Serializable) map.get(o)); } - catch (IOException e) - { + return entries; + } + + public static void saveConfiguration(Map config, String fileName) { + try { + saveMap(new File(Main.plugin.getDataFolder(), fileName), config); + } catch (IOException e) { e.printStackTrace(); } } - - @SuppressWarnings("unchecked") - public static void saveList(File file, List entries) throws IOException - { + + @SuppressWarnings ("unchecked") + public static void saveMap(File file, Map entries) throws IOException { + JSONObject map = new JSONObject(); + map.putAll(entries); + FileWriter writer = new FileWriter(file); + writer.write(map.toJSONString()); + writer.close(); + } + + @SuppressWarnings ("unchecked") + public static void saveList(File file, List entries) throws IOException { JSONArray array = new JSONArray(); array.addAll(entries); FileWriter writer = new FileWriter(file); writer.write(array.toJSONString()); writer.close(); } - - public static List loadList(File file) throws IOException, ParseException - { - FileReader read = new FileReader(file); + + public static List loadList(File file) throws IOException, ParseException { + FileReader read = new FileReader(file); List entries = new ArrayList<>(); - JSONArray array = (JSONArray) new JSONParser().parse(read); - for (Object o : array) - { + JSONArray array = (JSONArray) new JSONParser().parse(read); + for (Object o : array) { entries.add((Serializable) o); } return entries; } - - @SuppressWarnings("unchecked") - public static void saveMap(File file, Map entries) throws IOException - { - JSONObject map = new JSONObject(); - map.putAll(entries); - FileWriter writer = new FileWriter(file); - writer.write(map.toJSONString()); - writer.close(); - } - - public static Map loadMap(File file) throws IOException, ParseException - { - FileReader reader = new FileReader(file); - JSONObject map = (JSONObject) new JSONParser().parse(reader); - Map entries = new HashMap<>(); - for (Object o : map.keySet()) - { - entries.put((Serializable) o, (Serializable) map.get(o)); - } - return entries; - } } diff --git a/src/main/java/com/redstoner/misc/mysql/MysqlHandler.java b/src/main/java/com/redstoner/misc/mysql/MysqlHandler.java index 909d276..d76227a 100644 --- a/src/main/java/com/redstoner/misc/mysql/MysqlHandler.java +++ b/src/main/java/com/redstoner/misc/mysql/MysqlHandler.java @@ -1,113 +1,86 @@ package com.redstoner.misc.mysql; +import com.redstoner.misc.Main; +import com.redstoner.misc.mysql.elements.MysqlDatabase; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.json.simple.parser.ParseException; + import java.io.File; import java.io.IOException; import java.io.Serializable; -import java.sql.Connection; -import java.sql.DatabaseMetaData; -import java.sql.DriverManager; -import java.sql.ResultSet; -import java.sql.SQLException; +import java.sql.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.json.simple.parser.ParseException; - -import com.redstoner.misc.Main; -import com.redstoner.misc.mysql.elements.MysqlDatabase; - -public class MysqlHandler -{ +public class MysqlHandler { public static MysqlHandler INSTANCE; - private String url, username, password; - - public MysqlHandler(String hostname, int port, String username, String password) - { + private String url, username, password; + + public MysqlHandler(String hostname, int port, String username, String password) { this.url = "jdbc:mysql://" + hostname + ":" + port + "/"; this.username = username; this.password = password; } - - public static void init() - { - Map mysqlCredentials = new HashMap<>(); - File mysqlCredentialsFile = new File(Main.plugin.getDataFolder(), "mysqlCredentials.json"); - if (mysqlCredentialsFile.exists()) - { - try - { + + public static void init() { + Map mysqlCredentials = new HashMap<>(); + File mysqlCredentialsFile = new File(Main.plugin.getDataFolder(), "mysqlCredentials.json"); + if (mysqlCredentialsFile.exists()) { + try { mysqlCredentials = JSONManager.loadMap(mysqlCredentialsFile); - } - catch (IOException | ParseException e) - { + } catch (IOException | ParseException e) { e.printStackTrace(); } - } - else - { + } else { Bukkit.getConsoleSender().sendMessage( ChatColor.RED + "MySQL config does not exist, creating an example one, things might (will) break!"); mysqlCredentials.put("hostname", "localhost"); mysqlCredentials.put("port", "3306"); mysqlCredentials.put("username", "your username here"); mysqlCredentials.put("password", "your password here"); - try - { + try { JSONManager.saveMap(mysqlCredentialsFile, mysqlCredentials); - } - catch (IOException e) - { + } catch (IOException e) { e.printStackTrace(); } } String hostname = (String) mysqlCredentials.get("hostname"); - int port = Integer.valueOf((String) mysqlCredentials.get("port")); + int port = Integer.valueOf((String) mysqlCredentials.get("port")); String username = (String) mysqlCredentials.get("username"); String password = (String) mysqlCredentials.get("password"); INSTANCE = new MysqlHandler(hostname, port, username, password); } - - private Connection getConnection(String databaseName) throws IllegalStateException - { + + public MysqlDatabase getDatabase(String databaseName) { + return new MysqlDatabase(getConnection(databaseName)); + } + + private Connection getConnection(String databaseName) throws IllegalStateException { Connection connection = null; - try - { + try { connection = DriverManager.getConnection(url + databaseName, username, password); - } - catch (SQLException e) - { + } catch (SQLException e) { throw new IllegalStateException("Cannot connect to the database!", e); } return connection; } - - public MysqlDatabase getDatabase(String databaseName) - { - return new MysqlDatabase(getConnection(databaseName)); - } - - public List getDatabases() - { - try - { - List databases = new ArrayList<>(); - Connection connection = DriverManager.getConnection(url.substring(0, url.length()), username, password); - DatabaseMetaData metadata = connection.getMetaData(); - ResultSet queryResults = metadata.getCatalogs(); - while (queryResults.next()) - { + + public List getDatabases() { + try { + List databases = new ArrayList<>(); + Connection connection = DriverManager.getConnection(url.substring(0, url.length()), username, password); + DatabaseMetaData metadata = connection.getMetaData(); + ResultSet queryResults = metadata.getCatalogs(); + while (queryResults.next()) { String databaseName = queryResults.getString("TABLE_CAT"); databases.add(new MysqlDatabase(getConnection(databaseName))); } connection.close(); return databases; - } - catch (SQLException e) - { + } catch (SQLException e) { e.printStackTrace(); return null; } diff --git a/src/main/java/com/redstoner/misc/mysql/MysqlQueryHandler.java b/src/main/java/com/redstoner/misc/mysql/MysqlQueryHandler.java index f89a08a..df46cab 100644 --- a/src/main/java/com/redstoner/misc/mysql/MysqlQueryHandler.java +++ b/src/main/java/com/redstoner/misc/mysql/MysqlQueryHandler.java @@ -1,29 +1,25 @@ package com.redstoner.misc.mysql; -import java.sql.CallableStatement; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; +import java.sql.*; public class MysqlQueryHandler { public static ResultSet queryResult(Connection connection, String query) { try { Statement statement = connection.createStatement(); - ResultSet results = statement.executeQuery(query); - + ResultSet results = statement.executeQuery(query); + return results; } catch (SQLException e) { e.printStackTrace(); return null; } } - + public static boolean queryNoResult(Connection connection, String query) { try { CallableStatement statement = connection.prepareCall(query); statement.execute(); - + return true; } catch (SQLException e) { e.printStackTrace(); diff --git a/src/main/java/com/redstoner/misc/mysql/elements/ConstraintOperator.java b/src/main/java/com/redstoner/misc/mysql/elements/ConstraintOperator.java index 45cb33c..1e8d523 100644 --- a/src/main/java/com/redstoner/misc/mysql/elements/ConstraintOperator.java +++ b/src/main/java/com/redstoner/misc/mysql/elements/ConstraintOperator.java @@ -2,7 +2,7 @@ package com.redstoner.misc.mysql.elements; public enum ConstraintOperator { LESS_THAN, GREATER_THAN, EQUAL, NOT_EQUAL, LESS_THAN_OR_EQUAL, GREATER_THAN_OR_EQUAL; - + public String toString() { switch (this) { case LESS_THAN: diff --git a/src/main/java/com/redstoner/misc/mysql/elements/MysqlConstraint.java b/src/main/java/com/redstoner/misc/mysql/elements/MysqlConstraint.java index d651344..8b99d12 100644 --- a/src/main/java/com/redstoner/misc/mysql/elements/MysqlConstraint.java +++ b/src/main/java/com/redstoner/misc/mysql/elements/MysqlConstraint.java @@ -3,7 +3,7 @@ package com.redstoner.misc.mysql.elements; public class MysqlConstraint { private String fieldName, value; private ConstraintOperator operator; - + public MysqlConstraint(String fieldName, ConstraintOperator operator, String value) { this.fieldName = fieldName; this.operator = operator; diff --git a/src/main/java/com/redstoner/misc/mysql/elements/MysqlDatabase.java b/src/main/java/com/redstoner/misc/mysql/elements/MysqlDatabase.java index 91c0fe4..3f1c288 100644 --- a/src/main/java/com/redstoner/misc/mysql/elements/MysqlDatabase.java +++ b/src/main/java/com/redstoner/misc/mysql/elements/MysqlDatabase.java @@ -1,5 +1,7 @@ package com.redstoner.misc.mysql.elements; +import com.redstoner.misc.mysql.MysqlQueryHandler; + import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.ResultSet; @@ -7,84 +9,82 @@ import java.sql.SQLException; import java.util.ArrayList; import java.util.List; -import com.redstoner.misc.mysql.MysqlQueryHandler; - public class MysqlDatabase { private Connection connection; - + public MysqlDatabase(Connection connection) { this.connection = connection; } - - public String getName() { - try { - return connection.getCatalog(); - } catch (SQLException e) { - e.printStackTrace(); - return null; - } - } - + public MysqlTable getTable(String name) { return new MysqlTable(this, name); } - + public boolean createTable(String name, MysqlField... description) { return MysqlQueryHandler.queryNoResult(connection, "CREATE TABLE `" + name + "` " + getDescription(description) + ";"); } - + + private String getDescription(MysqlField... description) { + String desc = "("; + + for (int i = 0; i < description.length; i++) { + String nil = ""; + + if (description[i].canBeNull()) { + nil = " NOT NULL"; + } + + desc += "`" + description[i].getName() + "` " + description[i].getType().getName() + nil; + + if (i < description.length - 1) { + desc += ","; + } + } + + desc += ")"; + + return desc; + } + public boolean createTableIfNotExists(String name, MysqlField... description) { return MysqlQueryHandler.queryNoResult(connection, "CREATE TABLE IF NOT EXISTS `" + name + "` " + getDescription(description) + ";"); } - + public boolean dropTable(String name) { return MysqlQueryHandler.queryNoResult(connection, "DROP TABLE `" + name + "`;"); } - + public boolean drop() { return MysqlQueryHandler.queryNoResult(connection, "DROP DATABASE `" + getName() + "`;"); } - + + public String getName() { + try { + return connection.getCatalog(); + } catch (SQLException e) { + e.printStackTrace(); + return null; + } + } + public List getTables() { try { - List tables = new ArrayList<>(); - DatabaseMetaData metadata = connection.getMetaData(); - ResultSet queryResults = metadata.getTables(null, null, "%", null); - + List tables = new ArrayList<>(); + DatabaseMetaData metadata = connection.getMetaData(); + ResultSet queryResults = metadata.getTables(null, null, "%", null); + while (queryResults.next()) { tables.add(new MysqlTable(this, queryResults.getString(3))); } - + return tables; } catch (SQLException e) { e.printStackTrace(); return null; } } - + protected Connection getConnection() { return connection; } - - private String getDescription(MysqlField... description) { - String desc = "("; - - for (int i = 0; i < description.length; i++) { - String nil = ""; - - if (description[i].canBeNull()) { - nil = " NOT NULL"; - } - - desc += "`" + description[i].getName() + "` " + description[i].getType().getName() + nil; - - if (i < description.length - 1) { - desc += ","; - } - } - - desc += ")"; - - return desc; - } } diff --git a/src/main/java/com/redstoner/misc/mysql/elements/MysqlField.java b/src/main/java/com/redstoner/misc/mysql/elements/MysqlField.java index 61cba2e..68b6fcc 100644 --- a/src/main/java/com/redstoner/misc/mysql/elements/MysqlField.java +++ b/src/main/java/com/redstoner/misc/mysql/elements/MysqlField.java @@ -3,30 +3,30 @@ package com.redstoner.misc.mysql.elements; import com.redstoner.misc.mysql.types.MysqlType; public class MysqlField { - private String name; + private String name; private MysqlType type; - private boolean canBeNull; - + private boolean canBeNull; + public MysqlField(String name, MysqlType type, boolean canBeNull) { this.name = name; this.type = type; this.canBeNull = canBeNull; } - + public MysqlField(String name, String type, boolean canBeNull) { this.name = name; this.type = MysqlType.getTypeFromString(type); this.canBeNull = canBeNull; } - + public String getName() { return name; } - + public MysqlType getType() { return type; } - + public boolean canBeNull() { return canBeNull; } diff --git a/src/main/java/com/redstoner/misc/mysql/elements/MysqlResult.java b/src/main/java/com/redstoner/misc/mysql/elements/MysqlResult.java index 6db0769..1b4f246 100644 --- a/src/main/java/com/redstoner/misc/mysql/elements/MysqlResult.java +++ b/src/main/java/com/redstoner/misc/mysql/elements/MysqlResult.java @@ -5,11 +5,11 @@ import java.sql.SQLException; public class MysqlResult { private ResultSet results; - + public MysqlResult(ResultSet results) { this.results = results; } - + public Object getObject(int columnIndex, Class type) throws SQLException { return results.getObject(columnIndex, type); } diff --git a/src/main/java/com/redstoner/misc/mysql/elements/MysqlTable.java b/src/main/java/com/redstoner/misc/mysql/elements/MysqlTable.java index 6656fcd..e6a7617 100644 --- a/src/main/java/com/redstoner/misc/mysql/elements/MysqlTable.java +++ b/src/main/java/com/redstoner/misc/mysql/elements/MysqlTable.java @@ -1,133 +1,113 @@ package com.redstoner.misc.mysql.elements; +import com.redstoner.misc.mysql.MysqlQueryHandler; + import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; -import com.redstoner.misc.mysql.MysqlQueryHandler; - -public class MysqlTable -{ +public class MysqlTable { private MysqlDatabase database; - private String name; - - public MysqlTable(MysqlDatabase database, String name) - { + private String name; + + public MysqlTable(MysqlDatabase database, String name) { this.database = database; this.name = name; } - - public String getName() - { + + public String getName() { return this.name; } - - public MysqlField[] describe() - { - try - { - List description = new ArrayList<>(); - DatabaseMetaData metadata = database.getConnection().getMetaData(); - ResultSet queryResults = metadata.getColumns(null, null, name, null); - while (queryResults.next()) - { - description.add(new MysqlField(queryResults.getString(4), - queryResults.getString(6).split(" ")[0] + "(" + queryResults.getString(7) + ")", - queryResults.getBoolean(11))); - } - return description.toArray(new MysqlField[0]); - } - catch (SQLException e) - { - e.printStackTrace(); - return null; - } - } - - public boolean insert(String... values) - { + + public boolean insert(String... values) { MysqlField[] description = describe(); - if (values.length > 0 && values.length == description.length) - { + if (values.length > 0 && values.length == description.length) { String val = "(\"" + String.join("\",\"", values) + "\")"; - return MysqlQueryHandler.queryNoResult(database.getConnection(), - "INSERT INTO `" + name + "` VALUES " + val + ";"); - } - else - { + return MysqlQueryHandler.queryNoResult( + database.getConnection(), + "INSERT INTO `" + name + "` VALUES " + val + ";" + ); + } else { return false; } } - - public Object[] get(String fieldName, MysqlConstraint... constraints) - { - ResultSet results = MysqlQueryHandler.queryResult(database.getConnection(), - "SELECT " + fieldName + " FROM `" + name + "`" + getConstraints(constraints) + ";"); - List resObj = new ArrayList<>(); - try - { - while (results.next()) - { - resObj.add(results.getObject(1)); + + public MysqlField[] describe() { + try { + List description = new ArrayList<>(); + DatabaseMetaData metadata = database.getConnection().getMetaData(); + ResultSet queryResults = metadata.getColumns(null, null, name, null); + while (queryResults.next()) { + description.add(new MysqlField( + queryResults.getString(4), + queryResults.getString(6).split(" ")[0] + "(" + queryResults.getString(7) + ")", + queryResults.getBoolean(11) + )); } - } - catch (SQLException e) - { + return description.toArray(new MysqlField[0]); + } catch (SQLException e) { e.printStackTrace(); - return new Object[0]; + return null; } - return resObj.toArray(new Object[0]); } - - public Object[] get(String statement) - { - ResultSet results = MysqlQueryHandler.queryResult(database.getConnection(), statement); + + public Object[] get(String fieldName, MysqlConstraint... constraints) { + ResultSet results = MysqlQueryHandler.queryResult( + database.getConnection(), + "SELECT " + fieldName + " FROM `" + name + "`" + getConstraints(constraints) + ";" + ); List resObj = new ArrayList<>(); - try - { - while (results.next()) - { + try { + while (results.next()) { resObj.add(results.getObject(1)); } - } - catch (SQLException e) - { + } catch (SQLException e) { e.printStackTrace(); return new Object[0]; } return resObj.toArray(new Object[0]); } - - public boolean delete(MysqlConstraint... constraints) - { - return MysqlQueryHandler.queryNoResult(database.getConnection(), - "DELETE FROM `" + name + "`" + getConstraints(constraints) + ";"); - } - - public boolean drop() - { - return MysqlQueryHandler.queryNoResult(database.getConnection(), "DROP TABLE `" + name + "`;"); - } - - private String getConstraints(MysqlConstraint... constraints) - { + + private String getConstraints(MysqlConstraint... constraints) { String cons = ""; - if (constraints.length > 0) - { + if (constraints.length > 0) { cons += " WHERE "; - for (int i = 0; i < constraints.length; i++) - { + for (int i = 0; i < constraints.length; i++) { MysqlConstraint constraint = constraints[i]; cons += constraint.getFieldName() + constraint.getOperator().toString() + "\"" + constraint.getValue() - + "\""; - if (i < constraints.length - 1) - { + + "\""; + if (i < constraints.length - 1) { cons += " AND "; } } } return cons; } + + public Object[] get(String statement) { + ResultSet results = MysqlQueryHandler.queryResult(database.getConnection(), statement); + List resObj = new ArrayList<>(); + try { + while (results.next()) { + resObj.add(results.getObject(1)); + } + } catch (SQLException e) { + e.printStackTrace(); + return new Object[0]; + } + return resObj.toArray(new Object[0]); + } + + public boolean delete(MysqlConstraint... constraints) { + return MysqlQueryHandler.queryNoResult( + database.getConnection(), + "DELETE FROM `" + name + "`" + getConstraints(constraints) + ";" + ); + } + + public boolean drop() { + return MysqlQueryHandler.queryNoResult(database.getConnection(), "DROP TABLE `" + name + "`;"); + } } diff --git a/src/main/java/com/redstoner/misc/mysql/types/MysqlType.java b/src/main/java/com/redstoner/misc/mysql/types/MysqlType.java index 86413f9..4a1c32f 100644 --- a/src/main/java/com/redstoner/misc/mysql/types/MysqlType.java +++ b/src/main/java/com/redstoner/misc/mysql/types/MysqlType.java @@ -1,45 +1,21 @@ package com.redstoner.misc.mysql.types; -import com.redstoner.misc.mysql.types.date.Date; -import com.redstoner.misc.mysql.types.date.DateTime; -import com.redstoner.misc.mysql.types.date.Time; -import com.redstoner.misc.mysql.types.date.TimeStamp; -import com.redstoner.misc.mysql.types.date.Year; -import com.redstoner.misc.mysql.types.number.BigInt; -import com.redstoner.misc.mysql.types.number.Decimal; +import com.redstoner.misc.mysql.types.date.*; import com.redstoner.misc.mysql.types.number.Double; import com.redstoner.misc.mysql.types.number.Float; -import com.redstoner.misc.mysql.types.number.Int; -import com.redstoner.misc.mysql.types.number.MediumInt; -import com.redstoner.misc.mysql.types.number.SmallInt; -import com.redstoner.misc.mysql.types.number.TinyInt; -import com.redstoner.misc.mysql.types.text.Blob; -import com.redstoner.misc.mysql.types.text.Char; +import com.redstoner.misc.mysql.types.number.*; import com.redstoner.misc.mysql.types.text.Enum; -import com.redstoner.misc.mysql.types.text.LongBlob; -import com.redstoner.misc.mysql.types.text.LongText; -import com.redstoner.misc.mysql.types.text.MediumBlob; -import com.redstoner.misc.mysql.types.text.MediumText; -import com.redstoner.misc.mysql.types.text.Set; -import com.redstoner.misc.mysql.types.text.Text; -import com.redstoner.misc.mysql.types.text.TinyText; -import com.redstoner.misc.mysql.types.text.VarChar; +import com.redstoner.misc.mysql.types.text.*; -public abstract class MysqlType -{ - public abstract String getName(); - - public static MysqlType getTypeFromString(String type) - { +public abstract class MysqlType { + public static MysqlType getTypeFromString(String type) { String[] splitType = type.split("\\("); - String toSwitch = splitType[0].toUpperCase(); - String value = ""; - if (type.contains("(") && type.endsWith(")")) - { + String toSwitch = splitType[0].toUpperCase(); + String value = ""; + if (type.contains("(") && type.endsWith(")")) { value = splitType[1].substring(0, splitType[1].length() - 1); } - switch (toSwitch) - { + switch (toSwitch) { case "CHAR": return new Char(Integer.valueOf(value)); case "ENUM": @@ -93,4 +69,6 @@ public abstract class MysqlType } return null; } + + public abstract String getName(); } diff --git a/src/main/java/com/redstoner/misc/mysql/types/number/Int.java b/src/main/java/com/redstoner/misc/mysql/types/number/Int.java index 4256f7b..7b2fbfd 100644 --- a/src/main/java/com/redstoner/misc/mysql/types/number/Int.java +++ b/src/main/java/com/redstoner/misc/mysql/types/number/Int.java @@ -4,11 +4,11 @@ import com.redstoner.misc.mysql.types.MysqlType; public class Int extends MysqlType { private int maxSize; - + public Int(int maxSize) { this.maxSize = maxSize; } - + @Override public String getName() { return "INT(" + maxSize + ")"; diff --git a/src/main/java/com/redstoner/misc/mysql/types/text/Char.java b/src/main/java/com/redstoner/misc/mysql/types/text/Char.java index ece068c..4d4a938 100644 --- a/src/main/java/com/redstoner/misc/mysql/types/text/Char.java +++ b/src/main/java/com/redstoner/misc/mysql/types/text/Char.java @@ -4,11 +4,11 @@ import com.redstoner.misc.mysql.types.MysqlType; public class Char extends MysqlType { private int size; - + public Char(int size) { this.size = size; } - + @Override public String getName() { return "CHAR(" + size + ")"; diff --git a/src/main/java/com/redstoner/misc/mysql/types/text/Enum.java b/src/main/java/com/redstoner/misc/mysql/types/text/Enum.java index e68476d..6200292 100644 --- a/src/main/java/com/redstoner/misc/mysql/types/text/Enum.java +++ b/src/main/java/com/redstoner/misc/mysql/types/text/Enum.java @@ -4,24 +4,24 @@ import com.redstoner.misc.mysql.types.MysqlType; public class Enum extends MysqlType { private String[] possibleValues; - + public Enum(String... possibleValues) { this.possibleValues = possibleValues; } - + @Override public String getName() { String name = "ENUM("; - + for (int i = 0; i < possibleValues.length; i++) { name += "'" + possibleValues[i] + "'"; - + if (i != possibleValues.length - 1) { name += ","; } } - + return name + ")"; } - + } diff --git a/src/main/java/com/redstoner/misc/mysql/types/text/Set.java b/src/main/java/com/redstoner/misc/mysql/types/text/Set.java index 4e12ce6..f82f02b 100644 --- a/src/main/java/com/redstoner/misc/mysql/types/text/Set.java +++ b/src/main/java/com/redstoner/misc/mysql/types/text/Set.java @@ -4,24 +4,24 @@ import com.redstoner.misc.mysql.types.MysqlType; public class Set extends MysqlType { private String[] possibleValues; - + public Set(String... possibleValues) { this.possibleValues = possibleValues; } - + @Override public String getName() { String name = "SET("; - + for (int i = 0; i < possibleValues.length; i++) { name += "'" + possibleValues[i] + "'"; - + if (i != possibleValues.length - 1) { name += ","; } } - + return name + ")"; } - + } diff --git a/src/main/java/com/redstoner/misc/mysql/types/text/VarChar.java b/src/main/java/com/redstoner/misc/mysql/types/text/VarChar.java index cb28ad1..65b6416 100644 --- a/src/main/java/com/redstoner/misc/mysql/types/text/VarChar.java +++ b/src/main/java/com/redstoner/misc/mysql/types/text/VarChar.java @@ -4,11 +4,11 @@ import com.redstoner.misc.mysql.types.MysqlType; public class VarChar extends MysqlType { private int maxSize; - + public VarChar(int maxSize) { this.maxSize = maxSize; } - + @Override public String getName() { return "VARCHAR(" + maxSize + ")"; diff --git a/src/main/java/com/redstoner/modules/CoreModule.java b/src/main/java/com/redstoner/modules/CoreModule.java index 9f71557..77ca178 100644 --- a/src/main/java/com/redstoner/modules/CoreModule.java +++ b/src/main/java/com/redstoner/modules/CoreModule.java @@ -2,23 +2,22 @@ package com.redstoner.modules; import com.redstoner.annotations.Version; -/** This class shall be used for "CoreModules", which are acting on a lower level than modules and are also exempted from being disabled or reloaded on the go.
+/** + * This class shall be used for "CoreModules", which are acting on a lower level than modules and are also exempted from being disabled or reloaded on the go.
* Please note that CoreModules will not be known to the ModuleLoader itself!
* Examples are the ModuleLoader and the Debugger. - * - * @author Pepich */ -@Version(major = 2, minor = 0, revision = 0, compatible = -1) -public interface CoreModule extends Module -{ + * + * @author Pepich + */ +@Version (major = 2, minor = 0, revision = 0, compatible = -1) +public interface CoreModule extends Module { /** Core modules don't need to be enabled. */ @Override - public default boolean onEnable() - { + public default boolean onEnable() { return true; } - + /** Core modules don't need to be disabled. */ @Override - public default void onDisable() - {} + public default void onDisable() {} } diff --git a/src/main/java/com/redstoner/modules/Module.java b/src/main/java/com/redstoner/modules/Module.java index 1c89e15..67c1063 100644 --- a/src/main/java/com/redstoner/modules/Module.java +++ b/src/main/java/com/redstoner/modules/Module.java @@ -3,52 +3,51 @@ package com.redstoner.modules; import com.redstoner.annotations.Version; import com.redstoner.coremods.moduleLoader.ModuleLoader; -/** Interface for the Module class. Modules must always have an empty constructor to be invoked by the ModuleLoader. - * - * @author Pepich */ -@Version(major = 4, minor = 0, revision = 0, compatible = 0) -public interface Module -{ +/** + * Interface for the Module class. Modules must always have an empty constructor to be invoked by the ModuleLoader. + * + * @author Pepich + */ +@Version (major = 4, minor = 0, revision = 0, compatible = 0) +public interface Module { /** Will be called when the module gets enabled. */ - public default boolean onEnable() - { + public default boolean onEnable() { return true; } - - /** This methods gets called after all modules were enabled, please use this method to register commands and similar.
- * It will only get called if and only if the module was successfully enabled. */ - public default void postEnable() - {} - + + /** + * This methods gets called after all modules were enabled, please use this method to register commands and similar.
+ * It will only get called if and only if the module was successfully enabled. + */ + public default void postEnable() {} + /** Will be called when the module gets disabled. */ - public default void onDisable() - {} - - /** Gets called on registration of the module, when this option is selected for command registration - * - * @return The String used for the CommandManager to register the commands. */ - public default String getCommandString() - { + public default void onDisable() {} + + /** + * Gets called on registration of the module, when this option is selected for command registration + * + * @return The String used for the CommandManager to register the commands. + */ + public default String getCommandString() { return null; } - - public default ModuleLogger getLogger() - { - return ModuleLoader.getModuleLogger(this); - } - + /** This method gets run the very first time a module gets loaded. You can use this to set up file structures or background data. */ - public default void firstLoad() - {} - - /** This method gets run every time a module gets loaded and its version has changed. - * - * @param old The version of the previous module. */ - public default void migrate(Version old) - {} - - default void setPrefix(final String name) - { + public default void firstLoad() {} + + /** + * This method gets run every time a module gets loaded and its version has changed. + * + * @param old The version of the previous module. + */ + public default void migrate(Version old) {} + + default void setPrefix(final String name) { getLogger().setName(name); } + + public default ModuleLogger getLogger() { + return ModuleLoader.getModuleLogger(this); + } } diff --git a/src/main/java/com/redstoner/modules/ModuleLogger.java b/src/main/java/com/redstoner/modules/ModuleLogger.java index 11d71b6..b68343b 100644 --- a/src/main/java/com/redstoner/modules/ModuleLogger.java +++ b/src/main/java/com/redstoner/modules/ModuleLogger.java @@ -1,77 +1,63 @@ package com.redstoner.modules; -import org.bukkit.Bukkit; -import org.bukkit.command.CommandSender; - import com.redstoner.annotations.Version; - import net.nemez.chatapi.ChatAPI; import net.nemez.chatapi.click.Message; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; -@Version(major = 4, minor = 0, revision = 0, compatible = -1) -public class ModuleLogger -{ - public static final String PREFIX_WARN = "§8[§eWARN§8]:§7 "; +@Version (major = 4, minor = 0, revision = 0, compatible = -1) +public class ModuleLogger { + public static final String PREFIX_WARN = "§8[§eWARN§8]:§7 "; public static final String PREFIX_ERROR = "§8[§cERROR§8]:§7 "; - public static final String PREFIX_INFO = "§8[§fINFO§8]:§7 "; - + public static final String PREFIX_INFO = "§8[§fINFO§8]:§7 "; + private String name; - - public ModuleLogger(final String name) - { + + public ModuleLogger(final String name) { this.name = name; } - - public void info(final String message) - { + + public void info(final String message) { Bukkit.getConsoleSender().sendMessage(PREFIX_INFO + getPrefix() + ChatAPI.colorify(null, message)); } - - public void warn(final String message) - { + + public String getPrefix() { + return getPrefix(false); + } + + public String getPrefix(final boolean error) { + return "§8[§" + (error ? 'c' : '2') + name + "§8]§7 "; + } + + public void warn(final String message) { Bukkit.getConsoleSender().sendMessage(PREFIX_WARN + getPrefix() + ChatAPI.colorify(null, message)); } - - public void error(final String message) - { + + public void error(final String message) { Bukkit.getConsoleSender().sendMessage(PREFIX_ERROR + getPrefix() + ChatAPI.colorify(null, message)); } - - public void message(final CommandSender recipient, final String... message) - { + + public void message(final CommandSender recipient, final String... message) { message(recipient, false, message); } - - public void message(final CommandSender recipient, final boolean error, final String... message) - { + + public void message(final CommandSender recipient, final boolean error, final String... message) { Message m = new Message(recipient, null); if (message.length == 1) m.appendText(getPrefix(error) + message[0]); - else - { + else { m.appendText(getHeader()); m.appendText("&7" + String.join("\n&7", message)); } m.send(); } - - public String getPrefix() - { - return getPrefix(false); - } - - public String getPrefix(final boolean error) - { - return "§8[§" + (error ? 'c' : '2') + name + "§8]§7 "; - } - - public String getHeader() - { + + public String getHeader() { return "§2--=[ " + name + " ]=--\n"; } - - protected final void setName(final String name) - { + + protected final void setName(final String name) { this.name = name; } } -- cgit v1.2.3