类org.bukkit.command.CommandException源码实例Demo

下面列出了怎么用org.bukkit.command.CommandException的API类实例代码及写法,或者点击链接到github查看源代码。

@Test
public void shouldSendCommandErrorMessage() {
    when(commandLine.parse(any())).thenThrow(new CommandException("generic error"));

    CommandResult result = commandExecutor.execute("say", "hello");

    assertTrue(result.isExists());
    verify(commandLine).parse("say", "hello");
    assertEquals(ChatColor.RED + "generic error", result.getOutput().get(0));
}
 
源代码2 项目: Thermos   文件: CraftServer.java
public List<String> tabCompleteCommand(Player player, String message) {
    // Spigot Start
    if ( !org.spigotmc.SpigotConfig.tabComplete && !message.contains( " " ) )
    {
        return ImmutableList.of();
    }
    // Spigot End

    // Spigot Start
    List<String> completions = new ArrayList<String>();
    try {
        message = message.substring( 1 );
        List<String> bukkitCompletions = getCommandMap().tabComplete( player, message );
        if ( bukkitCompletions != null )
        {
            completions.addAll( bukkitCompletions );
        }
        List<String> vanillaCompletions = org.spigotmc.VanillaCommandWrapper.complete( player, message );
        if ( vanillaCompletions != null )
        {
            completions.addAll( vanillaCompletions );
        }
        // Spigot End
    } catch (CommandException ex) {
        player.sendMessage(ChatColor.RED + "An internal error occurred while attempting to tab-complete this command");
        getLogger().log(Level.SEVERE, "Exception when " + player.getName() + " attempted to tab complete " + message, ex);
    }

    return completions; // Spigot
}
 
源代码3 项目: RedProtect   文件: RedProtectUtil.java
private void initMysql() throws Exception {
    for (World world : Bukkit.getWorlds()) {

        String url = "jdbc:mysql://" + RedProtect.get().config.configRoot().mysql.host + "/";
        String reconnect = "?autoReconnect=true";
        String tableName = RedProtect.get().config.configRoot().mysql.table_prefix + world.getName();

        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e2) {
            RedProtect.get().logger.severe("Couldn't find the driver for MySQL! com.mysql.jdbc.Driver.");
            return;
        }
        PreparedStatement st = null;
        try {
            if (!checkTableExists(tableName)) {
                //create db
                Connection con = DriverManager.getConnection(url + RedProtect.get().config.configRoot().mysql.table_prefix + reconnect, RedProtect.get().config.configRoot().mysql.user_name, RedProtect.get().config.configRoot().mysql.user_pass);
                st = con.prepareStatement("CREATE TABLE `" + tableName + "` (name varchar(20) PRIMARY KEY NOT NULL, leaders longtext, admins longtext, members longtext, maxMbrX int, minMbrX int, maxMbrZ int, minMbrZ int, centerX int, centerZ int, minY int, maxY int, date varchar(10), wel longtext, prior int, world varchar(100), value Long not null, tppoint mediumtext, flags longtext, candelete tinyint(1)) CHARACTER SET utf8 COLLATE utf8_general_ci");
                st.executeUpdate();
                st.close();
                st = null;
                RedProtect.get().logger.info("Created table: " + tableName + "!");
            }
            addNewColumns(tableName);
        } catch (CommandException e3) {
            RedProtect.get().logger.severe("Couldn't connect to mysql! Make sure you have mysql turned on and installed properly, and the service is started.");
            throw new Exception("Couldn't connect to mysql!");
        } catch (SQLException e) {
            printJarVersion();
            e.printStackTrace();
            RedProtect.get().logger.severe("There was an error while parsing SQL, redProtect will still with actual DB setting until you change the connection options or check if a Mysql service is running. Use /rp reload to try again");
        } finally {
            if (st != null) {
                st.close();
            }
        }
    }
}
 
源代码4 项目: NovaGuilds   文件: CommandManager.java
/**
 * Executes a command
 *
 * @param command command enum
 * @param sender  sender instance
 * @param args    command arguments
 */
public void execute(CommandWrapper command, CommandSender sender, String[] args) {
	CommandExecutor executor = getExecutor(command);

	if(command.getPermission() != null && !command.hasPermission(sender)) {
		Message.CHAT_NOPERMISSIONS.send(sender);
		return;
	}

	if(!command.allowedSender(sender)) {
		Message.CHAT_CMDFROMCONSOLE.send(sender);
		return;
	}

	NovaPlayer nPlayer = PlayerManager.getPlayer(sender);

	if((sender instanceof Player) && (command.hasFlag(CommandWrapper.Flag.CONFIRM) && !Permission.NOVAGUILDS_ADMIN_NOCONFIRM.has(sender) && (nPlayer.getCommandExecutorHandler() == null || nPlayer.getCommandExecutorHandler().getState() != CommandExecutorHandler.State.CONFIRMED))) {
		nPlayer.newCommandExecutorHandler(command, args);
		nPlayer.getCommandExecutorHandler().executorVariable(command.getExecutorVariable());
	}
	else {
		if(executor instanceof CommandExecutor.Reversed) {
			((CommandExecutor.Reversed) executor).set(command.getExecutorVariable());
			command.executorVariable(null);
		}

		try {
			executor.execute(sender, args);
		}
		catch(Exception e) {
			LoggerUtils.exception(new CommandException("Unhandled exception executing command '" + command.getName() + "' in plugin NovaGuilds", e));
		}
	}
}
 
源代码5 项目: AreaShop   文件: GeneralRegion.java
/**
 * Run commands as the CommandsSender, replacing all tags with the relevant values.
 * @param sender   The sender that should perform the command
 * @param commands A list of the commands to run (without slash and with tags)
 */
public void runCommands(CommandSender sender, List<String> commands) {
	if(commands == null || commands.isEmpty()) {
		return;
	}

	for(String command : commands) {
		if(command == null || command.isEmpty()) {
			continue;
		}
		// It is not ideal we have to disable language replacements here, but otherwise giving language variables
		// to '/areashop message' by a command in the config gets replaced and messes up the fancy formatting.
		command = Message.fromString(command).replacements(this).noLanguageReplacements().getSingle();

		boolean result;
		String error = null;
		String stacktrace = null;
		try {
			result = plugin.getServer().dispatchCommand(sender, command);
		} catch(CommandException e) {
			result = false;
			error = e.getMessage();
			stacktrace = ExceptionUtils.getStackTrace(e);
		}
		boolean printed = false;
		if(!result) {
			printed = true;
			if(error != null) {
				AreaShop.warn("Command execution failed, command=" + command + ", error=" + error + ", stacktrace:");
				AreaShop.warn(stacktrace);
				AreaShop.warn("--- End of stacktrace ---");
			} else {
				AreaShop.warn("Command execution failed, command=" + command);
			}
		}
		if(!printed) {
			AreaShop.debug("Command run, executor=" + sender.getName() + ", command=" + command);
		}
	}
}
 
源代码6 项目: UhcCore   文件: PlayersManager.java
public void killOfflineUhcPlayer(UhcPlayer uhcPlayer, @Nullable Location location, Set<ItemStack> playerDrops, @Nullable Player killer){
	GameManager gm = GameManager.getGameManager();
	PlayersManager pm = gm.getPlayersManager();
	MainConfiguration cfg = gm.getConfiguration();

	if (uhcPlayer.getState() != PlayerState.PLAYING){
		Bukkit.getLogger().warning("[UhcCore] " + uhcPlayer.getName() + " died while already in 'DEAD' mode!");
		return;
	}

	// kill event
	if(killer != null){
		UhcPlayer uhcKiller = pm.getUhcPlayer(killer);

		uhcKiller.kills++;

		// Call Bukkit event
		UhcPlayerKillEvent killEvent = new UhcPlayerKillEvent(uhcKiller, uhcPlayer);
		Bukkit.getServer().getPluginManager().callEvent(killEvent);

		if(cfg.getEnableKillEvent()){
			double reward = cfg.getRewardKillEvent();
			List<String> killCommands = cfg.getKillCommands();
			if (reward > 0) {
				VaultManager.addMoney(killer, reward);
				if (!Lang.EVENT_KILL_REWARD.isEmpty()) {
					killer.sendMessage(Lang.EVENT_KILL_REWARD.replace("%money%", "" + reward));
				}
			}

			killCommands.forEach(cmd -> {
				try {
					Bukkit.dispatchCommand(Bukkit.getConsoleSender(), cmd.replace("%name%", killer.getName()));
				} catch (CommandException exception) {
					Bukkit.getLogger().warning("[UhcCore] Failed to execute kill reward command: " + cmd);
					exception.printStackTrace();
				}
			});

		}
	}

	// Store drops in case player gets re-spawned.
	uhcPlayer.getStoredItems().clear();
	uhcPlayer.getStoredItems().addAll(playerDrops);

	// eliminations
	ScenarioManager sm = gm.getScenarioManager();
	if (!sm.isActivated(Scenario.SILENTNIGHT) || !((SilentNightListener) sm.getScenarioListener(Scenario.SILENTNIGHT)).isNightMode()) {
		gm.broadcastInfoMessage(Lang.PLAYERS_ELIMINATED.replace("%player%", uhcPlayer.getName()));
	}

	if(cfg.getRegenHeadDropOnPlayerDeath()){
		playerDrops.add(UhcItems.createRegenHead(uhcPlayer));
	}

	if(location != null && cfg.getEnableGoldenHeads()){
		if (cfg.getPlaceHeadOnFence() && !gm.getScenarioManager().isActivated(Scenario.TIMEBOMB)){
			// place head on fence
			Location loc = location.clone().add(1,0,0);
			loc.getBlock().setType(UniversalMaterial.OAK_FENCE.getType());
			loc.add(0, 1, 0);
			loc.getBlock().setType(UniversalMaterial.PLAYER_HEAD_BLOCK.getType());

			Skull skull = (Skull) loc.getBlock().getState();
			VersionUtils.getVersionUtils().setSkullOwner(skull, uhcPlayer);
			skull.setRotation(BlockFace.NORTH);
			skull.update();
		}else{
			playerDrops.add(UhcItems.createGoldenHeadPlayerSkull(uhcPlayer.getName(), uhcPlayer.getUuid()));
		}
	}

	if(location != null && cfg.getEnableExpDropOnDeath()){
		UhcItems.spawnExtraXp(location, cfg.getExpDropOnDeath());
	}

	if (location != null){
		playerDrops.forEach(item -> location.getWorld().dropItem(location, item));
	}

	uhcPlayer.setState(PlayerState.DEAD);
	pm.strikeLightning(uhcPlayer);
	pm.playSoundPlayerDeath();

	pm.checkIfRemainingPlayers();
}
 
源代码7 项目: UhcCore   文件: PlayerDeathListener.java
@EventHandler(priority = EventPriority.HIGH)
public void onPlayerDeath(PlayerDeathEvent event){
	Player player = event.getEntity();
	GameManager gm = GameManager.getGameManager();
	PlayersManager pm = gm.getPlayersManager();
	MainConfiguration cfg = gm.getConfiguration();
	UhcPlayer uhcPlayer = pm.getUhcPlayer(player);

	if (uhcPlayer.getState() != PlayerState.PLAYING){
		Bukkit.getLogger().warning("[UhcCore] " + player.getName() + " died while already in 'DEAD' mode!");
		player.kickPlayer("Don't cheat!");
		return;
	}

	pm.setLastDeathTime();

	// kill event
	Player killer = player.getKiller();
	if(killer != null){
		UhcPlayer uhcKiller = pm.getUhcPlayer(killer);

		uhcKiller.kills++;

		// Call Bukkit event
		UhcPlayerKillEvent killEvent = new UhcPlayerKillEvent(uhcPlayer, uhcKiller);
		Bukkit.getServer().getPluginManager().callEvent(killEvent);

		if(cfg.getEnableKillEvent()){
			double reward = cfg.getRewardKillEvent();
			List<String> killCommands = cfg.getKillCommands();
			if (reward > 0) {
				VaultManager.addMoney(killer, reward);
				if (!Lang.EVENT_KILL_REWARD.isEmpty()) {
					killer.sendMessage(Lang.EVENT_KILL_REWARD.replace("%money%", "" + reward));
				}
			}
			// If the list is empty, this will never execute
			killCommands.forEach(cmd -> {
				try {
					Bukkit.dispatchCommand(Bukkit.getConsoleSender(), cmd.replace("%name%", uhcKiller.getRealName()));
				} catch (CommandException exception){
					Bukkit.getLogger().warning("[UhcCore] Failed to execute kill reward command: " + cmd);
					exception.printStackTrace();
				}
			});
		}
	}

	// Store drops in case player gets re-spawned.
	uhcPlayer.getStoredItems().clear();
	uhcPlayer.getStoredItems().addAll(event.getDrops());

	// eliminations
	ScenarioManager sm = gm.getScenarioManager();
	if (!sm.isActivated(Scenario.SILENTNIGHT) || !((SilentNightListener) sm.getScenarioListener(Scenario.SILENTNIGHT)).isNightMode()) {
		gm.broadcastInfoMessage(Lang.PLAYERS_ELIMINATED.replace("%player%", player.getName()));
	}

	if(cfg.getRegenHeadDropOnPlayerDeath()){
		event.getDrops().add(UhcItems.createRegenHead(uhcPlayer));
	}

	if(cfg.getEnableGoldenHeads()){
		if (cfg.getPlaceHeadOnFence() && !gm.getScenarioManager().isActivated(Scenario.TIMEBOMB)){
			// place head on fence
			Location loc = player.getLocation().clone().add(1,0,0);
			loc.getBlock().setType(UniversalMaterial.OAK_FENCE.getType());
			loc.add(0, 1, 0);
			loc.getBlock().setType(UniversalMaterial.PLAYER_HEAD_BLOCK.getType());

			Skull skull = (Skull) loc.getBlock().getState();
			VersionUtils.getVersionUtils().setSkullOwner(skull, uhcPlayer);
			skull.setRotation(BlockFace.NORTH);
			skull.update();
		}else{
			event.getDrops().add(UhcItems.createGoldenHeadPlayerSkull(player.getName(), player.getUniqueId()));
		}
	}

	if(cfg.getEnableExpDropOnDeath()){
		UhcItems.spawnExtraXp(player.getLocation(), cfg.getExpDropOnDeath());
	}

	uhcPlayer.setState(PlayerState.DEAD);
	pm.strikeLightning(uhcPlayer);
	pm.playSoundPlayerDeath();

	// handle player leaving the server
	boolean canContinueToSpectate = player.hasPermission("uhc-core.spectate.override")
			|| cfg.getCanSpectateAfterDeath();

	if (!canContinueToSpectate) {
		if (cfg.getEnableBungeeSupport()) {
			Bukkit.getScheduler().runTaskAsynchronously(UhcCore.getPlugin(), new TimeBeforeSendBungeeThread(uhcPlayer, cfg.getTimeBeforeSendBungeeAfterDeath()));
		} else {
			player.kickPlayer(Lang.DISPLAY_MESSAGE_PREFIX + " " + Lang.KICK_DEAD);
		}
	}

	pm.checkIfRemainingPlayers();
}
 
源代码8 项目: SaneEconomy   文件: MockServer.java
@Override
public boolean dispatchCommand(CommandSender commandSender, String s) throws CommandException {
    return false;
}
 
源代码9 项目: RedProtect   文件: WorldMySQLRegionManager.java
public WorldMySQLRegionManager(String world) throws SQLException {
    super();
    this.regions = new HashMap<>();
    this.world = world;
    this.tableName = RedProtect.get().config.configRoot().mysql.table_prefix + world;

    this.dbcon = null;
    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e1) {
        try {
            Class.forName("org.mariadb.jdbc.Driver");
        } catch (ClassNotFoundException e2) {
            RedProtect.get().logger.severe("Couldn't find the driver for MySQL! com.mysql.jdbc.Driver or org.mariadb.jdbc.Driver.");
            return;
        }
    }
    PreparedStatement st = null;
    try {
        if (!this.checkTableExists()) {
            Connection con = DriverManager.getConnection(this.url + this.dbname + this.reconnect + (RedProtect.get().config.configRoot().mysql.ssl ? "&useSSL=true&requireSSL=true" : "")
                    , RedProtect.get().config.configRoot().mysql.user_name, RedProtect.get().config.configRoot().mysql.user_pass);

            st = con.prepareStatement("CREATE TABLE `" + tableName + "` " +
                    "(name varchar(20) PRIMARY KEY NOT NULL, leaders varchar(200) , admins varchar(200), members varchar(200), maxMbrX int, minMbrX int, maxMbrZ int, minMbrZ int, centerX int, centerZ int, minY int, maxY int, date varchar(10), wel varchar(200), prior int, world varchar(100), value Long not null, tppoint varchar(20), flags longtext, candelete tinyint(1), canpurge tinyint(1)) CHARACTER SET utf8 COLLATE utf8_general_ci");
            st.executeUpdate();
            st.close();
            st = null;
            RedProtect.get().logger.info("Created table: " + tableName + "!");

        }
        ConnectDB();
        addNewColumns();
    } catch (CommandException e3) {
        RedProtect.get().logger.severe("Couldn't connect to mysql! Make sure you have mysql turned on and installed properly, and the service is started. Reload the Redprotect plugin after you fix or change your DB configurations");
    } catch (SQLException e) {
        CoreUtil.printJarVersion();
        e.printStackTrace();
    } finally {
        if (st != null) {
            st.close();
        }
    }
}
 
源代码10 项目: Kettle   文件: Bukkit.java
/**
 * Dispatches a command on this server, and executes it if found.
 *
 * @param sender      the apparent sender of the command
 * @param commandLine the command + arguments. Example: <code>test abc
 *                    123</code>
 * @return returns false if no target is found
 * @throws CommandException thrown when the executor for the given command
 *                          fails with an unhandled exception
 */
public static boolean dispatchCommand(CommandSender sender, String commandLine) throws CommandException {
    return server.dispatchCommand(sender, commandLine);
}
 
 类所在包
 类方法
 同包方法