/** @author CraftCraft */ public void loadPlugins() { pluginManager.registerInterface(JavaPluginLoader.class); File pluginFolder = theServer.getFile("plugins"); if (pluginFolder.exists()) { this.theLogger.info("Plugins are being loaded..."); Plugin[] plugins = pluginManager.loadPlugins(pluginFolder); for (Plugin plugin : plugins) { try { String message = String.format("Loading %s", plugin.getDescription().getFullName()); plugin.getLogger().info(message); plugin.onLoad(); } catch (Throwable ex) { Logger.getLogger(CraftServer.class.getName()) .log( Level.SEVERE, ex.getMessage() + " initializing " + plugin.getDescription().getFullName() + " (Is it up to date?)", ex); } } } else { theLogger.info("Plugin folder doesn't exist: " + pluginFolder.getAbsolutePath()); pluginFolder.mkdir(); } }
/* * @author CraftCraft */ private void loadPlugin(Plugin plugin) { try { pluginManager.enablePlugin(plugin); List<Permission> perms = plugin.getDescription().getPermissions(); for (Permission perm : perms) { try { pluginManager.addPermission(perm); } catch (IllegalArgumentException ex) { getLogger() .log( Level.WARNING, "Plugin " + plugin.getDescription().getFullName() + " tried to register permission '" + perm.getName() + "' but it's already registered", ex); } } } catch (Throwable ex) { Logger.getLogger(CraftServer.class.getName()) .log( Level.SEVERE, ex.getMessage() + " loading " + plugin.getDescription().getFullName() + " (Is it up to date?)", ex); } }
private boolean versionCheck(String title) { if (type != UpdateType.NO_VERSION_CHECK) { String version = plugin.getDescription().getVersion(); if (title.split("v").length == 2) { String remoteVersion = title.split("v")[1].split(" ")[0]; // Get the newest file's version number if (hasTag(version) || version.equalsIgnoreCase(remoteVersion)) { // We already have the latest version, or this build is tagged for no-update result = Updater.UpdateResult.NO_UPDATE; return false; } } else { // The file's name did not contain the string 'vVersion' plugin .getLogger() .warning("The author of this plugin has misconfigured their Auto Update system"); plugin .getLogger() .warning( "Files uploaded to BukkitDev should contain the version number, seperated from the name by a 'v', such as PluginName v1.0"); plugin .getLogger() .warning( "Please notify the author (" + plugin.getDescription().getAuthors().get(0) + ") of this error."); result = Updater.UpdateResult.FAIL_NOVERSION; return false; } } return true; }
public void start() throws Exception { if (!plugin.isEnabled()) return; if (!enabled) return; BottomLine.debug("Searching for update..."); HttpURLConnection c = (HttpURLConnection) new URL("http://www.spigotmc.org/api/general.php").openConnection(); c.setDoOutput(true); c.setRequestMethod("POST"); c.getOutputStream() .write( ("key=98BE0FE67F88AB82B4C197FAF1DC3B69206EFDCC4D3B80FC83A00037510B99B4&resource=" + id) .getBytes("UTF-8")); String current = plugin.getDescription().getVersion(); String vers = new BufferedReader(new InputStreamReader(c.getInputStream())) .readLine() .replaceAll("[a-zA-Z ]", ""); if (compareVersions(vers, current) == 1) { BottomLine.debug("Found new version, " + vers + "! (Currently running " + current + ")"); BottomLine.debug("Download at: http://www.spigotmc.org/resources/bottomline." + id); BottomLine.update = true; newvers = vers; oldvers = plugin.getDescription().getVersion(); } else { BottomLine.debug("No new update found to download!"); } }
/** * Enable all plugins of the given load order type. * * @param type The type of plugin to enable. */ public void enablePlugins(PluginLoadOrder type) { Plugin[] plugins = pluginManager.getPlugins(); for (Plugin plugin : plugins) { if (!plugin.isEnabled() && plugin.getDescription().getLoad() == type) { List<Permission> perms = plugin.getDescription().getPermissions(); for (Permission perm : perms) { try { pluginManager.addPermission(perm); } catch (IllegalArgumentException ex) { getLogger() .log( Level.WARNING, "Plugin " + plugin.getDescription().getFullName() + " tried to register permission '" + perm.getName() + "' but it's already registered", ex); } } try { pluginManager.enablePlugin(plugin); } catch (Throwable ex) { logger.log(Level.SEVERE, "Error loading {0}", plugin.getDescription().getFullName()); ex.printStackTrace(); } } } }
private boolean detectSpout() { Plugin p = this.getServer().getPluginManager().getPlugin("Spout"); if (p != null) { return p.isEnabled(); } return false; }
@Override public void onPluginEnable(PluginEnableEvent event) { if (TombWorker.getPermission() == null) { Plugin Permissions = TombPlugin.getBukkitServer().getPluginManager().getPlugin("Permissions"); if (Permissions != null) { if (Permissions.isEnabled()) { TombWorker.setPermission(((Permissions) Permissions).getHandler()); System.out.println("[Tomb] Successfully linked with Permissions."); } } } if (TombWorker.getPayement() == null) { // Check to see if we need a payment method if (!this.Methods.hasMethod()) { if (this.Methods.setMethod(event.getPlugin())) { // You might want to make this a public variable inside your MAIN class public Method // Method = null; // then reference it through this.plugin.Method so that way you can use it in the rest of // your plugin ;) TombWorker.setMethod(this.Methods.getMethod()); System.out.println( "[Tomb] Payment method found (" + TombWorker.getPayement().getName() + " version: " + TombWorker.getPayement().getVersion() + ")"); } } } }
private void enableSubPlugins() { File root = new File(getDataFolder(), Setting.SUBPLUGIN_FOLDER.asString()); if (!root.exists() || !root.isDirectory()) return; File[] files = root.listFiles(); for (File file : files) { Plugin plugin; try { plugin = Bukkit.getPluginManager().loadPlugin(file); } catch (Exception e) { continue; } if (plugin == null) continue; // code beneath modified from CraftServer try { Messaging.logTr(Messages.LOADING_SUB_PLUGIN, plugin.getDescription().getFullName()); plugin.onLoad(); } catch (Throwable ex) { Messaging.severeTr( Messages.ERROR_INITALISING_SUB_PLUGIN, ex.getMessage(), plugin.getDescription().getFullName()); ex.printStackTrace(); } } ((CraftServer) Bukkit.getServer()).enablePlugins(PluginLoadOrder.POSTWORLD); }
@Override public void shutdown() { theLogger.info("Stopping the Bukkit API " + version); int pollCount = 0; while (pollCount < 50 && getScheduler().getActiveWorkers().size() > 0) { try { Thread.sleep(50); } catch (InterruptedException e) {} pollCount++; } List<BukkitWorker> overdueWorkers = getScheduler().getActiveWorkers(); for (BukkitWorker worker : overdueWorkers) { Plugin plugin = worker.getOwner(); String author = "<NoAuthorGiven>"; if (plugin.getDescription().getAuthors().size() > 0) { author = plugin.getDescription().getAuthors().get(0); } getLogger().log(Level.SEVERE, String.format( "Nag author: '%s' of '%s' about the following: %s", author, plugin.getDescription().getName(), "This plugin is not properly shutting down its async tasks when it is being reloaded. This may cause conflicts with the newly loaded version of the plugin" )); } getPluginManager().disablePlugins(); //theServer.stopServer(); }
@Override public boolean run( CommandSender sender, Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { boolean toggled = false; boolean enabled = true; for (Plugin p : TotalFreedomMod.server.getPluginManager().getPlugins()) { if (p.getName().equalsIgnoreCase("nyan")) { if (p.isEnabled()) { p.getPluginLoader().disablePlugin(p); enabled = false; } else { p.getPluginLoader().enablePlugin(p); enabled = true; } toggled = true; } } if (toggled) { if (!enabled) { TotalFreedomMod.server.broadcastMessage( ChatColor.RED + sender.getName() + " - Disabling Nyan Plugin"); } else { TotalFreedomMod.server.broadcastMessage( ChatColor.GREEN + sender.getName() + " - Enabling Nyan Plugin"); } } return true; }
private void registerPluginIds() { if (pluginIds.isEmpty()) { for (Plugin plugin : Bukkit.getServer().getPluginManager().getPlugins()) { if (pluginIds.containsKey(plugin)) { VoxelGuest.log( "Attempted to register multiple IDs for plugin \"" + plugin.getDescription().getName() + "\"", 1); continue; } String sample = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"; char[] key = new char[16]; Random rand = new Random(); for (int i = 0; i < 16; i++) { key[i] = sample.charAt(rand.nextInt(sample.length())); } String id = new String(key); pluginIds.put(plugin, id); } } }
public boolean startRound() { /// trying to start when we havent created anything yet /// or event was canceled/closed if (round < 0 || state == EventState.CLOSED) { return false; } announceRound(); Plugin plugin = BattleArena.getSelf(); /// Section to start the match curTimer = plugin .getServer() .getScheduler() .scheduleSyncDelayedTask( plugin, new Runnable() { public void run() { Round tr = rounds.get(round); for (Matchup m : tr.getMatchups()) { ac.addMatchup(m); } } }, (long) (timeBetweenRounds * 20L * Defaults.TICK_MULT)); return true; }
public void enablePlugin(final Plugin plugin) { if (!(plugin instanceof JavaPlugin)) { throw new IllegalArgumentException("Plugin is not associated with this PluginLoader"); } if (!plugin.isEnabled()) { JavaPlugin jPlugin = (JavaPlugin) plugin; String pluginName = jPlugin.getDescription().getName(); if (!loaders.containsKey(pluginName)) { loaders.put(pluginName, (PluginClassLoader) jPlugin.getClassLoader()); } try { jPlugin.setEnabled(true); } catch (Throwable ex) { server .getLogger() .log( Level.SEVERE, "Error occurred while enabling " + plugin.getDescription().getFullName() + " (Is it up to date?): " + ex.getMessage(), ex); } // Perhaps abort here, rather than continue going, but as it stands, // an abort is not possible the way it's currently written server.getPluginManager().callEvent(new PluginEnableEvent(plugin)); } }
@Test public void testNullWorld() { // Pull a core instance from the server. Plugin plugin = mockServer.getPluginManager().getPlugin("Multiverse-Core"); // Make sure Core is not null assertNotNull(plugin); // Make sure Core is enabled assertTrue(plugin.isEnabled()); // Initialize a fake command Command mockCommand = mock(Command.class); when(mockCommand.getName()).thenReturn("mv"); // Ensure that there are no worlds imported. This is a fresh setup. assertEquals(0, creator.getCore().getMVWorldManager().getMVWorlds().size()); // Create the NULL world // The safe check is now BALLS SLOW. Use the -n to skip checking. String[] normalArgs = new String[] {"create", "nullworld", "normal", "-n"}; plugin.onCommand(mockCommandSender, mockCommand, "", normalArgs); // We should now have one world! assertEquals(1, creator.getCore().getMVWorldManager().getMVWorlds().size()); // Verify verify(mockCommandSender).sendMessage("Starting creation of world 'nullworld'..."); verify(mockCommandSender).sendMessage("Complete!"); WorldCreatorMatcher matcher = new WorldCreatorMatcher(new WorldCreator("nullworld")); verify(mockServer).createWorld(Matchers.argThat(matcher)); }
/** Loads all plugins, calling onLoad, &c. */ private void loadPlugins() { // clear the map commandMap.clearCommands(); commandMap.register("glowstone", new ColorCommand("colors")); commandMap.register("glowstone", new TellrawCommand()); File folder = new File(config.getString(ServerConfig.Key.PLUGIN_FOLDER)); if (!folder.isDirectory() && !folder.mkdirs()) { logger.log(Level.SEVERE, "Could not create plugins directory: " + folder); } // clear plugins and prepare to load pluginManager.clearPlugins(); pluginManager.registerInterface(JavaPluginLoader.class); Plugin[] plugins = pluginManager.loadPlugins(folder); // call onLoad methods for (Plugin plugin : plugins) { try { plugin.onLoad(); } catch (Exception ex) { logger.log(Level.SEVERE, "Error loading " + plugin.getDescription().getFullName(), ex); } } }
/** Loads all plugins, calling onLoad, &c. */ private void loadPlugins() { // clear the map commandMap.removeAllOfType(PluginCommand.class); File folder = new File(config.getString("server.folders.plugins", "plugins")); folder.mkdirs(); // clear plugins and prepare to load pluginManager.clearPlugins(); pluginManager.registerInterface(JavaPluginLoader.class); Plugin[] plugins = pluginManager.loadPlugins(folder); // call onLoad methods for (Plugin plugin : plugins) { try { plugin.onLoad(); } catch (Exception ex) { logger.log( Level.SEVERE, "Error loading {0}: {1}", new Object[] {plugin.getDescription().getName(), ex.getMessage()}); ex.printStackTrace(); } } }
private void setupOtherPlugins() { // setup permissions and iconomy Plugin plugin = this.getServer().getPluginManager().getPlugin("Permissions"); if (General.Permissions == null) { if (plugin != null) { General.Permissions = (Permissions) plugin; System.out.println("[" + General.name + "] hooked into Permissions."); } } Plugin p2 = this.getServer().getPluginManager().getPlugin("iConomy"); if (General.iConomy == null) { if (p2 != null) { General.iConomy = (iConomy) p2; System.out.println("[" + General.name + "] hooked into iConomy."); } } // set up command registry for (Plugin p : getServer().getPluginManager().getPlugins()) { if (p.isEnabled()) { if (p != null && !p.getDescription().getName().equalsIgnoreCase(General.name)) { iListen.checkPluginCommands(p); } } } }
@Override public void onEnable() { Plugin plug = getServer().getPluginManager().getPlugin("WGCustomFlags"); if (plug == null || !(plug instanceof WGCustomFlagsPlugin) || !plug.isEnabled()) { getLogger().warning("Could not load WorldGuard Custom Flags Plugin, disabling"); getServer().getPluginManager().disablePlugin(this); return; } else { custPlugin = (WGCustomFlagsPlugin) plug; } plug = getServer().getPluginManager().getPlugin("WorldGuard"); if (plug == null || !(plug instanceof WorldGuardPlugin) || !plug.isEnabled()) { getLogger().warning("Could not load WorldGuard Plugin, disabling"); getServer().getPluginManager().disablePlugin(this); return; } else { wgPlugin = (WorldGuardPlugin) plug; } custPlugin.addCustomFlag(KEEP_INVENTORY_FLAG); custPlugin.addCustomFlag(KEEP_LEVEL_FLAG); listener = new WGKIFlagListener(this, wgPlugin); loadInventories(); getServer().getPluginManager().registerEvents(listener, this); }
/** * Execute the command. * * @param sender the sender of the command * @param command the command being done * @param label the name of the command * @param args the arguments supplied */ @Override public void execute(CommandSender sender, Command command, String label, String[] args) { if (!hasPermission()) { sender.sendMessage(PlugMan.getInstance().getMessageFormatter().format("error.no-permission")); return; } if (args.length < 2) { sender.sendMessage( PlugMan.getInstance().getMessageFormatter().format("error.specify-plugin")); sendUsage(); return; } Plugin potential = PluginUtil.getPluginByName(args, 1); if (potential != null) { sender.sendMessage( PlugMan.getInstance() .getMessageFormatter() .format("load.already-loaded", potential.getName())); return; } String name = StringUtil.consolidateStrings(args, 1); if (PluginUtil.isIgnored(name)) { sender.sendMessage(PlugMan.getInstance().getMessageFormatter().format("error.ignored")); return; } sender.sendMessage(PluginUtil.load(name)); }
private void checkPluginVault() { if (vault != null) return; Plugin vaultCheck = pm.getPlugin("Vault"); if (vaultCheck != null && vaultCheck.isEnabled()) { vault = vaultCheck; core.log.info(core.getNameBrackets() + "found Vault plugin."); RegisteredServiceProvider<Permission> permissionProvider = core.getServer() .getServicesManager() .getRegistration(net.milkbowl.vault.permission.Permission.class); if (permissionProvider != null) { permission = permissionProvider.getProvider(); core.log.info( core.getNameBrackets() + "Reported permission provider: " + permission.getName()); } RegisteredServiceProvider<Economy> economyProvider = core.getServer() .getServicesManager() .getRegistration(net.milkbowl.vault.economy.Economy.class); if (economyProvider != null) { economy = economyProvider.getProvider(); core.log.info(core.getNameBrackets() + "Reported economy provider: " + economy.getName()); } } }
public void start() { System.out.println("Arena::onStart " + timedSpawns); if (timedSpawns != null && !timedSpawns.isEmpty()) { Plugin plugin = BattleArena.getSelf(); /// Create our Q, with a descending Comparator spawnQ = new PriorityQueue<NextSpawn>( timedSpawns.size(), new Comparator<NextSpawn>() { public int compare(NextSpawn o1, NextSpawn o2) { return (o1.timeToNext.compareTo(o2.timeToNext)); } }); /// TeamJoinResult our items into the Q ArrayList<NextSpawn> nextspawns = new ArrayList<NextSpawn>(); for (TimedSpawn is : timedSpawns.values()) { // System.out.println("itemSpawns = " + timedSpawns.size() + " " + // is.getFirstSpawnTime()+ " ts=" + is); long tts = is.getFirstSpawnTime(); if (tts == 0) is.spawn(); NextSpawn ns = new NextSpawn(is, tts); spawnQ.add(ns); nextspawns.add(ns); } timerId = plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new SpawnNextEvent(0L)); } }
public void mergeConfig() { // options().copyDefaults(false); // System.out.println("merging // config?"+contains("settings.restrictions.ProtectInventoryBeforeLogIn")+checkDefaults()); if (!contains("settings.restrictions.ProtectInventoryBeforeLogIn")) { set("settings.restrictions.enablePasswordVerifier", true); set("settings.restrictions.ProtectInventoryBeforeLogIn", true); } if (!contains("settings.security.passwordMaxLength")) { set("settings.security.passwordMaxLength", 20); } if (!contains("BackupSystem.ActivateBackup")) { set("BackupSystem.ActivateBackup", false); set("BackupSystem.OnServerStart", false); set("BackupSystem.OnServeStop", false); } if (!contains("BackupSystem.MysqlWindowsPath")) { set("BackupSystem.MysqlWindowsPath", "C:\\Program Files\\MySQL\\MySQL Server 5.1\\"); } if (!contains("settings.messagesLanguage")) { set("settings.messagesLanguage", "en"); } else return; plugin.getLogger().info("Merge new Config Options.."); plugin.saveConfig(); return; }
private ChunkGenerator getGenerator(int dimID) { ConfigurationSection section = bukkitConfig.getConfigurationSection("worlds"); ChunkGenerator result = null; if (section != null) { section = section.getConfigurationSection(Integer.toString(dimID)); if (section != null) { String name = section.getString("generator"); if ((name != null) && (!name.equals(""))) { String[] split = name.split(":", 2); String id = (split.length > 1) ? split[1] : null; Plugin plugin = pluginManager.getPlugin(split[0]); if (plugin == null) { getLogger().severe("Could not set generator for default world '" + Integer.toString(dimID) + "': Plugin '" + split[0] + "' does not exist"); } else if (!plugin.isEnabled()) { getLogger().severe("Could not set generator for default world '" + Integer.toString(dimID) + "': Plugin '" + split[0] + "' is not enabled yet (is it load:STARTUP?)"); } else { result = plugin.getDefaultWorldGenerator(Integer.toString(dimID), id); } } } } return result; }
private void setupSpout(PluginManager pm) { Plugin spout = pm.getPlugin("Spout"); if (spout != null && spout.isEnabled()) { spoutEnabled = true; MiscUtil.log(Level.INFO, "Loaded Spout v" + spout.getDescription().getVersion()); } }
@Test public void testWorldCreateInvalidGenerator() { // Pull a core instance from the server. Plugin plugin = mockServer.getPluginManager().getPlugin("Multiverse-Core"); // Make sure Core is not null assertNotNull(plugin); // Make sure Core is enabled assertTrue(plugin.isEnabled()); // Initialize a fake command Command mockCommand = mock(Command.class); when(mockCommand.getName()).thenReturn("mv"); // Ensure that there are no worlds imported. This is a fresh setup. assertEquals(0, creator.getCore().getMVWorldManager().getMVWorlds().size()); // Create the world String[] normalArgs = new String[] {"create", "newworld", "normal", "-g", "BogusGen"}; plugin.onCommand(mockCommandSender, mockCommand, "", normalArgs); // This command should halt, not creating any worlds assertEquals(0, creator.getCore().getMVWorldManager().getMVWorlds().size()); // Verify verify(mockCommandSender) .sendMessage( "Invalid generator! 'BogusGen'. " + ChatColor.RED + "Aborting world creation."); }
public static AWEAdaptor getAWEAdaptor() { if (adaptor == null) { Plugin awe = getAWE(); if (awe != null) { VersionUtil.Version version = VersionUtil.getVersion(awe.getDescription().getVersion()); String className = null; if (version.isLT("3.0")) { className = "us.talabrek.ultimateskyblock.handler.asyncworldedit.AWE211Adaptor"; } else if (version.isLT("3.2.0")) { className = "us.talabrek.ultimateskyblock.handler.asyncworldedit.AWE311Adaptor"; } else { className = "us.talabrek.ultimateskyblock.handler.asyncworldedit.AWE321Adaptor"; } try { adaptor = (AWEAdaptor) Class.forName(className).<AWEAdaptor>newInstance(); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException | NoClassDefFoundError e) { log.log(Level.WARNING, "Unable to locate AWE adaptor for version " + version + ": " + e); adaptor = NULL_ADAPTOR; } } else { adaptor = NULL_ADAPTOR; } } return adaptor; }
@Test public void testWorldImportWithNoFolder() { // Make sure the world directory do NOT exist // (it was created by the TestInstanceCreator) File worldFile = new File(TestInstanceCreator.serverDirectory, "world"); assertTrue(worldFile.exists()); assertTrue(worldFile.delete()); // Start actual testing. // Pull a core instance from the server. Plugin plugin = mockServer.getPluginManager().getPlugin("Multiverse-Core"); // Make sure Core is not null assertNotNull(plugin); // Make sure Core is enabled assertTrue(plugin.isEnabled()); // Initialize a fake command Command mockCommand = mock(Command.class); when(mockCommand.getName()).thenReturn("mv"); String[] normalArgs = new String[] {"import", "world", "normal"}; // Ensure we have a fresh copy of MV, 0 worlds. assertEquals(0, creator.getCore().getMVWorldManager().getMVWorlds().size()); // Import the first world. The world folder does not exist. plugin.onCommand(mockCommandSender, mockCommand, "", normalArgs); verify(mockCommandSender).sendMessage(ChatColor.RED + "FAILED."); verify(mockCommandSender) .sendMessage("That world folder does not exist. These look like worlds to me:"); // We should still have no worlds. assertEquals(0, creator.getCore().getMVWorldManager().getMVWorlds().size()); }
/** * Initialize the updater * * @param plugin The plugin that is checking for an update. * @param slug The dev.bukkit.org slug of the project * (http://dev.bukkit.org/server-mods/SLUG_IS_HERE) * @param file The file that the plugin is running from, get this by doing this.getFile() from * within your main class. * @param type Specify the type of update this will be. See {@link UpdateType} * @param announce True if the program should announce the progress of new updates in console */ public Updater(Plugin plugin, String slug, File file, UpdateType type, boolean announce) { this.plugin = plugin; this.type = type; this.announce = announce; this.file = file; try { // Obtain the results of the project's file feed url = new URL(DBOUrl + slug + "/files.rss"); } catch (MalformedURLException ex) { // Invalid slug plugin .getLogger() .warning( "The author of this plugin (" + plugin.getDescription().getAuthors().get(0) + ") has misconfigured their Auto Update system"); plugin .getLogger() .warning( "The project slug given ('" + slug + "') is invalid. Please nag the author about this."); result = Updater.UpdateResult.FAIL_BADSLUG; // Bad slug! Bad! } thread = new Thread(new UpdateRunnable()); thread.start(); }
public void check() { if (!isCurrent()) { plugin.getLogger().log(Level.INFO, "New Version " + version + " Out!"); plugin.getLogger().log(Level.INFO, title + " published on: " + pubdate); plugin.getLogger().log(Level.INFO, "Download at " + link); warn = true; } }
@EventHandler public void onPluginEnable(PluginEnableEvent event) { Plugin p = event.getPlugin(); String name = p.getDescription().getName(); if (name.equals("dynmap") || name.equals("Essentials")) { if (dynmap.isEnabled() && citizens.isEnabled()) activate(); } }