Java Code Examples for org.bukkit.plugin.SimplePluginManager

The following examples show how to use org.bukkit.plugin.SimplePluginManager. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: mcspring-boot   Source File: CommandService.java    License: MIT License 6 votes vote down vote up
@SneakyThrows
public void unregisterCommand(CommandSpec commandSpec) {
    val commandName = commandSpec.name();
    val manager = (SimplePluginManager) plugin.getServer().getPluginManager();

    val commandMapField = SimplePluginManager.class.getDeclaredField("commandMap");
    commandMapField.setAccessible(true);
    val map = (CommandMap) commandMapField.get(manager);

    val knownCommandsField = SimpleCommandMap.class.getDeclaredField("knownCommands");
    knownCommandsField.setAccessible(true);
    val knownCommands = (Map<String, Command>) knownCommandsField.get(map);

    val command = knownCommands.get(commandName);
    if (command != null) {
        command.unregister(map);
        knownCommands.remove(commandName);
    }
}
 
Example 2
@SuppressWarnings("unchecked")
public Plugin loadPlugin(PluginDescriptionFile plugin) throws UnknownDependencyException {
  final SimplePluginManager manager = (SimplePluginManager) server.getPluginManager();
  try {
    final File file = new File("plugins", plugin.getName());
    final Class[] init =
        new Class[] {
          PluginLoader.class, Server.class, PluginDescriptionFile.class, File.class, File.class
        };
    final JavaPlugin instance =
        (JavaPlugin)
            Class.forName(plugin.getMain())
                .getConstructor(init)
                .newInstance(this, server, plugin, file, file);

    readField(SimplePluginManager.class, manager, List.class, "plugins").add(instance);
    readField(SimplePluginManager.class, manager, Map.class, "lookupNames")
        .put(instance.getName().toLowerCase(), instance);

    return instance;
  } catch (Throwable t) {
    throw new UnknownDependencyException(
        t, "Unable to load plugin: " + plugin.getName() + " (" + plugin.getMain() + ")");
  }
}
 
Example 3
Source Project: LuckPerms   Source File: InjectorDefaultsMap.java    License: MIT License 6 votes vote down vote up
private LuckPermsDefaultsMap tryInject() throws Exception {
    Objects.requireNonNull(DEFAULT_PERMISSIONS_FIELD, "DEFAULT_PERMISSIONS_FIELD");
    PluginManager pluginManager = this.plugin.getBootstrap().getServer().getPluginManager();

    if (!(pluginManager instanceof SimplePluginManager)) {
        this.plugin.getLogger().severe("PluginManager instance is not a 'SimplePluginManager', instead: " + pluginManager.getClass());
        this.plugin.getLogger().severe("Unable to inject LuckPerms Default Permission map.");
        return null;
    }

    Object map = DEFAULT_PERMISSIONS_FIELD.get(pluginManager);
    if (map instanceof LuckPermsDefaultsMap && ((LuckPermsDefaultsMap) map).plugin == this.plugin) {
        return null;
    }

    //noinspection unchecked
    Map<Boolean, Set<Permission>> castedMap = (Map<Boolean, Set<Permission>>) map;

    // make a new map & inject it
    LuckPermsDefaultsMap newMap = new LuckPermsDefaultsMap(this.plugin, castedMap);
    DEFAULT_PERMISSIONS_FIELD.set(pluginManager, newMap);
    return newMap;
}
 
Example 4
Source Project: LuckPerms   Source File: InjectorDefaultsMap.java    License: MIT License 6 votes vote down vote up
public void uninject() {
    try {
        Objects.requireNonNull(DEFAULT_PERMISSIONS_FIELD, "DEFAULT_PERMISSIONS_FIELD");

        PluginManager pluginManager = this.plugin.getBootstrap().getServer().getPluginManager();
        if (!(pluginManager instanceof SimplePluginManager)) {
            return;
        }

        Object map = DEFAULT_PERMISSIONS_FIELD.get(pluginManager);
        if (map instanceof LuckPermsDefaultsMap) {
            LuckPermsDefaultsMap lpMap = (LuckPermsDefaultsMap) map;
            DEFAULT_PERMISSIONS_FIELD.set(pluginManager, new HashMap<>(lpMap));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 5
Source Project: LuckPerms   Source File: InjectorPermissionMap.java    License: MIT License 6 votes vote down vote up
private LuckPermsPermissionMap tryInject() throws Exception {
    Objects.requireNonNull(PERMISSIONS_FIELD, "PERMISSIONS_FIELD");
    PluginManager pluginManager = this.plugin.getBootstrap().getServer().getPluginManager();

    if (!(pluginManager instanceof SimplePluginManager)) {
        this.plugin.getLogger().severe("PluginManager instance is not a 'SimplePluginManager', instead: " + pluginManager.getClass());
        this.plugin.getLogger().severe("Unable to inject LuckPerms Permission map.");
        return null;
    }

    Object map = PERMISSIONS_FIELD.get(pluginManager);
    if (map instanceof LuckPermsPermissionMap && ((LuckPermsPermissionMap) map).plugin == this.plugin) {
        return null;
    }

    //noinspection unchecked
    Map<String, Permission> castedMap = (Map<String, Permission>) map;

    // make a new map & inject it
    LuckPermsPermissionMap newMap = new LuckPermsPermissionMap(this.plugin, castedMap);
    PERMISSIONS_FIELD.set(pluginManager, newMap);
    return newMap;
}
 
Example 6
Source Project: LuckPerms   Source File: InjectorPermissionMap.java    License: MIT License 6 votes vote down vote up
public void uninject() {
    try {
        Objects.requireNonNull(PERMISSIONS_FIELD, "PERMISSIONS_FIELD");

        PluginManager pluginManager = this.plugin.getBootstrap().getServer().getPluginManager();
        if (!(pluginManager instanceof SimplePluginManager)) {
            return;
        }

        Object map = PERMISSIONS_FIELD.get(pluginManager);
        if (map instanceof LuckPermsPermissionMap) {
            LuckPermsPermissionMap lpMap = (LuckPermsPermissionMap) map;
            PERMISSIONS_FIELD.set(pluginManager, new HashMap<>(lpMap));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 7
Source Project: LuckPerms   Source File: InjectorSubscriptionMap.java    License: MIT License 6 votes vote down vote up
public void uninject() {
    try {
        Objects.requireNonNull(PERM_SUBS_FIELD, "PERM_SUBS_FIELD");

        PluginManager pluginManager = this.plugin.getBootstrap().getServer().getPluginManager();
        if (!(pluginManager instanceof SimplePluginManager)) {
            return;
        }

        Object map = PERM_SUBS_FIELD.get(pluginManager);
        if (map instanceof LuckPermsSubscriptionMap) {
            LuckPermsSubscriptionMap lpMap = (LuckPermsSubscriptionMap) map;
            PERM_SUBS_FIELD.set(pluginManager, lpMap.detach());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 8
Source Project: SonarPet   Source File: CommandManager.java    License: GNU General Public License v3.0 6 votes vote down vote up
public CommandMap getCommandMap() {
    if (!(Bukkit.getPluginManager() instanceof SimplePluginManager)) {
        this.plugin.getLogger().warning("Seems like your server is using a custom PluginManager? Well let's try injecting our custom commands anyways...");
    }

    CommandMap map = null;

    try {
        map = SERVER_COMMAND_MAP.get(Bukkit.getPluginManager());

        if (map == null) {
            if (fallback != null) {
                return fallback;
            } else {
                fallback = map = new SimpleCommandMap(EchoPet.getPlugin().getServer());
                Bukkit.getPluginManager().registerEvents(new FallbackCommandRegistrationListener(fallback), this.plugin);
            }
        }
    } catch (Exception pie) {
        this.plugin.getLogger().warning("Failed to dynamically register the commands! Let's give it a last shot...");
        // Hmmm.... Pie...
        fallback = map = new SimpleCommandMap(EchoPet.getPlugin().getServer());
        Bukkit.getPluginManager().registerEvents(new FallbackCommandRegistrationListener(fallback), this.plugin);
    }
    return map;
}
 
Example 9
Source Project: PlayerSQL   Source File: PluginHelper.java    License: GNU General Public License v2.0 6 votes vote down vote up
@SneakyThrows
public static void addExecutor(Plugin plugin, Command command) {
    Field f = SimplePluginManager.class.getDeclaredField("commandMap");
    f.setAccessible(true);
    CommandMap map = (CommandMap) f.get(plugin.getServer().getPluginManager());
    Constructor<PluginCommand> init = PluginCommand.class.getDeclaredConstructor(String.class, Plugin.class);
    init.setAccessible(true);
    PluginCommand inject = init.newInstance(command.getName(), plugin);
    inject.setExecutor((who, __, label, input) -> command.execute(who, label, input));
    inject.setAliases(command.getAliases());
    inject.setDescription(command.getDescription());
    inject.setLabel(command.getLabel());
    inject.setName(command.getName());
    inject.setPermission(command.getPermission());
    inject.setPermissionMessage(command.getPermissionMessage());
    inject.setUsage(command.getUsage());
    map.register(plugin.getName().toLowerCase(), inject);
}
 
Example 10
Source Project: EchoPet   Source File: CommandManager.java    License: GNU General Public License v3.0 6 votes vote down vote up
public CommandMap getCommandMap() {
    if (!(Bukkit.getPluginManager() instanceof SimplePluginManager)) {
        this.plugin.getLogger().warning("Seems like your server is using a custom PluginManager? Well let's try injecting our custom commands anyways...");
    }

    CommandMap map = null;

    try {
        map = SERVER_COMMAND_MAP.get(Bukkit.getPluginManager());

        if (map == null) {
            if (fallback != null) {
                return fallback;
            } else {
                fallback = map = new SimpleCommandMap(EchoPet.getPlugin().getServer());
                Bukkit.getPluginManager().registerEvents(new FallbackCommandRegistrationListener(fallback), this.plugin);
            }
        }
    } catch (Exception pie) {
        this.plugin.getLogger().warning("Failed to dynamically register the commands! Let's give it a last shot...");
        // Hmmm.... Pie...
        fallback = map = new SimpleCommandMap(EchoPet.getPlugin().getServer());
        Bukkit.getPluginManager().registerEvents(new FallbackCommandRegistrationListener(fallback), this.plugin);
    }
    return map;
}
 
Example 11
Source Project: TabooLib   Source File: TCommandHandler.java    License: MIT License 5 votes vote down vote up
@TFunction.Init
static void init() {
    SimpleReflection.saveField(SimplePluginManager.class, "commandMap");
    SimpleReflection.saveField(SimpleCommandMap.class, "knownCommands");
    commandMap = (SimpleCommandMap) SimpleReflection.getFieldValue(SimplePluginManager.class, Bukkit.getPluginManager(), "commandMap");
    knownCommands = (Map<String, Command>) SimpleReflection.getFieldValue(SimpleCommandMap.class, commandMap, "knownCommands");
}
 
Example 12
Source Project: DiscordBot   Source File: CommandManager.java    License: Apache License 2.0 5 votes vote down vote up
private CommandMap getCommandMap() {
	if (!(Bukkit.getPluginManager() instanceof SimplePluginManager)) {
		return null;
	}
	
	try {
		Field field = SimplePluginManager.class.getDeclaredField("commandMap");
		field.setAccessible(true);
		return (CommandMap) field.get(Bukkit.getPluginManager());
	} catch (IllegalAccessException | IllegalArgumentException | NoSuchFieldException | SecurityException ex) {
		DiscordBot.getInstance().getLogger().severe("Exception getting commandMap!");
		ex.printStackTrace();
	}
	return null;
}
 
Example 13
Source Project: UltimateChat   Source File: UChat.java    License: GNU General Public License v3.0 5 votes vote down vote up
public void registerAliases(String name, List<String> aliases, boolean shouldReg, String perm, Object cmdListener) {
    List<String> aliases1 = new ArrayList<>(aliases);

    for (Command cmd : PluginCommandYamlParser.parse(uchat)) {
        if (cmd.getName().equals(name)) {
            if (shouldReg) {
                getServer().getPluginCommand(name).setExecutor((CommandExecutor) cmdListener);
                getServer().getPluginCommand(name).setTabCompleter((TabCompleter) cmdListener);
                cmd.setAliases(aliases1);
                cmd.setLabel(name);
                if (perm != null) cmd.setPermission(perm);
            }
            try {
                Field field = SimplePluginManager.class.getDeclaredField("commandMap");
                field.setAccessible(true);
                CommandMap commandMap = (CommandMap) (field.get(getServer().getPluginManager()));
                if (shouldReg) {
                    Method register = commandMap.getClass().getMethod("register", String.class, Command.class);
                    register.invoke(commandMap, cmd.getName(), cmd);
                    ((PluginCommand) cmd).setExecutor((CommandExecutor) cmdListener);
                    ((PluginCommand) cmd).setTabCompleter((TabCompleter) cmdListener);
                } else if (getServer().getPluginCommand(name).isRegistered()) {
                    getServer().getPluginCommand(name).unregister(commandMap);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
 
Example 14
Source Project: LuckPerms   Source File: PluginManagerUtil.java    License: MIT License 5 votes vote down vote up
/**
 * Injects a dependency relationship into the plugin manager.
 *
 * @param plugin the plugin
 * @param depend the plugin being depended on
 */
@SuppressWarnings("unchecked")
public static void injectDependency(PluginManager pluginManager, String plugin, String depend) {
    if (DEPENDENCY_GRAPH_FIELD == null || !(pluginManager instanceof SimplePluginManager)) {
        return; // fail silently
    }

    try {
        MutableGraph<String> graph = (MutableGraph<String>) DEPENDENCY_GRAPH_FIELD.get(pluginManager);
        graph.putEdge(plugin, depend);
    } catch (Exception e) {
        // ignore
    }
}
 
Example 15
Source Project: LuckPerms   Source File: InjectorSubscriptionMap.java    License: MIT License 5 votes vote down vote up
private LuckPermsSubscriptionMap tryInject() throws Exception {
    Objects.requireNonNull(PERM_SUBS_FIELD, "PERM_SUBS_FIELD");
    PluginManager pluginManager = this.plugin.getBootstrap().getServer().getPluginManager();

    if (!(pluginManager instanceof SimplePluginManager)) {
        this.plugin.getLogger().severe("PluginManager instance is not a 'SimplePluginManager', instead: " + pluginManager.getClass());
        this.plugin.getLogger().severe("Unable to inject LuckPerms Permission Subscription map.");
        return null;
    }

    Object map = PERM_SUBS_FIELD.get(pluginManager);
    if (map instanceof LuckPermsSubscriptionMap) {
        if (((LuckPermsSubscriptionMap) map).plugin == this.plugin) {
            return null;
        }

        map = ((LuckPermsSubscriptionMap) map).detach();
    }

    //noinspection unchecked
    Map<String, Map<Permissible, Boolean>> castedMap = (Map<String, Map<Permissible, Boolean>>) map;

    // make a new subscription map & inject it
    LuckPermsSubscriptionMap newMap = new LuckPermsSubscriptionMap(this.plugin, castedMap);
    PERM_SUBS_FIELD.set(pluginManager, newMap);
    return newMap;
}
 
Example 16
Source Project: HoloAPI   Source File: DependencyGraphUtil.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static Collection<Plugin> getPluginsUnsafe() {
    final PluginManager man = Bukkit.getPluginManager();
    if (man instanceof SimplePluginManager) {
        return pluginsField.get(man);
    } else {
        return Arrays.asList(man.getPlugins());
    }
}
 
Example 17
Source Project: ScoreboardStats   Source File: ReplaceManagerTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testUnregister() throws Exception {
    PowerMockito.mockStatic(Bukkit.class);
    Mockito.when(Bukkit.getPluginManager()).thenReturn(PowerMockito.mock(SimplePluginManager.class));
    Mockito.when(Bukkit.getMessenger()).thenReturn(PowerMockito.mock(StandardMessenger.class));
    Mockito.when(Bukkit.getScheduler()).thenReturn(PowerMockito.mock(BukkitScheduler.class));

    Plugin plugin = PowerMockito.mock(Plugin.class);

    ReplaceManager replaceManager = new ReplaceManager(null, plugin, LoggerFactory.getLogger("test"));
    replaceManager.register(new Replacer(plugin, "test").scoreSupply(() -> 1));
}
 
Example 18
public static Collection<Plugin> getPluginsUnsafe() {
    final PluginManager man = Bukkit.getPluginManager();
    if (man instanceof SimplePluginManager) {
        return pluginsField.get(man);
    } else {
        return Arrays.asList(man.getPlugins());
    }
}
 
Example 19
Source Project: Kettle   Source File: TimingsCommand.java    License: GNU General Public License v3.0 4 votes vote down vote up
public void executeSpigotTimings(CommandSender sender, String[] args) {
    if ("on".equals(args[0])) {
        ((SimplePluginManager) Bukkit.getPluginManager()).useTimings(true);
        CustomTimingsHandler.reload();
        sender.sendMessage("Enabled Timings & Reset");
        return;
    } else if ("off".equals(args[0])) {
        ((SimplePluginManager) Bukkit.getPluginManager()).useTimings(false);
        sender.sendMessage("Disabled Timings");
        return;
    }

    if (!Bukkit.getPluginManager().useTimings()) {
        sender.sendMessage("Please enable timings by typing /timings on");
        return;
    }

    boolean paste = "paste".equals(args[0]);
    if ("reset".equals(args[0])) {
        CustomTimingsHandler.reload();
        sender.sendMessage("Timings reset");
    } else if ("merged".equals(args[0]) || "report".equals(args[0]) || paste) {
        long sampleTime = System.nanoTime() - timingStart;
        int index = 0;
        File timingFolder = new File("timings");
        timingFolder.mkdirs();
        File timings = new File(timingFolder, "timings.txt");
        ByteArrayOutputStream bout = (paste) ? new ByteArrayOutputStream() : null;
        while (timings.exists()) timings = new File(timingFolder, "timings" + (++index) + ".txt");
        PrintStream fileTimings = null;
        try {
            fileTimings = (paste) ? new PrintStream(bout) : new PrintStream(timings);

            CustomTimingsHandler.printTimings(fileTimings);
            fileTimings.println("Sample time " + sampleTime + " (" + sampleTime / 1E9 + "s)");

            fileTimings.println("<spigotConfig>");
            fileTimings.println(Bukkit.spigot().getConfig().saveToString());
            fileTimings.println("</spigotConfig>");

            if (paste) {
                new PasteThread(sender, bout).start();
                return;
            }

            sender.sendMessage("Timings written to " + timings.getPath());
            sender.sendMessage("Paste contents of file into form at http://www.spigotmc.org/go/timings to read results.");

        } catch (IOException e) {
        } finally {
            if (fileTimings != null) {
                fileTimings.close();
            }
        }
    }
}