下面列出了怎么用org.bukkit.plugin.java.JavaPlugin的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void run() {
if(this.ticksUntilRemove > 0) {
this.ticksUntilRemove--;
return;
}
long survivalSeconds = getSurvivalSeconds();
if(survivalSeconds < 0) return;
Player enemy = getEnemy();
ICombatLogX plugin = this.expansion.getPlugin();
if(enemy != null && waitUntilEnemyEscape()) {
ICombatManager combatManager = plugin.getCombatManager();
if(combatManager.isInCombat(enemy)) return;
}
Runnable task = () -> {
NPC npc = getNPC();
npc.despawn(DespawnReason.PLUGIN);
};
JavaPlugin javaPlugin = plugin.getPlugin();
BukkitScheduler scheduler = Bukkit.getScheduler();
scheduler.runTaskLater(javaPlugin, task, 1L);
}
/**
* A sin/cos based smoothly animated explosion wave.
* Source: https://www.youtube.com/watch?v=n8W7RxW5KB4
*
* @param rate the distance between each cos/sin lines.
* @since 1.0.0
*/
public static void explosionWave(JavaPlugin plugin, double rate, ParticleDisplay display, ParticleDisplay secDisplay) {
new BukkitRunnable() {
final double addition = Math.PI * 0.1;
final double rateDiv = Math.PI / rate;
double times = Math.PI / 4;
public void run() {
times += addition;
for (double theta = 0; theta <= PII; theta += rateDiv) {
double x = times * Math.cos(theta);
double y = 2 * Math.exp(-0.1 * times) * Math.sin(times) + 1.5;
double z = times * Math.sin(theta);
display.spawn(x, y, z);
theta = theta + Math.PI / 64;
x = times * Math.cos(theta);
//y = 2 * Math.exp(-0.1 * times) * Math.sin(times) + 1.5;
z = times * Math.sin(theta);
secDisplay.spawn(x, y, z);
}
if (times > 20) cancel();
}
}.runTaskTimerAsynchronously(plugin, 0L, 1L);
}
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onJoin(PlayerJoinEvent e) {
Player player = e.getPlayer();
player.setCanPickupItems(false);
NPCManager npcManager = this.expansion.getNPCManager();
NPC npc = npcManager.getNPC(player);
if(npc != null) npc.despawn(DespawnReason.PLUGIN);
Runnable task = () -> {
punish(player);
player.setCanPickupItems(true);
};
JavaPlugin plugin = this.expansion.getPlugin().getPlugin();
BukkitScheduler scheduler = Bukkit.getScheduler();
scheduler.runTaskLater(plugin, task, 1L);
}
/**
* Calls the specified consumer (if it's not null) with the specified parameter,
* catching and logging all exceptions it might throw.
*
* @param callback the consumer to call if it isn't null
* @param event the value the consumer should accept
* @param callbackName the name of the action, used for logging
* @param <T> the type of the value the consumer is accepting
*/
private <T extends InventoryEvent> void callCallback(@Nullable Consumer<T> callback,
@NotNull T event, @NotNull String callbackName) {
if (callback == null) {
return;
}
try {
callback.accept(event);
} catch (Throwable t) {
Logger logger = JavaPlugin.getProvidingPlugin(getClass()).getLogger();
String message = "Exception while handling " + callbackName + " in inventory '" + title + "', state=" + state;
if (event instanceof InventoryClickEvent) {
InventoryClickEvent clickEvent = (InventoryClickEvent) event;
message += ", slot=" + clickEvent.getSlot();
}
logger.log(Level.SEVERE, message, t);
}
}
public File getOpenerConfigFile() {
File openersDir = new File(JavaPlugin.getPlugin(CratesPlus.class).getDataFolder(), "openers");
if (!openersDir.exists())
if (!openersDir.mkdirs())
return null;
File configurationFile = new File(openersDir, getName() + ".yml");
if (!configurationFile.exists())
try {
if (!configurationFile.createNewFile())
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
return configurationFile;
}
@Before
public void setUpPlugin() throws IOException {
File dataFolder = temporaryFolder.newFolder();
// Set mock server
setField(Bukkit.class, "server", null, server);
given(server.getLogger()).willReturn(mock(Logger.class));
// PluginDescriptionFile is final and so cannot be mocked
PluginDescriptionFile descriptionFile = new PluginDescriptionFile(
"PerWorldInventory", "N/A", PerWorldInventory.class.getCanonicalName());
JavaPluginLoader pluginLoader = new JavaPluginLoader(server);
plugin = new PerWorldInventory(pluginLoader, descriptionFile, dataFolder, null);
setField(JavaPlugin.class, "logger", plugin, mock(PluginLogger.class));
Injector injector = new InjectorBuilder().addDefaultHandlers("me.gnat008.perworldinventory").create();
injector.register(PermissionManager.class, permissionManager);
injector.register(ConvertCommand.class, convertCommand);
injector.register(HelpCommand.class, helpCommand);
injector.register(PerWorldInventoryCommand.class, pwiCommand);
injector.register(ReloadCommand.class, reloadCommand);
injector.register(SetWorldDefaultCommand.class, setWorldDefaultsCommand);
injector.register(VersionCommand.class, versionCommand);
plugin.registerCommands(injector);
TestHelper.setField(PerWorldInventory.class, "permissionManager", plugin, permissionManager);
}
/**
* Initializes a new commandExecutor by all required parameters
*
* @param command command
* @param useAge useAge
* @param description description
* @param permission permission
* @param permissionMessage permissionMessage
* @param plugin plugin
*/
public UnRegistered(String command, String useAge, String description, String permission, String permissionMessage, JavaPlugin plugin) {
super(command);
if (useAge == null)
throw new IllegalArgumentException("Useage cannot be null!");
if (description == null)
throw new IllegalArgumentException("Description cannot be null!");
if (permission == null)
throw new IllegalArgumentException("Permission cannot be null!");
if (permissionMessage == null)
throw new IllegalArgumentException("PermissionMessage cannot be null!");
if (plugin == null)
throw new IllegalArgumentException("Plugin cannot be null!");
this.description = description;
this.usageMessage = useAge;
this.plugin = plugin;
this.setPermission(permission);
this.setPermissionMessage(permissionMessage);
this.setAliases(new ArrayList<>());
this.registerDynamicCommand(command);
}
@Before
public void setUpPlugin() throws IOException {
File dataFolder = temporaryFolder.newFolder();
// Set mock server
setField(Bukkit.class, "server", null, server);
given(server.getLogger()).willReturn(mock(Logger.class));
// PluginDescriptionFile is final and so cannot be mocked
PluginDescriptionFile descriptionFile = new PluginDescriptionFile(
"PerWorldInventory", "N/A", PerWorldInventory.class.getCanonicalName());
JavaPluginLoader pluginLoader = new JavaPluginLoader(server);
plugin = new PerWorldInventory(pluginLoader, descriptionFile, dataFolder, null);
setField(JavaPlugin.class, "logger", plugin, mock(PluginLogger.class));
Injector injector = new InjectorBuilder().addDefaultHandlers("me.gnat008.perworldinventory").create();
injector.register(PermissionManager.class, permissionManager);
injector.register(ConvertCommand.class, convertCommand);
injector.register(HelpCommand.class, helpCommand);
injector.register(PerWorldInventoryCommand.class, pwiCommand);
injector.register(ReloadCommand.class, reloadCommand);
injector.register(SetWorldDefaultCommand.class, setWorldDefaultsCommand);
injector.register(VersionCommand.class, versionCommand);
plugin.registerCommands(injector);
TestHelper.setField(PerWorldInventory.class, "permissionManager", plugin, permissionManager);
}
/**
* Package-private constructor. Use {@link Skript#registerAddon(JavaPlugin)} to get a SkriptAddon for your plugin.
*
* @param p
*/
SkriptAddon(final JavaPlugin p) {
plugin = p;
name = "" + p.getName();
Version v;
try {
v = new Version("" + p.getDescription().getVersion());
} catch (final IllegalArgumentException e) {
final Matcher m = Pattern.compile("(\\d+)(?:\\.(\\d+)(?:\\.(\\d+))?)?").matcher(p.getDescription().getVersion());
if (!m.find())
throw new IllegalArgumentException("The version of the plugin " + p.getName() + " does not contain any numbers: " + p.getDescription().getVersion());
v = new Version(Utils.parseInt("" + m.group(1)), m.group(2) == null ? 0 : Utils.parseInt("" + m.group(2)), m.group(3) == null ? 0 : Utils.parseInt("" + m.group(3)));
Skript.warning("The plugin " + p.getName() + " uses a non-standard version syntax: '" + p.getDescription().getVersion() + "'. Skript will use " + v + " instead.");
}
version = v;
}
/**
* Sends an action bar to a player for a specific amount of ticks.
*
* @param player the player to send the action bar to.
* @param message the message to send.
* @param duration the duration to keep the action bar in ticks.
* @see #sendActionBarWhile(JavaPlugin, Player, String, Callable)
* @since 1.0.0
*/
public static void sendActionBar(@Nonnull JavaPlugin plugin, @Nonnull Player player, @Nullable String message, long duration) {
if (duration < 1) return;
new BukkitRunnable() {
long repeater = duration;
@Override
public void run() {
sendActionBar(player, message);
repeater -= 40L;
if (repeater - 40L < -20L) cancel();
}
}.runTaskTimerAsynchronously(plugin, 0L, 40L);
}
@Override
public double getHeight() {
HologramPlugin plugin = JavaPlugin.getPlugin(HologramPlugin.class);
if (plugin.getEntityController().getMinecraftVersion() == MinecraftVersion.V1_8_R1) {
return 1.60;
}
return 0.5;
}
/**
* Spawns a galaxy-like vortex.
* Note that the speed of the particle is important.
* Speed 0 will spawn static lines.
*
* @param plugin the timer handler.
* @param points the points of the vortex.
* @param rate the speed of the vortex.
* @return the task handling the animation.
* @since 2.0.0
*/
public static BukkitTask vortex(JavaPlugin plugin, int points, double rate, ParticleDisplay display) {
double rateDiv = Math.PI / rate;
display.directional();
return new BukkitRunnable() {
double theta = 0;
@Override
public void run() {
theta += rateDiv;
for (int i = 0; i < points; i++) {
// Calculate our starting point in a circle radius.
double multiplier = (PII * ((double) i / points));
double x = Math.cos(theta + multiplier);
double z = Math.sin(theta + multiplier);
// Calculate our direction of the spreading particles based on their angle.
double angle = Math.atan2(z, x);
double xDirection = Math.cos(angle);
double zDirection = Math.sin(angle);
display.offset(xDirection, 0, zDirection);
display.spawn(x, 0, z);
}
}
}.runTaskTimerAsynchronously(plugin, 0L, 1L);
}
public static void init(JavaPlugin plugin) throws SQLException {
hostname = plugin.getConfig().getString("mysql.hostname");
port = plugin.getConfig().getString("mysql.port");
db_name = plugin.getConfig().getString("mysql.db_name");
username = plugin.getConfig().getString("mysql.username");
password = plugin.getConfig().getString("mysql.password");
salt = plugin.getConfig().getString("salt");
dsn = "jdbc:mysql://"+hostname+":"+port+"/"+db_name;
connect();
}
@Override
public boolean show() {
if (isHidden()) {
HologramPlugin plugin = JavaPlugin.getPlugin(HologramPlugin.class);
nameable = plugin.getEntityController().spawnNameable(this, getLocation());
nameable.setName(text);
}
return true;
}
/**
* Manage custom configurations and files
*/
public ConfigHandler(JavaPlugin plugin) {
Instance = this;
this.plugin = plugin;
this.loadDefaults();
this.setupLogger();
}
@Override
public void onEnable() {
ICombatLogX combat = getPlugin();
JavaPlugin plugin = combat.getPlugin();
PluginManager manager = Bukkit.getPluginManager();
manager.registerEvents(new ListenerNotifier(this), plugin);
CommandNotifier commandNotifier = new CommandNotifier(this);
combat.registerCommand("notifier", commandNotifier, "Toggle the boss bar, scoreboard, and action bar.", "/notifier bossbar/actionbar/scoreboard", "clx-toggle");
hookIfEnabled("MVdWPlaceholderAPI");
hookIfEnabled("PlaceholderAPI");
hookIfEnabled("TitleManager");
}
/**
* DO NOT CALL ME, IT JUST A INTERNAL METHOD, BUT BECAUSE CROSS-PACKAGE ACCESS, IT IS PUBLIC, SO DO NOT EXECUTE IT.
* Go away =w=
*
* @param qs The QuickShop plugin instance
*/
public static void setupApi(@NotNull JavaPlugin qs) {
if(!(qs instanceof QuickShop)){
throw new IllegalArgumentException("You can't setup API, it should only access by QuickShop internal calling.");
}
plugin = (QuickShop) qs;
}
public Assemble(JavaPlugin plugin, AssembleAdapter adapter) {
if (plugin == null) {
throw new RuntimeException("Assemble can not be instantiated without a plugin instance!");
}
this.plugin = plugin;
this.adapter = adapter;
this.boards = new ConcurrentHashMap<>();
this.setup();
}
public void registerListener(Expansion expansion, Listener listener) {
PluginManager manager = Bukkit.getPluginManager();
JavaPlugin plugin = this.plugin.getPlugin();
manager.registerEvents(listener, plugin);
this.expansionListenerMap.computeIfAbsent(expansion, e -> new ArrayList<>()).add(listener);
}
/**
* Simply an alias to register the Inventory listeners for a certain plugin.
* Intended to improve code readability.
*
* @param plugin The Spigot plugin instance that you wish to register the listeners for.
*/
public static void prepare(JavaPlugin plugin){
if(inventoryListenerGUI == null){
inventoryListenerGUI = new InventoryListenerGUI();
plugin.getServer().getPluginManager().registerEvents(inventoryListenerGUI, plugin);
}
}
@Override
public @Nullable <T extends Plugin> T getPlugin(Class<T> cls) {
try {
return (T) JavaPlugin.getPlugin(cls.asSubclass(JavaPlugin.class));
} catch(IllegalArgumentException e) {
return null;
}
}
/**
* Registers a tag (ie. !location) to a class using a supplied represented and constructed class.
* <br><br>
*
* <b>Fails to register if:</b><br>
* <ol>
* <li> the class being registered doesn't match the type used in the constructed and represented classes
* <li> the class is already registered
* <li> the tag is already registered
* <ol>
* <br>
* @param plugin
* @param tag tag being registered
* @param c class being registered
* @param rc represented class
* @param cc constructed class
* <br>
* @see me.sashie.skriptyaml.api.RepresentedClass
* @see me.sashie.skriptyaml.api.ConstructedClass
*
*/
public static void registerTag(JavaPlugin plugin, String tag, Class<?> c, RepresentedClass<?> rc, ConstructedClass<?> cc) {
String prefix = plugin.getName().toLowerCase() + "-";
if (!tag.startsWith(prefix))
tag = prefix + tag;
if (!REGISTERED_TAGS.containsKey(tag)) {
if (!representer.contains(c)) {
if (SkriptYamlUtils.getType(rc.getClass()) == c) {
if (SkriptYamlUtils.getType(cc.getClass()) == c) {
REGISTERED_TAGS.put(tag, plugin.getName());
representer.register(tag, c, rc);
constructor.register(tag, cc);
} else {
warn("The class '" + c.getSimpleName() + "' that the plugin '" + plugin.getName()
+ "' is trying to register does not match constructed class '"
+ SkriptYamlUtils.getType(cc.getClass()).getSimpleName() + "' for constructor '"
+ cc.getClass().getSimpleName() + "' the tag '" + tag + "' was not registered");
}
} else {
warn("The class '" + c.getSimpleName() + "' that the plugin '" + plugin.getName()
+ "' is trying to register does not match represented class '"
+ SkriptYamlUtils.getType(rc.getClass()).getSimpleName() + "' for representer '"
+ rc.getClass().getSimpleName() + "' the tag '" + tag + "' was not registered");
}
} else {
warn("The class '" + c.getSimpleName() + "' that the plugin '" + plugin.getName()
+ "' is trying to register for the tag '" + tag + "' is already registered");
}
} else {
warn("The plugin '" + plugin.getName() + "' is trying to register the tag '" + tag
+ "' but it's already registered to '" + REGISTERED_TAGS.get(tag) + "'");
}
}
public WorldBorderDataTagType(JavaPlugin javaPlugin) {
this.sizeKey = new NamespacedKey(javaPlugin, "size");
this.xKey = new NamespacedKey(javaPlugin, "center_x");
this.zKey = new NamespacedKey(javaPlugin, "center_z");
this.damageBufferInBlocksKey = new NamespacedKey(javaPlugin, "damage_buffer_in_blocks");
this.damageAmountKey = new NamespacedKey(javaPlugin, "damage_amount");
this.warningTimeSecondsKey = new NamespacedKey(javaPlugin, "warning_time_seconds");
this.warningDistanceKey = new NamespacedKey(javaPlugin, "warning_distance");
}
public AdditionsAPIInitializationEvent addResourcePack(JavaPlugin plugin, InputStream inputstream) {
try {
ResourcePackManager.registerResource(plugin, inputstream);
} catch (IOException e) {
e.printStackTrace();
}
return this;
}
/**
* copy a resource file inside the plugin's jar file
*/
public static void copyResource(JavaPlugin plugin, String resource, File fileOut) throws IOException {
InputStream in = plugin.getResource(resource);
if (!fileOut.exists()) {
createFileAndPath(fileOut);
}
FileOutputStream out = new FileOutputStream(fileOut);
copyStreams(in, out);
}
/**
*
* @param plugin
* @return the jar file of the given plugin
*/
public static String getPluginJarPath(JavaPlugin plugin) {
String path = new File(plugin.getClass().getProtectionDomain().getCodeSource().getLocation().getPath())
.getAbsolutePath();
try {
path = URLDecoder.decode(path, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return path;
}
/**
* Places an undos
* @param counter counter
* @param container container
* @param containers containers
* @param nextContainer nextContainer
*/
private void placeUndo(final int counter, final Container container, final List<Container> containers, final int nextContainer) {
if (counter > 100) {
Bukkit.getServer().getScheduler().runTaskLater(JavaPlugin.getPlugin(AstralEditPlugin.class), () -> this.placeUndoCalc(0, container, containers, nextContainer), 1L);
} else {
this.placeUndoCalc(counter, container, containers, nextContainer);
}
}
/**
* Initializes a new commandExecutor by command, plugin
*
* @param command command
* @param plugin plugin
*/
public Registered(String command, JavaPlugin plugin) {
super();
if (plugin == null)
throw new IllegalArgumentException("Plugin cannot be null!");
if (command == null)
throw new IllegalArgumentException("Command cannot be null!");
this.plugin = plugin;
plugin.getCommand(command).setExecutor(this);
}
@Override
public void onEnable() {
saveDefaultConfig("logger.yml");
ListenerLogger listener = new ListenerLogger(this);
JavaPlugin plugin = getPlugin().getPlugin();
Bukkit.getPluginManager().registerEvents(listener, plugin);
}
@Before
public void setUp() {
PowerMockito.mockStatic(BetonQuest.class);
BetonQuest betonQuestInstance = Mockito.mock(BetonQuest.class);
PowerMockito.suppress(MemberMatcher.methodsDeclaredIn(JavaPlugin.class));
PowerMockito.when(BetonQuest.getInstance()).thenReturn(betonQuestInstance);
PowerMockito.mockStatic(LogUtils.class);
PowerMockito.when(LogUtils.getLogger()).thenReturn(Logger.getGlobal());
PowerMockito.mockStatic(Config.class);
PowerMockito.when(Config.getString("config.journal.lines_per_page")).thenReturn("13");
PowerMockito.when(Config.getString("config.journal.chars_per_line")).thenReturn("19");
}