org.bukkit.Server Java Examples
The following examples show how to use
org.bukkit.Server.
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 check out the related API usage on the sidebar.
Example #1
Source File: Radiation.java From CraftserveRadiation with Apache License 2.0 | 6 votes |
@Override public void run() { Server server = plugin.getServer(); server.getOnlinePlayers().forEach(player -> { if (matcher.test(player)) { RadiationEvent event = new RadiationEvent(player); server.getPluginManager().callEvent(event); boolean showBossBar = event.shouldShowWarning(); boolean cancel = event.isCancelled(); if (!cancel) { this.hurt(player); addAffectedPlayer(player, showBossBar); return; } if (showBossBar) { addBossBar(player); } } else { removeAffectedPlayer(player, true); } }); }
Example #2
Source File: MetricsCustom.java From CratesPlus with GNU General Public License v3.0 | 6 votes |
/** * Gets the online player (backwards compatibility) * * @return online player amount */ private int getOnlinePlayers() { try { Method onlinePlayerMethod = Server.class.getMethod("getOnlinePlayers"); if (onlinePlayerMethod.getReturnType().equals(Collection.class)) { return ((Collection<?>) onlinePlayerMethod.invoke(Bukkit.getServer())).size(); } else { return ((Player[]) onlinePlayerMethod.invoke(Bukkit.getServer())).length; } } catch (Exception ex) { if (debug) { Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); } } return 0; }
Example #3
Source File: ModuleManager.java From ExploitFixer with GNU General Public License v3.0 | 6 votes |
public void reload(final Configuration configYml, final Configuration messagesYml, final Configuration spigotYml) { try { this.commandsModule.reload(configYml); this.connectionModule.reload(configYml); this.customPayloadModule.reload(configYml); this.itemsFixModule.reload(configYml); this.messagesModule.reload(messagesYml); this.notificationsModule.reload(configYml); this.packetsModule.reload(configYml); this.exploitPlayerManager.reload(); } catch (final NullPointerException e) { final Server server = plugin.getServer(); server.getLogger().log(Level.SEVERE, "Your ExploitFixer configuration is wrong, please reset it or the plugin wont work!"); server.getPluginManager().disablePlugin(plugin); e.printStackTrace(); } }
Example #4
Source File: VaultHandler.java From AuthMeReloaded with GNU General Public License v3.0 | 6 votes |
/** * Returns the Vault Permission interface. * * @param server the bukkit server instance * @return the vault permission instance * @throws PermissionHandlerException if the vault permission instance cannot be retrieved */ @VisibleForTesting Permission getVaultPermission(Server server) throws PermissionHandlerException { // Get the permissions provider service RegisteredServiceProvider<Permission> permissionProvider = server .getServicesManager().getRegistration(Permission.class); if (permissionProvider == null) { throw new PermissionHandlerException("Could not load permissions provider service"); } // Get the Vault provider and make sure it's valid Permission vaultPerms = permissionProvider.getProvider(); if (vaultPerms == null) { throw new PermissionHandlerException("Could not load Vault permissions provider"); } return vaultPerms; }
Example #5
Source File: PlanBukkitMocker.java From Plan with GNU Lesser General Public License v3.0 | 6 votes |
PlanBukkitMocker withServer() { Server serverMock = Mockito.mock(Server.class); doReturn("").when(serverMock).getIp(); doReturn("Bukkit").when(serverMock).getName(); doReturn("Bukkit").when(serverMock).getServerName(); doReturn(25565).when(serverMock).getPort(); doReturn("1.12.2").when(serverMock).getVersion(); doReturn("32423").when(serverMock).getBukkitVersion(); doReturn(TestConstants.SERVER_MAX_PLAYERS).when(serverMock).getMaxPlayers(); ConsoleCommandSender sender = Mockito.mock(ConsoleCommandSender.class); doReturn(sender).when(serverMock).getConsoleSender(); BukkitScheduler bukkitScheduler = Mockito.mock(BukkitScheduler.class); doReturn(bukkitScheduler).when(serverMock).getScheduler(); doReturn(serverMock).when(planMock).getServer(); return this; }
Example #6
Source File: PurgeTaskTest.java From AuthMeReloaded with GNU General Public License v3.0 | 6 votes |
@Test public void shouldStopTaskAndInformConsoleUser() { // given Set<String> names = newHashSet("name1", "name2"); PurgeTask task = new PurgeTask(purgeService, permissionsManager, null, names, new OfflinePlayer[0]); BukkitTask bukkitTask = mock(BukkitTask.class); given(bukkitTask.getTaskId()).willReturn(10049); ReflectionTestUtils.setField(BukkitRunnable.class, task, "task", bukkitTask); Server server = mock(Server.class); BukkitScheduler scheduler = mock(BukkitScheduler.class); given(server.getScheduler()).willReturn(scheduler); ReflectionTestUtils.setField(Bukkit.class, null, "server", server); ConsoleCommandSender consoleSender = mock(ConsoleCommandSender.class); given(server.getConsoleSender()).willReturn(consoleSender); task.run(); // Run for the first time -> results in empty names list // when task.run(); // then verify(scheduler).cancelTask(task.getTaskId()); verify(consoleSender).sendMessage(argThat(containsString("Database has been purged successfully"))); }
Example #7
Source File: SpringSpigotTestInitializer.java From mcspring-boot with MIT License | 5 votes |
private static Plugin mockPlugin() { Plugin plugin = mock(Plugin.class); when(plugin.getName()).thenReturn(PLUGIN_NAME); Server server = mockServer(); when(plugin.getServer()).thenReturn(server); FileConfiguration config = mockConfig(); when(plugin.getConfig()).thenReturn(config); when(server.getPluginManager().getPlugin(PLUGIN_NAME)).thenReturn(plugin); return plugin; }
Example #8
Source File: PerWorldInventoryInitializationTest.java From PerWorldInventory with GNU General Public License v3.0 | 5 votes |
@Test public void shouldInitializeAllServices() { // given Injector injector = new InjectorBuilder().addDefaultHandlers("me.gnat008.perworldinventory").create(); injector.register(PerWorldInventory.class, plugin); injector.register(Server.class, server); injector.register(PluginManager.class, pluginManager); injector.provide(DataFolder.class, dataFolder); injector.register(Settings.class, settings); injector.registerProvider(DataSource.class, DataSourceProvider.class); // when plugin.injectServices(injector); plugin.registerEventListeners(injector); plugin.registerCommands(injector); // then - check various samples assertThat(injector.getIfAvailable(GroupManager.class), not(nullValue())); assertThat(injector.getIfAvailable(DataSource.class), instanceOf(FlatFile.class)); assertThat(injector.getIfAvailable(PWIPlayerManager.class), not(nullValue())); verifyRegisteredListener(PluginListener.class); verifyRegisteredListener(PlayerGameModeChangeListener.class); CommandVerifier commandVerifier = new CommandVerifier(plugin, injector); commandVerifier.assertHasCommand("pwi", PerWorldInventoryCommand.class); commandVerifier.assertHasCommand("reload", ReloadCommand.class); commandVerifier.assertHasCommand("setworlddefault", SetWorldDefaultCommand.class); }
Example #9
Source File: ExploitFixer.java From ExploitFixer with GNU General Public License v3.0 | 5 votes |
@Override public void onEnable() { final Server server = this.getServer(); final BukkitScheduler scheduler = server.getScheduler(); this.configurationUtil = new ConfigurationUtil(this); createConfigurations(); final YamlConfiguration configYml = this.configurationUtil.getConfiguration("%datafolder%/config.yml"); final YamlConfiguration messagesYml = this.configurationUtil.getConfiguration("%datafolder%/messages.yml"); VersionUtil.initialize(server); exploitFixer = this; this.moduleManager = new ModuleManager(this, configYml, messagesYml); this.listenerInitializer = new ListenerInitializer(this, moduleManager); registerListeners(); registerCommands(); if (checkHamsterAPI()) { server.getMessenger().registerOutgoingPluginChannel(this, "BungeeCord"); this.hamsterAPIListenerInitializer = new HamsterAPIListenerInitializer(this, moduleManager); registerHamsterApi(); } else { scheduler.runTaskTimer(this, () -> this.getLogger().severe( "ExploitFixer requires HamsterAPI 0.0.8 or newer to work! Download: https://www.spigotmc.org/resources/78831/"), 20L, 20L); } scheduler.runTaskTimerAsynchronously(this, () -> { final ExploitPlayerManager exploitPlayerManager = moduleManager.getExploitPlayerManager(); exploitPlayerManager.clear(); }, 9000L, 9000L); }
Example #10
Source File: MetricsHandler.java From CraftserveRadiation with Apache License 2.0 | 5 votes |
public MetricsHandler(Plugin plugin, Server server, Logger logger, LugolsIodineEffect effect, LugolsIodinePotion potion) { this.plugin = Objects.requireNonNull(plugin, "plugin"); this.server = Objects.requireNonNull(server, "server"); this.logger = Objects.requireNonNull(logger, "logger"); this.effect = Objects.requireNonNull(effect, "effect"); this.potion = Objects.requireNonNull(potion, "potion"); }
Example #11
Source File: SpringSpigotTestInitializer.java From mcspring-boot with MIT License | 5 votes |
private static void setServer(Server server) { try { Field serverField = Bukkit.class.getDeclaredField("server"); serverField.setAccessible(true); serverField.set(null, server); } catch (Exception exception) { exception.printStackTrace(); } }
Example #12
Source File: ListenerInitializer.java From ExploitFixer with GNU General Public License v3.0 | 5 votes |
public void register() { this.registered = true; final Server server = this.plugin.getServer(); final PluginManager pluginManager = server.getPluginManager(); pluginManager.registerEvents(new PlayerCommandListener(plugin, moduleManager), plugin); pluginManager.registerEvents(new PlayerLoginListener(plugin, moduleManager), plugin); pluginManager.registerEvents(new PlayerQuitListener(moduleManager), plugin); }
Example #13
Source File: ExploitPlayerManager.java From ExploitFixer with GNU General Public License v3.0 | 5 votes |
ExploitPlayerManager(final Plugin plugin, final Server server, final ModuleManager moduleManager) { this.plugin = plugin; this.server = server; this.moduleManager = moduleManager; this.punishments = 0; reload(); }
Example #14
Source File: BungeeManager.java From FastLogin with MIT License | 5 votes |
private void registerPluginChannels() { Server server = Bukkit.getServer(); // check for incoming messages from the bungeecord version of this plugin String groupId = plugin.getName(); String forceChannel = NamespaceKey.getCombined(groupId, LoginActionMessage.FORCE_CHANNEL); server.getMessenger().registerIncomingPluginChannel(plugin, forceChannel, new BungeeListener(plugin)); // outgoing String successChannel = new NamespaceKey(groupId, SUCCESS_CHANNEL).getCombinedName(); String changeChannel = new NamespaceKey(groupId, CHANGE_CHANNEL).getCombinedName(); server.getMessenger().registerOutgoingPluginChannel(plugin, successChannel); server.getMessenger().registerOutgoingPluginChannel(plugin, changeChannel); }
Example #15
Source File: PGMPlugin.java From PGM with GNU Affero General Public License v3.0 | 5 votes |
public PGMPlugin( PluginLoader loader, Server server, PluginDescriptionFile description, File dataFolder, File file) { super(loader, server, description, dataFolder, file); }
Example #16
Source File: ChatEventsTest.java From uSkyBlock with GNU General Public License v3.0 | 5 votes |
@Before public void setUp() { uSkyBlock fakePlugin = mock(uSkyBlock.class); Server fakeServer = mock(Server.class); when(fakePlugin.getServer()).thenReturn(fakeServer); fakeScheduler = mock(BukkitScheduler.class); when(fakeScheduler.runTask(any(Plugin.class), any(Runnable.class))).thenReturn(mock(BukkitTask.class)); when(fakeServer.getScheduler()).thenReturn(fakeScheduler); fakeLogic = spy(mock(ChatLogic.class)); doNothing().when(fakeLogic).sendMessage(any(), any(), any()); listener = new ChatEvents(fakeLogic, fakePlugin); }
Example #17
Source File: JavaPlugin.java From Kettle with GNU General Public License v3.0 | 5 votes |
final void init(PluginLoader loader, Server server, PluginDescriptionFile description, File dataFolder, File file, ClassLoader classLoader) { this.loader = loader; this.server = server; this.file = file; this.description = description; this.dataFolder = dataFolder; this.classLoader = classLoader; this.configFile = new File(dataFolder, "config.yml"); this.logger = new PluginLogger(this); }
Example #18
Source File: SpringSpigotTestInitializer.java From mcspring-boot with MIT License | 5 votes |
private static Server mockServer() { Server server = mock(Server.class); PluginManager pluginManager = mock(PluginManager.class); when(server.getPluginManager()).thenReturn(pluginManager); BukkitScheduler scheduler = mock(BukkitScheduler.class); when(server.getScheduler()).thenReturn(scheduler); setServer(server); return server; }
Example #19
Source File: NettyInjector.java From Bukkit-Connect with GNU General Public License v3.0 | 5 votes |
@SuppressWarnings("unchecked") public static int injectAndFindPort(Server server, NettyInjectHandler handler) throws Exception { Method serverGetHandle = server.getClass().getDeclaredMethod("getServer"); Object minecraftServer = serverGetHandle.invoke(server); // Get Server Connection Method serverConnectionMethod = null; for(Method method : minecraftServer.getClass().getSuperclass().getDeclaredMethods()) { if(!method.getReturnType().getSimpleName().equals("ServerConnection")) { continue; } serverConnectionMethod = method; break; } Object serverConnection = serverConnectionMethod.invoke(minecraftServer); // Get ChannelFuture List // TODO find the field dynamically List<ChannelFuture> channelFutureList = ReflectionUtils.getPrivateField(serverConnection.getClass(), serverConnection, List.class, ConnectPlugin.getProtocol().getNettyInjectorChannelFutureList()); // Iterate ChannelFutures int commonPort = 0; for(ChannelFuture channelFuture : channelFutureList) { // Get ChannelPipeline ChannelPipeline channelPipeline = channelFuture.channel().pipeline(); // Get ServerBootstrapAcceptor ChannelHandler serverBootstrapAcceptor = channelPipeline.last(); // Get Old ChildHandler ChannelInitializer<SocketChannel> oldChildHandler = ReflectionUtils.getPrivateField(serverBootstrapAcceptor.getClass(), serverBootstrapAcceptor, ChannelInitializer.class, "childHandler"); // Set New ChildHandler ReflectionUtils.setFinalField(serverBootstrapAcceptor.getClass(), serverBootstrapAcceptor, "childHandler", new NettyChannelInitializer(handler, oldChildHandler)); // Update Common Port commonPort = ((InetSocketAddress) channelFuture.channel().localAddress()).getPort(); } return commonPort; }
Example #20
Source File: Command.java From Kettle with GNU General Public License v3.0 | 5 votes |
public static void broadcastCommandMessage(CommandSender source, String message, boolean sendToSource) { String result = source.getName() + ": " + message; if (source instanceof BlockCommandSender) { BlockCommandSender blockCommandSender = (BlockCommandSender) source; if (blockCommandSender.getBlock().getWorld().getGameRuleValue("commandBlockOutput").equalsIgnoreCase("false")) { Bukkit.getConsoleSender().sendMessage(result); return; } } else if (source instanceof CommandMinecart) { CommandMinecart commandMinecart = (CommandMinecart) source; if (commandMinecart.getWorld().getGameRuleValue("commandBlockOutput").equalsIgnoreCase("false")) { Bukkit.getConsoleSender().sendMessage(result); return; } } Set<Permissible> users = Bukkit.getPluginManager().getPermissionSubscriptions(Server.BROADCAST_CHANNEL_ADMINISTRATIVE); String colored = ChatColor.GRAY + "" + ChatColor.ITALIC + "[" + result + ChatColor.GRAY + ChatColor.ITALIC + "]"; if (sendToSource && !(source instanceof ConsoleCommandSender)) { source.sendMessage(message); } for (Permissible user : users) { if (user instanceof CommandSender && user.hasPermission(Server.BROADCAST_CHANNEL_ADMINISTRATIVE)) { CommandSender target = (CommandSender) user; if (target instanceof ConsoleCommandSender) { target.sendMessage(result); } else if (target != source) { target.sendMessage(colored); } } } }
Example #21
Source File: ChatEvents.java From uSkyBlock with GNU General Public License v3.0 | 5 votes |
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onChatEvent(AsyncPlayerChatEvent e) { IslandChatEvent.Type toggle = logic.getToggle(e.getPlayer()); if (toggle != null) { e.setCancelled(true); Server server = plugin.getServer(); // Called via a sync task, because this listener might get called async. server.getScheduler().runTask(plugin, () -> server.getPluginManager().callEvent( new IslandChatEvent(e.getPlayer(), toggle, e.getMessage()))); } }
Example #22
Source File: AuthMeApiTest.java From AuthMeReloaded with GNU General Public License v3.0 | 5 votes |
@Test public void shouldUnregisterPlayerByName() { // given Server server = mock(Server.class); ReflectionTestUtils.setField(Bukkit.class, null, "server", server); String name = "tristan"; Player player = mock(Player.class); given(server.getPlayer(name)).willReturn(player); // when api.forceUnregister(name); // then verify(management).performUnregisterByAdmin(null, name, player); }
Example #23
Source File: RestartListener.java From ProjectAres with GNU Affero General Public License v3.0 | 5 votes |
@Inject RestartListener(Loggers loggers, RestartManager restartManager, MatchManager mm, Server server, AutoRestartConfiguration config) { this.restartManager = restartManager; this.logger = loggers.get(getClass()); this.mm = mm; this.server = server; this.config = config; this.matchLimit = config.matchLimit() > 0 ? config.matchLimit() : null; }
Example #24
Source File: NbtFactory.java From AdditionsAPI with MIT License | 5 votes |
private String getPackageName() { Server server = Bukkit.getServer(); String name = server != null ? server.getClass().getPackage().getName() : null; if (name != null && name.contains("craftbukkit")) { return name; } else { // Fallback return "org.bukkit.craftbukkit.v1_13_R1"; } }
Example #25
Source File: BukkitServerProperties.java From Plan with GNU Lesser General Public License v3.0 | 5 votes |
public BukkitServerProperties(Server server) { super( server.getName(), server.getPort(), server.getVersion(), server.getBukkitVersion(), server::getIp, server.getMaxPlayers() ); }
Example #26
Source File: BungeemodeListener.java From HeavySpleef with GNU General Public License v3.0 | 5 votes |
private boolean restartServer() { Server.Spigot spigot = Bukkit.spigot(); try { spigot.getClass().getMethod("restart"); //Ok, just restart using the default way spigot.restart(); return false; } catch (NoSuchMethodException | SecurityException e) { //Not available, try to access the RestartCommand via reflection try { Class<?> restartCommandClazz = Class.forName("org.spigotmc.RestartCommand"); Class<?> spigotConfigClazz = Class.forName("org.spigotmc.SpigotConfig"); Field field = spigotConfigClazz.getField("restartScript"); String restartScript = (String) field.get(null); Method restartMethod = restartCommandClazz.getDeclaredMethod("restart", File.class); restartMethod.invoke(null, new File(restartScript)); return true; } catch (ClassNotFoundException | NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e1) { addon.getLogger().log(Level.SEVERE, "Failed to restart server", e1); return false; } } }
Example #27
Source File: AuthMeApiTest.java From AuthMeReloaded with GNU General Public License v3.0 | 5 votes |
@Test public void shouldGetLastLocation() { // given String name = "Gary"; Player player = mockPlayerWithName(name); PlayerAuth auth = PlayerAuth.builder().name(name) .locWorld("world") .locX(12.4) .locY(24.6) .locZ(-438.2) .locYaw(3.41f) .locPitch(0.29f) .build(); given(playerCache.getAuth(name)).willReturn(auth); Server server = mock(Server.class); ReflectionTestUtils.setField(Bukkit.class, null, "server", server); World world = mock(World.class); given(server.getWorld(auth.getWorld())).willReturn(world); // when Location result = api.getLastLocation(player); // then assertThat(result, not(nullValue())); assertThat(result.getX(), equalTo(auth.getQuitLocX())); assertThat(result.getY(), equalTo(auth.getQuitLocY())); assertThat(result.getZ(), equalTo(auth.getQuitLocZ())); assertThat(result.getWorld(), equalTo(world)); assertThat(result.getYaw(), equalTo(auth.getYaw())); assertThat(result.getPitch(), equalTo(auth.getPitch())); }
Example #28
Source File: CommandMapUtil.java From LuckPerms with MIT License | 5 votes |
public static CommandMap getCommandMap(Server server) { try { return (CommandMap) COMMAND_MAP_FIELD.get(server.getPluginManager()); } catch (Exception e) { throw new RuntimeException("Could not get CommandMap", e); } }
Example #29
Source File: BukkitReflectionUtils.java From FastAsyncWorldedit with GNU General Public License v3.0 | 5 votes |
/** * check server version and class names */ public static void init() { if (Bukkit.getServer() != null) { if (Bukkit.getVersion().contains("MCPC") || Bukkit.getVersion().contains("Forge")) { forge = true; } final Server server = Bukkit.getServer(); final Class<?> bukkitServerClass = server.getClass(); String[] pas = bukkitServerClass.getName().split("\\."); if (pas.length == 5) { final String verB = pas[3]; preClassB = "org.bukkit.craftbukkit." + verB; } try { final Method getHandle = bukkitServerClass.getDeclaredMethod("getHandle"); final Object handle = getHandle.invoke(server); final Class handleServerClass = handle.getClass(); pas = handleServerClass.getName().split("\\."); if (pas.length == 5) { final String verM = pas[3]; preClassM = "net.minecraft.server." + verM; } } catch (final Exception ignored) { MainUtil.handleError(ignored); } } }
Example #30
Source File: Radiation.java From CraftserveRadiation with Apache License 2.0 | 5 votes |
public void enable() { Server server = this.plugin.getServer(); this.bossBar = this.config.bar().create(server, ChatColor.DARK_RED); this.task = new Task(); this.task.runTaskTimer(this.plugin, 20L, 20L); server.getPluginManager().registerEvents(this, this.plugin); }