org.bukkit.Bukkit Java Examples

The following examples show how to use org.bukkit.Bukkit. 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: StructureUtil.java    From Civs with GNU General Public License v3.0 7 votes vote down vote up
public static void removeBoundingBox(UUID uuid) {
    Player player = Bukkit.getPlayer(uuid);
    if (player == null || !player.isOnline()) {
        return;
    }
    StructureUtil.BoundingBox boundingBox = boundingBoxes.get(uuid);
    if (boundingBox == null) {
        return;
    }
    Map<Location, Color> locations = boundingBoxes.get(uuid).getLocations();
    if (locations == null) {
        return;
    }
    if (!ConfigManager.getInstance().isUseParticleBoundingBoxes()) {
        for (Location location : locations.keySet()) {
            if (!Util.isLocationWithinSightOfPlayer(location)) {
                continue;
            }
            player.sendBlockChange(location, Material.AIR.createBlockData());
        }
    }
    boundingBoxes.remove(uuid);
}
 
Example #2
Source File: NicknameCommands.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void enable() {
    final PermissionAttachment attachment = Bukkit.getConsoleSender().addAttachment(plugin);
    Stream.of(
        PERMISSION,
        PERMISSION_GET,
        PERMISSION_SET,
        PERMISSION_ANY,
        PERMISSION_ANY_GET,
        PERMISSION_ANY_SET,
        PERMISSION_IMMEDIATE
    ).forEach(name -> {
        final Permission permission = new Permission(name, PermissionDefault.FALSE);
        pluginManager.addPermission(permission);
        attachment.setPermission(permission, true);
    });
}
 
Example #3
Source File: PunishmentCommands.java    From CardinalPGM with MIT License 6 votes vote down vote up
@Command(aliases = {"warn", "w"}, usage = "<player> [reason]", desc = "Warn a player.", min = 1)
@CommandPermissions("cardinal.punish.warn")
public static void warn(CommandContext cmd, CommandSender sender) throws CommandException {
    Player warned = Bukkit.getPlayer(cmd.getString(0));
    if (warned == null) {
        throw new CommandException(ChatConstant.ERROR_NO_PLAYER_MATCH.getMessage(ChatUtil.getLocale(sender)));
    }
    String reason = cmd.argsLength() > 1 ? cmd.getJoinedStrings(1) : "You have been warned!";
    ChatChannel channel = GameHandler.getGameHandler().getMatch().getModules().getModule(AdminChannel.class);
    channel.sendMessage("[" + ChatColor.GOLD + "A" + ChatColor.WHITE + "] " + ((sender instanceof Player) ? Teams.getTeamColorByPlayer((Player) sender) + ((Player) sender).getDisplayName() : ChatColor.YELLOW + "*Console") + ChatColor.GOLD + " warned " + Teams.getTeamColorByPlayer(warned) + warned.getDisplayName() + ChatColor.GOLD + " for " + reason);
    warned.sendMessage(ChatColor.RED + "" + ChatColor.MAGIC + "-------" + ChatColor.YELLOW + "WARNING" + ChatColor.RED + ChatColor.MAGIC + "-------");
    warned.sendMessage(ChatColor.GREEN + reason);
    warned.sendMessage(ChatColor.YELLOW + reason);
    warned.sendMessage(ChatColor.RED + reason);
    warned.sendMessage(ChatColor.RED + "" + ChatColor.MAGIC + "-------" + ChatColor.YELLOW + "WARNING" + ChatColor.RED + ChatColor.MAGIC + "-------");
}
 
Example #4
Source File: FriendsFeature.java    From AreaShop with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Delete a friend from the region.
 * @param player The UUID of the player to delete
 * @param by     The CommandSender that is adding the friend, or null
 * @return true if the friend has been added, false if adding a friend was cancelled by another plugin
 */
public boolean deleteFriend(UUID player, CommandSender by) {
	// Fire and check event
	DeletedFriendEvent event = new DeletedFriendEvent(getRegion(), Bukkit.getOfflinePlayer(player), by);
	Bukkit.getPluginManager().callEvent(event);
	if(event.isCancelled()) {
		plugin.message(by, "general-cancelled", event.getReason(), this);
		return false;
	}

	Set<String> friends = new HashSet<>(getRegion().getConfig().getStringList("general.friends"));
	friends.remove(player.toString());
	List<String> list = new ArrayList<>(friends);
	if(list.isEmpty()) {
		getRegion().setSetting("general.friends", null);
	} else {
		getRegion().setSetting("general.friends", list);
	}
	return true;
}
 
Example #5
Source File: PeopleMenu.java    From Civs with GNU General Public License v3.0 6 votes vote down vote up
private void alphabeticalSort(List<Civilian> civilians) {
    civilians.sort(new Comparator<Civilian>() {
        @Override
        public int compare(Civilian civilian1, Civilian civilian2) {
            OfflinePlayer offlinePlayer1 = Bukkit.getOfflinePlayer(civilian1.getUuid());
            OfflinePlayer offlinePlayer2 = Bukkit.getOfflinePlayer(civilian2.getUuid());
            try {
                return offlinePlayer1.getName().compareTo(offlinePlayer2.getName());
            } catch (Exception e) {
                Object[] args = { Civs.NAME, offlinePlayer1.getName(), offlinePlayer2.getName()};
                Civs.logger.log(Level.WARNING, "{0} Failed to compare name {1} with {2}", args);
                return 0;
            }
        }
    });
}
 
Example #6
Source File: VaultManager.java    From UhcCore with GNU General Public License v3.0 6 votes vote down vote up
public static void addMoney(final Player player, final double amount){
	Validate.notNull(player);

	if(!GameManager.getGameManager().getConfiguration().getVaultLoaded()){
		return;
	}

	if(economy == null){
		Bukkit.getLogger().warning("[UhcCore] Vault is not loaded! Couldn't pay "+amount+" to "+player.getName()+"!");
		return;
	}

	final OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(player.getUniqueId());

	Bukkit.getScheduler().runTaskAsynchronously(UhcCore.getPlugin(), () -> economy.depositPlayer(offlinePlayer, amount));
}
 
Example #7
Source File: ASkyBlock.java    From askyblock with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @return the netherWorld
 */
public static World getNetherWorld() {
    if (netherWorld == null && Settings.createNether) {
        if (Settings.useOwnGenerator) {
            return Bukkit.getServer().getWorld(Settings.worldName +"_nether");
        }
        if (plugin.getServer().getWorld(Settings.worldName + "_nether") == null) {
            Bukkit.getLogger().info("Creating " + plugin.getName() + "'s Nether...");
        }
        if (!Settings.newNether) {
            netherWorld = WorldCreator.name(Settings.worldName + "_nether").type(WorldType.NORMAL).environment(World.Environment.NETHER).createWorld();
        } else {
            netherWorld = WorldCreator.name(Settings.worldName + "_nether").type(WorldType.FLAT).generator(new ChunkGeneratorWorld())
                    .environment(World.Environment.NETHER).createWorld();
        }
        netherWorld.setMonsterSpawnLimit(Settings.monsterSpawnLimit);
        netherWorld.setAnimalSpawnLimit(Settings.animalSpawnLimit);
    }
    return netherWorld;
}
 
Example #8
Source File: Metrics.java    From QualityArmory with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Starts the Scheduler which submits our data every 30 minutes.
 */
private void startSubmitting() {
    final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags
    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            if (!plugin.isEnabled()) { // Plugin was disabled
                timer.cancel();
                return;
            }
            // Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler
            // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;)
            Bukkit.getScheduler().runTask(plugin, new Runnable() {
                @Override
                public void run() {
                    submitData();
                }
            });
        }
    }, 1000*60*5, 1000*60*30);
    // Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start
    // WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted!
    // WARNING: Just don't do it!
}
 
Example #9
Source File: ItemStack.java    From Kettle with GNU General Public License v3.0 6 votes vote down vote up
@Utility
public Map<String, Object> serialize() {
    Map<String, Object> result = new LinkedHashMap<String, Object>();

    result.put("type", getType().name());

    if (getDurability() != 0) {
        result.put("damage", getDurability());
    }

    if (getAmount() != 1) {
        result.put("amount", getAmount());
    }

    ItemMeta meta = getItemMeta();
    if (!Bukkit.getItemFactory().equals(meta, null)) {
        result.put("meta", meta);
    }

    return result;
}
 
Example #10
Source File: ChatItem.java    From ChatItem with GNU General Public License v3.0 6 votes vote down vote up
private boolean isMc112Orlater(){
    switch(getVersion(Bukkit.getServer())){
        case "v1_7_R1": return false;
        case "v1_7_R2": return false;
        case "v1_7_R3": return false;
        case "v1_7_R4": return false;
        case "v1_8_R1": return false;
        case "v1_8_R2": return false;
        case "v1_8_R3": return false;
        case "v1_9_R1": return false;
        case "v1_9_R2": return false;
        case "v1_10_R1": return false;
        case "v1_10_R2": return false;
        case "v1_11_R1": return false;
        default: return true;
    }
}
 
Example #11
Source File: VaultManager.java    From PlayerVaults with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Load the player's vault and return it.
 *
 * @param player The holder of the vault.
 * @param number The vault number.
 */
public Inventory loadOwnVault(Player player, int number, int size) {
    if (size % 9 != 0) {
        size = PlayerVaults.getInstance().getDefaultVaultSize();
    }

    PlayerVaults.debug("Loading self vault for " + player.getName() + " (" + player.getUniqueId() + ')');

    String title = Lang.VAULT_TITLE.toString().replace("%number", String.valueOf(number)).replace("%p", player.getName());
    VaultViewInfo info = new VaultViewInfo(player.getUniqueId().toString(), number);
    if (PlayerVaults.getInstance().getOpenInventories().containsKey(info.toString())) {
        PlayerVaults.debug("Already open");
        return PlayerVaults.getInstance().getOpenInventories().get(info.toString());
    }

    YamlConfiguration playerFile = getPlayerVaultFile(player.getUniqueId().toString(), true);
    VaultHolder vaultHolder = new VaultHolder(number);
    if (playerFile.getString(String.format(VAULTKEY, number)) == null) {
        PlayerVaults.debug("No vault matching number");
        Inventory inv = Bukkit.createInventory(vaultHolder, size, title);
        vaultHolder.setInventory(inv);
        return inv;
    } else {
        return getInventory(vaultHolder, player.getUniqueId().toString(), playerFile, size, number, title);
    }
}
 
Example #12
Source File: ArmorListener.java    From AdditionsAPI with MIT License 6 votes vote down vote up
@EventHandler(priority =  EventPriority.HIGHEST, ignoreCancelled = true)
public void playerInteractEvent(PlayerInteractEvent e){
	if(e.getAction() == Action.PHYSICAL) return;
	if(e.getAction() == Action.RIGHT_CLICK_AIR || e.getAction() == Action.RIGHT_CLICK_BLOCK){
		Player player = e.getPlayer();
		ArmorType newArmorType = ArmorType.matchType(e.getItem());
		if(newArmorType != null){
			if(newArmorType.equals(ArmorType.HELMET) && isAirOrNull(e.getPlayer().getInventory().getHelmet()) || newArmorType.equals(ArmorType.CHESTPLATE) && isAirOrNull(e.getPlayer().getInventory().getChestplate()) || newArmorType.equals(ArmorType.LEGGINGS) && isAirOrNull(e.getPlayer().getInventory().getLeggings()) || newArmorType.equals(ArmorType.BOOTS) && isAirOrNull(e.getPlayer().getInventory().getBoots())){
				ArmorEquipEvent armorEquipEvent = new ArmorEquipEvent(e.getPlayer(), EquipMethod.HOTBAR, ArmorType.matchType(e.getItem()), null, e.getItem());
				Bukkit.getServer().getPluginManager().callEvent(armorEquipEvent);
				if(armorEquipEvent.isCancelled()){
					e.setCancelled(true);
					player.updateInventory();
				}
			}
		}
	}
}
 
Example #13
Source File: MoreFutures.java    From HeavySpleef with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Add a callback to a {@link ListenableFuture}
 * to be run on the bukkit main thread
 * 
 * @param plugin The plugin registering the callback
 * @param future The {@link ListenableFuture} to add this callback
 * @param callback The callback to be called
 */
public static <T> void addBukkitSyncCallback(final Plugin plugin, ListenableFuture<T> future, final FutureCallback<T> callback) {
	Futures.addCallback(future, new FutureCallback<T>() {
		@Override
		public void onFailure(final Throwable cause) {
			Bukkit.getScheduler().runTask(plugin, new Runnable() {
				
				@Override
				public void run() {
					callback.onFailure(cause);
				}
			});
		}
		@Override
		public void onSuccess(final T result) {
			Bukkit.getScheduler().runTask(plugin, new Runnable() {
				
				@Override
				public void run() {
					callback.onSuccess(result);
				}
			});
		}
	});
}
 
Example #14
Source File: MojangUtils.java    From UhcCore with GNU General Public License v3.0 6 votes vote down vote up
public static String getPlayerName(String name){
    if (Bukkit.isPrimaryThread()){
        throw new RuntimeException("Requesting player UUID is not allowed on the primary thread!");
    }

    try {
        URL url = new URL("https://api.mojang.com/users/profiles/minecraft/" + name);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.connect();

        JsonParser parser = new JsonParser();
        JsonElement json = parser.parse(new InputStreamReader(connection.getInputStream()));

        connection.disconnect();

        if (!json.isJsonObject()){
            return name;
        }

        return json.getAsJsonObject().get("name").getAsString();
    }catch (IOException ex){
        ex.printStackTrace();
        return name;
    }
}
 
Example #15
Source File: AnimatedFrame.java    From AnimatedFrames with MIT License 6 votes vote down vote up
private void displayCurrentFrame() {
	MultiMapController controller = ((MultiMapController) this.mapWrappers[this.currentFrame].getController());
	for (Iterator<UUID> iterator = this.worldPlayers.iterator(); iterator.hasNext(); ) {
		OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(iterator.next());
		Player player = offlinePlayer != null ? offlinePlayer.getPlayer() : null;
		if (player != null) {
			if (player.getWorld().getName().equals(worldName)) {
				if (player.getLocation().distanceSquared(baseVector.toBukkitLocation(getWorld())) < plugin.maxAnimateDistanceSquared) {
					controller.showInFrames(player.getPlayer(), this.itemFrameIds);
				}
			}
		} else {
			iterator.remove();
			if (offlinePlayer != null) {
				for (MapWrapper wrapper : this.mapWrappers) {
					wrapper.getController().removeViewer(offlinePlayer);
				}
			}
		}
	}
}
 
Example #16
Source File: ArenaManager.java    From civcraft with GNU General Public License v2.0 6 votes vote down vote up
private static World createArenaWorld(ConfigArena arena, String name) {
	World world;
	world = Bukkit.getServer().getWorld(name);
	if (world == null) {
		WorldCreator wc = new WorldCreator(name);
		wc.environment(Environment.NORMAL);
		wc.type(WorldType.FLAT);
		wc.generateStructures(false);
		
		world = Bukkit.getServer().createWorld(wc);
		world.setAutoSave(false);
		world.setSpawnFlags(false, false);
		world.setKeepSpawnInMemory(false);
		ChunkCoord.addWorld(world);
	}
	
	return world;
}
 
Example #17
Source File: ProtectionsTests.java    From Civs with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void blockPlaceShouldNotBeCancelledInUnprotected() {
    RegionsTests.loadRegionTypeDirt();

    Player player = mock(Player.class);
    UUID uuid = new UUID(1, 2);
    when(player.getUniqueId()).thenReturn(uuid);

    Player player2 = mock(Player.class);
    UUID uuid2 = new UUID(1, 3);
    when(player2.getUniqueId()).thenReturn(uuid2);

    HashMap<UUID, String> owners = new HashMap<>();
    owners.put(uuid2, Constants.OWNER);
    Location regionLocation = new Location(Bukkit.getWorld("world"), 0,0,0);
    RegionManager.getInstance().addRegion(new Region("dirt", owners, regionLocation, RegionsTests.getRadii(), new HashMap<String, String>(),0));

    ProtectionHandler protectionHandler = new ProtectionHandler();
    BlockBreakEvent event = new BlockBreakEvent(TestUtil.block3, player);
    protectionHandler.onBlockBreak(event);
    assertFalse(event.isCancelled());
}
 
Example #18
Source File: Contributor.java    From CardinalPGM with MIT License 5 votes vote down vote up
public String getDisplayName() {
    if (uniqueId == null) return ChatColor.DARK_AQUA + name;
    if (Bukkit.getOfflinePlayer(uniqueId).isOnline()) {
        return Bukkit.getPlayer(uniqueId).getDisplayName();
    } else {
        return Rank.getPrefix(uniqueId) + ChatColor.DARK_AQUA + name;
    }
}
 
Example #19
Source File: SoundModule.java    From CardinalPGM with MIT License 5 votes vote down vote up
@EventHandler
public void onMatchEnd(MatchEndEvent event) {
    for (Player player : Bukkit.getOnlinePlayers()) {
        Players.playSoundEffect(player, event.getTeam().isPresent()
                && event.getTeam().get().contains(player) ? Sound.ENTITY_WITHER_DEATH : Sound.ENTITY_WITHER_SPAWN, 1f, 1f);
    }
}
 
Example #20
Source File: SystemCommand.java    From LagMonitor with MIT License 5 votes vote down vote up
private void displayWorldInfo(CommandSender sender) {
    int entities = 0;
    int chunks = 0;
    int livingEntities = 0;
    int tileEntities = 0;

    long usedWorldSize = 0;

    List<World> worlds = Bukkit.getWorlds();
    for (World world : worlds) {
        for (Chunk loadedChunk : world.getLoadedChunks()) {
            tileEntities += loadedChunk.getTileEntities().length;
        }

        livingEntities += world.getLivingEntities().size();
        entities += world.getEntities().size();
        chunks += world.getLoadedChunks().length;

        File worldFolder = Bukkit.getWorld(world.getUID()).getWorldFolder();
        usedWorldSize += LagUtils.getFolderSize(plugin.getLogger(), worldFolder.toPath());
    }

    sendMessage(sender, "Entities", String.format("%d/%d", livingEntities, entities));
    sendMessage(sender, "Tile Entities", String.valueOf(tileEntities));
    sendMessage(sender, "Loaded Chunks", String.valueOf(chunks));
    sendMessage(sender, "Worlds", String.valueOf(worlds.size()));
    sendMessage(sender, "World Size", readableBytes(usedWorldSize));
}
 
Example #21
Source File: LoadDependencies.java    From WildernessTp with MIT License 5 votes vote down vote up
private void loadFeudal(){
    if(wild.getConfig().getBoolean("Feudal")){
        if(Bukkit.getServer().getPluginManager().getPlugin("Feudal")==null){
            Bukkit.getServer().getPluginManager().disablePlugin(wild);
            wild.getLogger().info("Plugin will disable due to missing dependency Feudal");
        }else{
            wild.getLogger().info("Feudal hook enabled");
        }
    }
}
 
Example #22
Source File: EntityPacketPet.java    From EchoPet with GNU General Public License v3.0 5 votes vote down vote up
protected void addToPlayerList() {
    PacketPlayOutPlayerInfo playerInfo = new PacketPlayOutPlayerInfo(EnumPlayerInfoAction.ADD_PLAYER);
    PlayerInfoData infoData = new PlayerInfoData(playerInfo, (GameProfile) this.profile.getHandle(), 0, EnumGamemode.SPECTATOR, new ChatComponentText(""));
    injectToList(playerInfo, infoData);
    for (Player player : Bukkit.getOnlinePlayers()) {
        ServerUtil.sendPacket(playerInfo, player);
    }
}
 
Example #23
Source File: BungeeCordVariables.java    From ScoreboardStats with MIT License 5 votes vote down vote up
@Override
public void run() {
    Player sender = Iterables.getFirst(Bukkit.getOnlinePlayers(), null);
    if (sender != null) {
        ByteArrayDataOutput out = ByteStreams.newDataOutput();
        out.writeUTF("PlayerCount");
        out.writeUTF("ALL");

        sender.sendPluginMessage(plugin, BUNGEE_CHANNEL, out.toByteArray());
    }
}
 
Example #24
Source File: TownyHandler.java    From Shopkeepers with GNU General Public License v3.0 5 votes vote down vote up
public static boolean isCommercialArea(Location loc) {
	Plugin plugin = Bukkit.getPluginManager().getPlugin("Towny");
	if (plugin != null) {
		TownBlock townBlock = TownyUniverse.getTownBlock(loc);
		return townBlock.getType() == TownBlockType.COMMERCIAL;
	} else {
		return false;
	}
}
 
Example #25
Source File: ArmorStandDisplayItem.java    From QuickShop-Reremake with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void remove() {
    if (this.armorStand == null) {
        Util.debugLog("Ignore the armorStand removing because the armorStand not spawned.");
        return;
    }
    this.armorStand.remove();
    this.armorStand = null;
    this.guardedIstack = null;
    ShopDisplayItemDespawnEvent shopDisplayItemDespawnEvent =
            new ShopDisplayItemDespawnEvent(this.shop, this.originalItemStack, DisplayType.ARMORSTAND);
    Bukkit.getPluginManager().callEvent(shopDisplayItemDespawnEvent);
}
 
Example #26
Source File: ProtocolSupport.java    From ProtocolSupport with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void onDisable() {
	Bukkit.shutdown();
	if (!loaded) {
		return;
	}
	ServerPlatform.get().getInjector().onDisable();
}
 
Example #27
Source File: GameResetTask.java    From ZombieEscape with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void run() {
    gameArena.setRound(gameArena.getRound() + 1);
    if (gameArena.getRound() == 4) {
        for (Player player : Bukkit.getOnlinePlayers()) {
            player.teleport(plugin.getServerSpawn());
            player.getInventory().clear();
            player.getInventory().setArmorContents(null);
            player.getInventory().addItem(new ItemStackBuilder(Material.BOOK).withName("&aVote").build());
        }

        gameArena.setRound(1);
        gameArena.setGameState(GameState.RESETTING);
        Bukkit.getConsoleSender().sendMessage(Utils.color("&6Game reset task, resetting"));

        Messages.MATCH_OVER.broadcast();

        new BukkitRunnable() {
            @Override
            public void run() {
                if (gameArena.getArenaWorld() != null) {
                    Bukkit.unloadWorld(gameArena.getArenaWorld(), false);
                }

                gameArena.setGameState(GameState.WAITING);
                if (gameArena.shouldStart()) {
                    gameArena.startCountdown();
                } else {
                    Bukkit.getConsoleSender().sendMessage(Utils.color("&6Game reset task, waiting (shouldn't start)"));
                }
            }
        }.runTaskLater(plugin, 20 * 15);
    } else {
        gameArena.resetRound();
        Bukkit.getConsoleSender().sendMessage(Utils.color("&6Fired resetRound"));
    }
}
 
Example #28
Source File: LoadDependencies.java    From WildernessTp with MIT License 5 votes vote down vote up
private void loadGriefPreven() {
    if (wild.getConfig().getBoolean("GriefPrevention")) {
        if (Bukkit.getServer().getPluginManager().getPlugin("GriefPrevention") == null) {
            Bukkit.getServer().getPluginManager().disablePlugin(wild);
            wild.getLogger().info("Plugin will disable due to missing dependency GriefPrevention");
        } else {
            wild.getLogger().info("GriefPrevention hook enabled");
        }
    }
}
 
Example #29
Source File: QuestCommand.java    From BetonQuest with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Fires an event for an online player. It cannot work for offline players!
 */
private void handleEvents(CommandSender sender, String[] args) {
    // the player has to be specified every time
    if (args.length < 2 || (Bukkit.getPlayer(args[1]) == null && !args[1].equals("-"))) {
        LogUtils.getLogger().log(Level.FINE, "Player's name is missing or he's offline");
        sendMessage(sender, "specify_player");
        return;
    }
    String playerID = (args[1].equals("-")) ? null : PlayerConverter.getID(args[1]);
    if (args.length < 3) {
        LogUtils.getLogger().log(Level.FINE, "Event's ID is missing");
        sendMessage(sender, "specify_event");
        return;
    }
    EventID eventID;
    try {
        eventID = new EventID(null, args[2]);
    } catch (ObjectNotFoundException e) {
        sendMessage(sender, "error", new String[] {
                e.getMessage()
        });
        LogUtils.getLogger().log(Level.WARNING, "Could not find event: " + e.getMessage());
        LogUtils.logThrowable(e);
        return;
    }
    // fire the event
    BetonQuest.event(playerID, eventID);
    sendMessage(sender, "player_event", new String[] {
            eventID.generateInstruction().getInstruction()
    });
}
 
Example #30
Source File: UndergroundNether.java    From UhcCore with GNU General Public License v3.0 5 votes vote down vote up
public void build(){
	if(enable){
		MainConfiguration cfg = GameManager.getGameManager().getConfiguration();
		
		int occurrences = RandomUtils.randomInteger(minOccurrences, maxOccurrences);
		int worldSize = GameManager.getGameManager().getWorldBorder().getStartSize();
		World overworld = Bukkit.getWorld(cfg.getOverworldUuid());
		
		for(int i = 1; i <= occurrences ; i++){

			int randX = RandomUtils.randomInteger(-worldSize, worldSize);
			int randZ = RandomUtils.randomInteger(-worldSize, worldSize);
			Location randLoc = new Location(overworld,randX,cfg.getNetherPasteAtY(),randZ);
			
			try {
				// to do find loc
				SchematicHandler.pasteSchematic(randLoc, netherSchematic, 0);
			} catch (Exception e) {
				Bukkit.getLogger().severe("[UhcCore] Couldn't paste nether schematic at "+
						randLoc.getBlockX()+" "+randLoc.getBlockY()+" "+randLoc.getBlockZ());
				e.printStackTrace();
			}
		}
		
	}  
	
}