下面列出了怎么用org.bukkit.plugin.Plugin的API类实例代码及写法,或者点击链接到github查看源代码。
public static void load(Plugin plugin, String loc) {
if (loc != null && !"".equals(loc.trim())) {
locale = loc;
}
if (!BASE_LANG_CODE.equals(locale)) {
fallbackContainer = new BukkitTranslateContainer(BASE_LANG_CODE, plugin);
}
mainContainer = new BukkitTranslateContainer(locale, plugin, fallbackContainer);
customContainer = new BukkitTranslateContainer(new File(plugin.getDataFolder().toString(), "languages"), locale, mainContainer);
plugin.getLogger().info(
"Successfully loaded messages for " + plugin.getName() + "! Language: " + customContainer.getLanguage());
}
public Metrics(final Plugin plugin) throws IOException {
if (plugin == null) {
throw new IllegalArgumentException("Plugin cannot be null");
}
this.plugin = plugin;
// load the config
configurationFile = getConfigFile();
configuration = YamlConfiguration.loadConfiguration(configurationFile);
// add some defaults
configuration.addDefault("opt-out", false);
configuration.addDefault("guid", UUID.randomUUID().toString());
configuration.addDefault("debug", false);
// Do we need to create the file?
if (configuration.get("guid", null) == null) {
configuration.options().header("http://mcstats.org").copyDefaults(true);
configuration.save(configurationFile);
}
// Load the guid then
guid = configuration.getString("guid");
debug = configuration.getBoolean("debug", false);
}
public static void inject(Plugin plugin, Class<?> clazz) {
if (clazz.equals(TabooLib.class)) {
for (Dependency dependency : TabooLib.class.getAnnotationsByType(Dependency.class)) {
for (String url : dependency.url().split(";")) {
try {
if (TDependency.requestLib(dependency.maven(), dependency.mavenRepo(), url)) {
break;
}
} catch (Throwable ignored) {
}
}
}
} else {
try {
ClassReader classReader = new ClassReader(Files.getResource(plugin, clazz.getName().replace(".", "/") + ".class"));
ClassWriter classWriter = new ClassWriter(0);
ClassVisitor classVisitor = new DependencyClassVisitor(plugin, classWriter);
classReader.accept(classVisitor, ClassReader.EXPAND_FRAMES);
classWriter.visitEnd();
classVisitor.visitEnd();
} catch (Throwable t) {
t.printStackTrace();
}
}
}
@Override
public List<String> tabComplete(CommandSender sender, String alias, String[] args) {
Validate.notNull(sender, "Sender cannot be null");
Validate.notNull(args, "Arguments cannot be null");
Validate.notNull(alias, "Alias cannot be null");
if (args.length == 1) {
List<String> completions = new ArrayList<>();
String toComplete = args[0].toLowerCase(java.util.Locale.ENGLISH);
for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
if (StringUtil.startsWithIgnoreCase(plugin.getName(), toComplete)) {
completions.add(plugin.getName());
}
}
return completions;
}
return ImmutableList.of();
}
@Inject ChannelMatchModule(Match match, Plugin plugin) {
this.matchListeningPermission = new Permission("pgm.chat.all." + match.getId() + ".receive", PermissionDefault.FALSE);
final OnlinePlayerMapAdapter<Boolean> map = new OnlinePlayerMapAdapter<>(plugin);
map.enable();
this.teamChatters = new DefaultMapAdapter<>(map, true, false);
}
@Override
public BukkitTask runTaskAsynchronously(Plugin plugin, BukkitRunnable bukkitRunnable)
throws IllegalArgumentException {
TaskedRunnable wrapped = new TaskedRunnable(bukkitRunnable);
BukkitTask bukkitTask = delegate.runTaskAsynchronously(plugin, wrapped);
wrapped.setTaskID(bukkitTask.getTaskId());
return bukkitTask;
}
/**
* Guilds logLogo in console
*/
public static void logLogo(ConsoleCommandSender sender, Plugin plugin) {
sender.sendMessage(StringUtils.color("&a ________ "));
sender.sendMessage(StringUtils.color("&a / _____/ "));
sender.sendMessage(StringUtils.color("&a/ \\ ___ " + " &3Guilds &8v" + plugin.getDescription().getVersion()));
sender.sendMessage(StringUtils.color("&a\\ \\_\\ \\" + " &3Server Version: &8" + plugin.getServer().getVersion()));
sender.sendMessage(StringUtils.color("&a \\______ /"));
sender.sendMessage(StringUtils.color("&a \\/ "));
}
@Override
protected Plugin checkPlugin(Object plugin) throws IllegalArgumentException {
if (plugin instanceof Plugin) {
return (Plugin) plugin;
}
throw new IllegalArgumentException("Object " + plugin + " (" + plugin.getClass().getName() + ") is not a plugin.");
}
private void setupPlaceholderAPI() {
Plugin mvdw = getServer().getPluginManager().getPlugin("MVdWPlaceholderAPI");
if (mvdw != null && mvdw.isEnabled()) {
new MVDWPlaceholderAPIManager().register();
getLogger().info("Successfully registered placeholders with MVDWPlaceholderAPI.");
}
setupClipsPlaceholderAPI();
}
@Override
public void onActualEnable() {
ICombatLogX plugin = getPlugin();
ExpansionManager expansionManager = plugin.getExpansionManager();
PluginManager manager = Bukkit.getPluginManager();
Logger logger = getLogger();
Plugin pluginGriefPrevention = manager.getPlugin("GriefPrevention");
if(pluginGriefPrevention == null) {
logger.info("The GriefPrevention plugin could not be found. This expansion will be automatically disabled.");
expansionManager.disableExpansion(this);
return;
}
String version = pluginGriefPrevention.getDescription().getVersion();
logger.info("Successfully hooked into GriefPrevention v" + version);
saveDefaultConfig("griefprevention-compatibility.yml");
this.noEntryHandler = new GriefPreventionNoEntryHandler(this);
NoEntryListener listener = new NoEntryListener(this);
expansionManager.registerListener(this, listener);
Plugin pluginProtocolLib = manager.getPlugin("ProtocolLib");
if(pluginProtocolLib != null) {
NoEntryForceFieldListener forceFieldListener = new NoEntryForceFieldListener(this);
expansionManager.registerListener(this, forceFieldListener);
String versionProtocolLib = pluginProtocolLib.getDescription().getVersion();
logger.info("Successfully hooked into ProtocolLib v" + versionProtocolLib);
}
}
@Override
public void onEnable(Plugin plugin) throws Exception
{
this.sessionManager = new SessionManagerWrapper(WorldGuardPlugin.inst().getSessionManager());
this.regionContainer = new RegionContainerWrapper();
WorldGuardCommunicator.super.onEnable(plugin);
}
@Override
public void track(Hologram hologram, Plugin owningPlugin) {
this.holograms.put(hologram, owningPlugin);
if (!hologram.isSimple() && this.config.getConfigurationSection("holograms." + hologram.getSaveId()) == null) {
this.saveToFile(hologram);
}
if (hologram instanceof AnimatedHologram && !((AnimatedHologram) hologram).isAnimating()) {
((AnimatedHologram) hologram).animate();
}
HoloAPI.getCore().getServer().getPluginManager().callEvent(new HoloCreateEvent(hologram));
HoloAPI.getHoloUpdater().track(hologram);
}
@Override
public boolean add(Plugin plugin) {
if (plugin.getName().startsWith("AsyncWorldEdit")) {
Fawe.debug("Disabling `" + plugin.getName() + "` as it is incompatible");
} else if (plugin.getName().startsWith("BetterShutdown")) {
Fawe.debug("Disabling `" + plugin.getName() + "` as it is incompatible (Improperly shaded classes from com.sk89q.minecraft.util.commands)");
} else {
return super.add(plugin);
}
return false;
}
public Permission_BungeePerms(Plugin plugin)
{
super();
this.plugin = plugin;
Bukkit.getServer().getPluginManager().registerEvents(new PermissionServerListener(), BukkitPlugin.getInstance());
// Load Plugin in case it was loaded before
Plugin p = plugin.getServer().getPluginManager().getPlugin("BungeePerms");
if (p != null)
{
this.perms = BungeePerms.getInstance();
log.info(String.format("[%s][Permission] %s hooked.", plugin.getDescription().getName(), name));
}
}
/**
* Constructs a factory for building a hologram
*
* @param owningPlugin plugin to register constructed hologram under
* @throws java.lang.IllegalArgumentException if the owning plugin is null
*/
public HoloFactory(Plugin owningPlugin) {
if (owningPlugin == null) {
throw new IllegalArgumentException("Plugin cannot be null");
}
this.owningPlugin = owningPlugin;
}
public void uninject(Plugin plugin)
{
BungeePerms.getLogger().info("Uninjection of Bungeeperms into Vault");
try
{
Vault v = (Vault) plugin;
if (!v.isEnabled())
{
return;
}
//uninject BungeePerms permissions
Method m = v.getClass().getDeclaredMethod("loadChat");
m.setAccessible(true);
m.invoke(v);
//inject BungeePerms chat
m = v.getClass().getDeclaredMethod("loadPermission");
m.setAccessible(true);
m.invoke(v);
}
catch (Exception ex)
{
BungeePerms.getInstance().getDebug().log(ex);
}
}
public Chat_BungeePerms(Plugin plugin, Permission perms)
{
super(perms);
this.plugin = plugin;
Bukkit.getServer().getPluginManager().registerEvents(new ChatServerListener(), BukkitPlugin.getInstance());
// Load Plugin in case it was loaded before
Plugin p = plugin.getServer().getPluginManager().getPlugin("BungeePerms");
if (p != null)
{
this.perms = BungeePerms.getInstance();
log.info(String.format("[%s][Chat] %s hooked.", plugin.getDescription().getName(), name));
}
}
@Override
public void onActualEnable() {
ICombatLogX plugin = getPlugin();
ExpansionManager expansionManager = plugin.getExpansionManager();
PluginManager manager = Bukkit.getPluginManager();
Logger logger = getLogger();
Plugin pluginWorldGuard = manager.getPlugin("WorldGuard");
if(pluginWorldGuard == null) {
logger.info("The WorldGuard plugin could not be found. This expansion will be automatically disabled.");
expansionManager.disableExpansion(this);
return;
}
String version = pluginWorldGuard.getDescription().getVersion();
logger.info("Successfully hooked into WorldGuard v" + version);
saveDefaultConfig("worldguard-compatibility.yml");
this.noEntryHandler = new WorldGuardNoEntryHandler(this);
ListenerWorldGuard listenerWorldGuard = new ListenerWorldGuard();
expansionManager.registerListener(this, listenerWorldGuard);
NoEntryListener listener = new NoEntryListener(this);
expansionManager.registerListener(this, listener);
HookWorldGuard.registerListeners(this);
Plugin pluginProtocolLib = manager.getPlugin("ProtocolLib");
if(pluginProtocolLib != null) {
NoEntryForceFieldListener forceFieldListener = new NoEntryForceFieldListener(this);
expansionManager.registerListener(this, forceFieldListener);
String versionProtocolLib = pluginProtocolLib.getDescription().getVersion();
logger.info("Successfully hooked into ProtocolLib v" + versionProtocolLib);
}
}
AddonsChart() {
super("installed_addons", () -> {
Map<String, Integer> addons = new HashMap<>();
for (Plugin plugin : SlimefunPlugin.getInstalledAddons()) {
if (plugin.isEnabled()) {
addons.put(plugin.getName(), 1);
}
}
return addons;
});
}
public void enablePlugins(PluginLoadOrder type) {
// Cauldron start - initialize mod wrappers
org.bukkit.craftbukkit.block.CraftBlock.initMappings();
org.bukkit.craftbukkit.entity.CraftEntity.initMappings();
// Cauldron end
if (type == PluginLoadOrder.STARTUP) {
helpMap.clear();
helpMap.initializeGeneralTopics();
}
Plugin[] plugins = pluginManager.getPlugins();
for (Plugin plugin : plugins) {
if ((!plugin.isEnabled()) && (plugin.getDescription().getLoad() == type)) {
loadPlugin(plugin);
}
}
if (type == PluginLoadOrder.POSTWORLD) {
commandMap.setFallbackCommands();
setVanillaCommands();
commandMap.registerServerAliases();
loadCustomPermissions();
DefaultPermissions.registerCorePermissions();
helpMap.initializeCommands();
}
}
@Override
public void onEnable() {
ICombatLogX plugin = getPlugin();
ExpansionManager expansionManager = plugin.getExpansionManager();
PluginManager manager = Bukkit.getPluginManager();
Logger logger = getLogger();
if(!manager.isPluginEnabled("PlaceholderAPI")) {
logger.info("The PlaceholderAPI plugin could not be found. This expansion will be automatically disabled.");
expansionManager.disableExpansion(this);
return;
}
Plugin pluginPlaceholderAPI = manager.getPlugin("PlaceholderAPI");
if(pluginPlaceholderAPI == null) {
logger.info("The PlaceholderAPI plugin could not be found. This expansion will be automatically disabled.");
expansionManager.disableExpansion(this);
return;
}
String versionPlaceholderAPI = pluginPlaceholderAPI.getDescription().getVersion();
logger.info("Successfully hooked into PlaceholderAPI v" + versionPlaceholderAPI);
HookPlaceholderAPI hookPlaceholderAPI = new HookPlaceholderAPI(this);
hookPlaceholderAPI.register();
}
@Deprecated
public static FloatingItem[] getFloatingItems(Plugin plugin) {
notifyOldAPI(plugin);
Collection<FloatingItemAdapter> pluginFloatingItems = FloatingItemAdapter.activeFloatingItems.getOrDefault(plugin, Collections.emptyList());
return pluginFloatingItems.toArray(new FloatingItemAdapter[0]);
}
@Override
protected void registerVariable0(Plugin plugin, Variable variable) {
Preconditions.checkNotNull(plugin, "plugin");
Preconditions.checkNotNull(variable, "variable");
apiLock.writeLock().lock();
try {
Preconditions.checkArgument(!variablesByName.containsKey(variable.getName()), "variable already registered");
variablesByName.put(variable.getName(), variable);
variablesByPlugin.put(plugin, variable);
} finally {
apiLock.writeLock().unlock();
}
}
private static Object createHandler(String name) {
if (!PAPER_SPIGOT) {
return new CustomTimingsHandler(name);
} else {
try {
Class<?> clazz = Class.forName("co.aikar.timings.Timings");
return clazz.getDeclaredMethod("of", Plugin.class, String.class).invoke(null, MapManagerPlugin.instance, name);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
@EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onSlimeInteract(PlayerInteractEntityEvent event) {
if (event.getRightClicked().getType() != EntityType.SLIME) {
return;
}
Player clicker = event.getPlayer();
if (clicker.getGameMode() == GameMode.SPECTATOR) {
return;
}
NMSEntityBase entityBase = nmsManager.getNMSEntityBase(event.getRightClicked());
if (entityBase == null || !(entityBase.getHologramLine() instanceof CraftTouchSlimeLine)) {
return;
}
CraftTouchSlimeLine touchSlime = (CraftTouchSlimeLine) entityBase.getHologramLine();
if (touchSlime.getTouchablePiece().getTouchHandler() == null || !touchSlime.getParent().getVisibilityManager().isVisibleTo(clicker)) {
return;
}
Long lastClick = anticlickSpam.get(clicker);
if (lastClick != null && System.currentTimeMillis() - lastClick.longValue() < 100) {
return;
}
anticlickSpam.put(event.getPlayer(), System.currentTimeMillis());
try {
touchSlime.getTouchablePiece().getTouchHandler().onTouch(event.getPlayer());
} catch (Throwable t) {
Plugin plugin = touchSlime.getParent() instanceof PluginHologram ? ((PluginHologram) touchSlime.getParent()).getOwner() : HolographicDisplays.getInstance();
ConsoleLogger.log(Level.WARNING, "The plugin " + plugin.getName() + " generated an exception when the player " + event.getPlayer().getName() + " touched a hologram.", t);
}
}
/**
* 初始化所有插件的所有监听器
*/
public static void setupListeners() {
for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
try {
setupListener(plugin);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public SQLiteHost(File file, Plugin plugin) {
super(plugin);
this.file = file;
}
public PingManager(Plugin plugin) {
this.plugin = plugin;
}
public LoggedScheduler(Plugin owner) {
this(owner.getServer().getScheduler());
}
public static MenuBuilder builder(Plugin plugin) {
return new MenuBuilder(plugin);
}