Java Code Examples for org.spongepowered.api.command.CommandResult#success()

The following examples show how to use org.spongepowered.api.command.CommandResult#success() . 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: ExpExecutor.java    From EssentialCmds with MIT License 6 votes vote down vote up
public CommandResult execute(CommandSource src, CommandContext ctx) throws CommandException
{
	if(src instanceof Player)
	{
		Player player = (Player) src;
		ExperienceHolderData expHolderData = player.getOrCreate(ExperienceHolderData.class).get();
		player.sendMessage(Text.of(TextColors.GOLD, "Your current experience: ", TextColors.GRAY, expHolderData.totalExperience().get()));
		player.sendMessage(Text.of(TextColors.GOLD, "Experience to next level: ", TextColors.GRAY, expHolderData.getExperienceBetweenLevels().get() - expHolderData.experienceSinceLevel().get()));
	}
	else
	{
		src.sendMessage(Text.of(TextColors.DARK_RED, "Error! ", TextColors.RED, "You must be an in-game player to use this command!"));
	}
	
	return CommandResult.success();
}
 
Example 2
Source File: NationadminSpyExecutor.java    From Nations with MIT License 6 votes vote down vote up
public CommandResult execute(CommandSource src, CommandContext ctx) throws CommandException
{
	if (src instanceof Player)
	{
		NationMessageChannel channel = DataHandler.getSpyChannel();
		if (channel.getMembers().contains(src))
		{
			channel.removeMember(src);
			src.sendMessage(Text.of(TextColors.YELLOW, LanguageHandler.INFO_NATIONSPY_OFF));
		}
		else
		{
			channel.addMember(src);
			src.sendMessage(Text.of(TextColors.YELLOW, LanguageHandler.INFO_NATIONSPY_ON));
		}
	}
	else
	{
		src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_NOPLAYER));
	}
	return CommandResult.success();
}
 
Example 3
Source File: ForceLoginCommand.java    From FlexibleLogin with MIT License 6 votes vote down vote up
@Override
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
    Player player = args.<Player>getOne("account").get();
    if (plugin.getDatabase().isLoggedIn(player)) {
        throw new CommandException(settings.getText().getForceLoginAlreadyLoggedIn());
    }

    Task.builder()
            //we are executing a SQL Query which is blocking
            .async()
            .execute(new ForceLoginTask(plugin, attemptManager, protectionManager, player, src))
            .name("Force Login Query")
            .submit(plugin);

    return CommandResult.success();
}
 
Example 4
Source File: SetCommand.java    From ChangeSkin with MIT License 5 votes vote down vote up
@Override
public CommandResult execute(CommandSource src, CommandContext args) {
    if (!(src instanceof Player)) {
        plugin.sendMessage(src, "no-console");
        return CommandResult.empty();
    }

    UUID uniqueId = ((Player) src).getUniqueId();
    if (core.getCooldownService().isTracked(uniqueId)) {
        plugin.sendMessage(src, "cooldown");
        return CommandResult.empty();
    }

    Player receiver = (Player) src;
    String targetSkin = args.<String>getOne("skin").get();
    boolean keepSkin = args.hasAny("keep");

    if ("reset".equals(targetSkin)) {
        targetSkin = receiver.getUniqueId().toString();
    }

    if (targetSkin.length() > 16) {
        UUID targetUUID = UUID.fromString(targetSkin);

        if (core.getConfig().getBoolean("skinPermission") && !plugin.hasSkinPermission(src, targetUUID, true)) {
            return CommandResult.empty();
        }

        plugin.sendMessage(src, "skin-change-queue");
        Runnable skinDownloader = new SkinDownloader(plugin, src, receiver, targetUUID, keepSkin);
        Task.builder().async().execute(skinDownloader).submit(plugin);
        return CommandResult.success();
    }

    Runnable nameResolver = new NameResolver(plugin, src, targetSkin, receiver, keepSkin);
    Task.builder().async().execute(nameResolver).submit(plugin);
    return CommandResult.success();
}
 
Example 5
Source File: NotAccessibleByFactionCommand.java    From EagleFactions with MIT License 5 votes vote down vote up
private CommandResult showNotAccessibleByFaction(final Player sourcePlayer, final Faction faction)
{
    final List<Text> resultList = new ArrayList<>();
    final Set<Claim> claims = faction.getClaims();

    for (final Claim claim : claims)
    {
        if (claim.isAccessibleByFaction())
            continue;

        final Text.Builder claimHoverInfo = Text.builder();
        claimHoverInfo.append(Text.of(TextColors.GOLD, "Accessible by faction: ", TextColors.RESET, claim.isAccessibleByFaction(), "\n"));
        final List<String> ownersNames = claim.getOwners().stream()
                .map(owner -> super.getPlugin().getPlayerManager().getFactionPlayer(owner))
                .filter(Optional::isPresent)
                .map(factionPlayer -> factionPlayer.get().getName())
                .collect(Collectors.toList());
        claimHoverInfo.append(Text.of(TextColors.GOLD, "Owners: ", TextColors.RESET, String.join(", ", ownersNames)));

        final Text.Builder textBuilder = Text.builder();
        final Optional<World> world = Sponge.getServer().getWorld(claim.getWorldUUID());
        String worldName = "";
        if (world.isPresent())
            worldName = world.get().getName();
        textBuilder.append(Text.of("- ", TextColors.YELLOW, "World: " , TextColors.GREEN, worldName, TextColors.RESET, " | ", TextColors.YELLOW, "Chunk: ", TextColors.GREEN, claim.getChunkPosition()))
                .onHover(TextActions.showText(claimHoverInfo.build()));
        resultList.add(textBuilder.build());
        spawnParticlesInClaim(claim);
    }

    final PaginationList paginationList = PaginationList.builder().padding(Text.of("=")).title(Text.of(TextColors.YELLOW, "Claims List")).contents(resultList).linesPerPage(10).build();
    paginationList.sendTo(sourcePlayer);
    return CommandResult.success();
}
 
Example 6
Source File: CmdUserChangePassword.java    From Web-API with MIT License 5 votes vote down vote up
@Override
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
    Optional<String> optUsername = args.getOne("username");
    if (!optUsername.isPresent()) {
        return CommandResult.empty();
    }
    String username = optUsername.get();

    Optional<String> optPassword = args.getOne("password");
    if (!optPassword.isPresent()) {
        return CommandResult.empty();
    }
    String password = optPassword.get();

    UserService srv = WebAPI.getUserService();

    Optional<UserPermissionStruct> optUser = srv.getUser(username);
    if (!optUser.isPresent()) {
        src.sendMessage(Text.builder("Could not find user '" + username + "'").color(TextColors.RED).build());
        return CommandResult.empty();
    }

    UserPermissionStruct user = optUser.get();

    user.setPassword(srv.hashPassword(password));
    src.sendMessage(Text.builder("Changed password for ")
            .append(Text.builder(username).color(TextColors.GOLD).build())
            .build());

    srv.save();
    return CommandResult.success();
}
 
Example 7
Source File: NationChatExecutor.java    From Nations with MIT License 5 votes vote down vote up
public CommandResult execute(CommandSource src, CommandContext ctx) throws CommandException
{
	if (src instanceof Player)
	{
		Player player = (Player) src;
		Nation nation = DataHandler.getNationOfPlayer(player.getUniqueId());
		if (nation == null)
		{
			player.setMessageChannel(MessageChannel.TO_ALL);
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_NONATION));
			return CommandResult.success();
		}
		NationMessageChannel channel = nation.getMessageChannel();

		if (!ctx.<String>getOne("msg").isPresent())
		{
			if (player.getMessageChannel().equals(channel)) {
				player.setMessageChannel(MessageChannel.TO_ALL);
				src.sendMessage(Text.of(TextColors.YELLOW, LanguageHandler.INFO_NATIONCHAT_OFF));
			} else {
				player.setMessageChannel(channel);
				src.sendMessage(Text.of(TextColors.YELLOW, LanguageHandler.INFO_NATIONCHATON_ON));
			}
		}
		else
		{
			Text header = TextSerializers.FORMATTING_CODE.deserialize(ConfigHandler.getNode("others", "nationChatFormat").getString().replaceAll("\\{NATION\\}", nation.getTag()).replaceAll("\\{TITLE\\}", DataHandler.getCitizenTitle(player.getUniqueId())));
			
			Text msg = Text.of(header, TextColors.RESET, player.getName(), TextColors.WHITE, ": ", TextColors.YELLOW, ctx.<String>getOne("msg").get());
			channel.send(player, msg);
			DataHandler.getSpyChannel().send(Text.of(TextSerializers.FORMATTING_CODE.deserialize(ConfigHandler.getNode("others", "nationSpyChatTag").getString()), TextColors.RESET, msg));
		}

	}
	else
	{
		src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_NOPLAYER));
	}
	return CommandResult.success();
}
 
Example 8
Source File: LoginCommand.java    From FlexibleLogin with MIT License 5 votes vote down vote up
@Override
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
    if (!(src instanceof Player)) {
        throw new CommandException(settings.getText().getPlayersOnly());
    }

    Player player = (Player) src;
    if (plugin.getDatabase().isLoggedIn(player)) {
        throw new CommandException(settings.getText().getAlreadyLoggedIn());
    }

    UUID uniqueId = player.getUniqueId();
    if (!attemptManager.isAllowed(uniqueId)) {
        String lockCommand = settings.getGeneral().getLockCommand();
        if (!lockCommand.isEmpty()) {
            commandManager.process(Sponge.getServer().getConsole(), lockCommand);
        }

        Task.builder()
                .delay(settings.getGeneral().getWaitTime().getSeconds(), TimeUnit.SECONDS)
                .execute(() -> attemptManager.clearAttempts(uniqueId))
                .submit(plugin);

        throw new CommandException(settings.getText().getMaxAttempts());
    }

    attemptManager.increaseAttempt(uniqueId);

    //the arg isn't optional. We can be sure there is value
    String password = args.<String>getOne("password").get();

    Task.builder()
            //we are executing a SQL Query which is blocking
            .async()
            .execute(new LoginTask(plugin, attemptManager, protectionManager, (Player) src, password))
            .name("Login Query")
            .submit(plugin);

    return CommandResult.success();
}
 
Example 9
Source File: ChatCommand.java    From EagleFactions with MIT License 5 votes vote down vote up
@Override
public CommandResult execute(CommandSource source, CommandContext context) throws CommandException
{
    final Optional<ChatEnum> optionalChatType = context.<ChatEnum>getOne("chat");

    if(!(source instanceof Player))
        throw new CommandException(Text.of(PluginInfo.ERROR_PREFIX, TextColors.RED, Messages.ONLY_IN_GAME_PLAYERS_CAN_USE_THIS_COMMAND));

    Player player = (Player) source;

    if(!super.getPlugin().getFactionLogic().getFactionByPlayerUUID(player.getUniqueId()).isPresent())
        throw new CommandException(Text.of(PluginInfo.ERROR_PREFIX, TextColors.RED, Messages.YOU_MUST_BE_IN_FACTION_IN_ORDER_TO_USE_THIS_COMMAND));

    if(optionalChatType.isPresent())
    {
        setChatChannel(player, optionalChatType.get());
    }
    else
    {
        //If player is in alliance chat or faction chat.
        if(EagleFactionsPlugin.CHAT_LIST.containsKey(player.getUniqueId()))
        {
            if(EagleFactionsPlugin.CHAT_LIST.get(player.getUniqueId()).equals(ChatEnum.ALLIANCE))
            {
                setChatChannel(player, ChatEnum.FACTION);
            }
            else
            {
                setChatChannel(player, ChatEnum.GLOBAL);
            }
        }
        else
        {
            setChatChannel(player, ChatEnum.ALLIANCE);
        }
    }
    return CommandResult.success();
}
 
Example 10
Source File: ForceRegisterCommand.java    From FlexibleLogin with MIT License 5 votes vote down vote up
@Override
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
    User user = args.<User>getOne("user").get();
    String password = args.<String>getOne("password").get();

    uuidRegister(user.getUniqueId(), src, password);
    return CommandResult.success();
}
 
Example 11
Source File: BlockInfoExecutor.java    From EssentialCmds with MIT License 5 votes vote down vote up
public CommandResult execute(CommandSource src, CommandContext ctx) throws CommandException
{
	if (src instanceof Player)
	{
		Player player = (Player) src;

		BlockRay<World> playerBlockRay = BlockRay.from(player).blockLimit(5).build();
		BlockRayHit<World> finalHitRay = null;

		while (playerBlockRay.hasNext())
		{
			BlockRayHit<World> currentHitRay = playerBlockRay.next();

			if (!player.getWorld().getBlockType(currentHitRay.getBlockPosition()).equals(BlockTypes.AIR))
			{
				finalHitRay = currentHitRay;
				break;
			}
		}

		if (finalHitRay != null)
		{
			player.sendMessage(Text.of(TextColors.GOLD, "The name of the block you're looking at is: ", TextColors.GRAY, finalHitRay.getLocation().getBlock().getType().getTranslation().get()));
			player.sendMessage(Text.of(TextColors.GOLD, "The ID of the block you're looking at is: ", TextColors.GRAY, finalHitRay.getLocation().getBlock().getName()));
			Optional<Object> metaDataQuery = finalHitRay.getLocation().getBlock().toContainer().get(DataQuery.of("UnsafeMeta"));
			player.sendMessage(Text.of(TextColors.GOLD, "The meta of the block you're looking at is: ", TextColors.GRAY, metaDataQuery.isPresent() ? metaDataQuery.get().toString() : 0));
		}
		else
		{
			player.sendMessage(Text.of(TextColors.DARK_RED, "Error! ", TextColors.RED, "You're not looking at any block within range."));
		}
	}
	else
	{
		src.sendMessage(Text.of(TextColors.DARK_RED, "Error! ", TextColors.RED, "You must be an in-game player to use this command."));
	}

	return CommandResult.success();
}
 
Example 12
Source File: CmdUserAdd.java    From Web-API with MIT License 5 votes vote down vote up
@Override
public CommandResult execute(CommandSource src, CommandContext args) {
    Optional<String> optUsername = args.getOne("username");
    if (!optUsername.isPresent()) {
        return CommandResult.empty();
    }
    String username = optUsername.get();

    Optional<String> optPassword = args.getOne("password");
    String password = optPassword.orElse(Util.generateUniqueId().substring(0, 8));

    Optional<UserPermissionStruct> optUser = WebAPI.getUserService().addUser(
            username, password, SecurityService.permitAllNode());

    if (!optUser.isPresent()) {
        src.sendMessage(Text.builder("A user with this name already exists").color(TextColors.RED).build());
        return CommandResult.empty();
    }

    if (!optPassword.isPresent()) {
        src.sendMessage(Text.builder("Created user ")
                .append(Text.builder(username).color(TextColors.GOLD).build())
                .append(Text.of(" with password "))
                .append(Text.builder(password).color(TextColors.GOLD).build())
                .build());
    } else {
        src.sendMessage(Text.builder("Created user ")
                .append(Text.builder(username).color(TextColors.GOLD).build())
                .build());
    }

    return CommandResult.success();
}
 
Example 13
Source File: CommandClaimGreeting.java    From GriefPrevention with MIT License 5 votes vote down vote up
@Override
public CommandResult execute(CommandSource src, CommandContext ctx) {
    Player player;
    try {
        player = GriefPreventionPlugin.checkPlayer(src);
    } catch (CommandException e) {
        src.sendMessage(e.getText());
        return CommandResult.success();
    }

    final GPPlayerData playerData = GriefPreventionPlugin.instance.dataStore.getOrCreatePlayerData(player.getWorld(), player.getUniqueId());
    final GPClaim claim = GriefPreventionPlugin.instance.dataStore.getClaimAtPlayer(playerData, player.getLocation());
    final Text result = claim.allowEdit(player);
    if (result != null) {
        GriefPreventionPlugin.sendMessage(src, result);
        return CommandResult.success();
    }

    final Text greeting = TextSerializers.FORMATTING_CODE.deserialize(ctx.<String>getOne("message").get());
    if (greeting.isEmpty()) {
        claim.getInternalClaimData().setGreeting(null);
    } else {
        claim.getInternalClaimData().setGreeting(greeting);
    }
    claim.getInternalClaimData().setRequiresSave(true);
    final Text message = GriefPreventionPlugin.instance.messageData.claimGreeting
            .apply(ImmutableMap.of(
            "greeting", greeting)).build();
    GriefPreventionPlugin.sendMessage(src, message);

    return CommandResult.success();
}
 
Example 14
Source File: JoinCommand.java    From EagleFactions with MIT License 5 votes vote down vote up
private CommandResult joinFactionAndNotify(final Player player, final Faction faction)
{
    final boolean isCancelled = EventRunner.runFactionJoinEvent(player, faction);
    if (isCancelled)
        return CommandResult.success();

    super.getPlugin().getFactionLogic().joinFaction(player.getUniqueId(), faction.getName());
    EagleFactionsPlugin.INVITE_LIST.remove(new Invite(faction.getName(), player.getUniqueId()));
    player.sendMessage(Text.of(PluginInfo.PLUGIN_PREFIX, MessageLoader.parseMessage(Messages.SUCCESSFULLY_JOINED_FACTION, TextColors.GREEN, Collections.singletonMap(Placeholders.FACTION_NAME, Text.of(TextColors.GOLD, faction.getName())))));
    return CommandResult.success();
}
 
Example 15
Source File: ExpExecutor.java    From EssentialCmds with MIT License 5 votes vote down vote up
@Override
public CommandResult execute(CommandSource src, CommandContext ctx) throws CommandException {
	int expLevel = ctx.<Integer> getOne("exp").get();
	Player player = ctx.<Player> getOne("target").get();
	player.offer(Keys.TOTAL_EXPERIENCE, player.get(Keys.TOTAL_EXPERIENCE).get() - expLevel);
	src.sendMessage(Text.of(TextColors.GREEN, "Success! ", TextColors.YELLOW, "Took " + expLevel + " experience from " + player.getName() + "."));
	return CommandResult.success();
}
 
Example 16
Source File: AttackCommand.java    From EagleFactions with MIT License 4 votes vote down vote up
private CommandResult attackChunk(Player player) throws CommandException
{
    final Optional<Faction> optionalPlayerFaction = getPlugin().getFactionLogic().getFactionByPlayerUUID(player.getUniqueId());
    if(!optionalPlayerFaction.isPresent())
        throw new CommandException(Text.of(PluginInfo.ERROR_PREFIX, TextColors.RED, Messages.YOU_MUST_BE_IN_FACTION_IN_ORDER_TO_USE_THIS_COMMAND));

    final Faction playerFaction = optionalPlayerFaction.get();
    final Optional<Faction> optionalChunkFaction = getPlugin().getFactionLogic().getFactionByChunk(player.getWorld().getUniqueId(), player.getLocation().getChunkPosition());
    if(!optionalChunkFaction.isPresent())
        throw new CommandException(Text.of(PluginInfo.ERROR_PREFIX, TextColors.RED, Messages.THIS_PLACE_DOES_NOT_BELONG_TO_ANYONE));

    if(optionalChunkFaction.get().isSafeZone() || optionalChunkFaction.get().isWarZone())
        throw new CommandException(Text.of(PluginInfo.ERROR_PREFIX, TextColors.RED, Messages.YOU_CANT_ATTACK_THIS_FACTION));

    if(!super.getPlugin().getPermsManager().canAttack(player.getUniqueId(), playerFaction))
        throw new CommandException(Text.of(PluginInfo.ERROR_PREFIX, TextColors.RED, Messages.PLAYERS_WITH_YOUR_RANK_CANT_ATTACK_LANDS));

    final Faction attackedFaction = optionalChunkFaction.get();

    if(playerFaction.getName().equals(attackedFaction.getName()))
        throw new CommandException(Text.of(PluginInfo.ERROR_PREFIX, TextColors.RED, Messages.YOU_CANT_ATTACK_YOURSELF));

    if(playerFaction.getAlliances().contains(attackedFaction.getName()) || playerFaction.getTruces().contains(attackedFaction.getName()))
        throw new CommandException(Text.of(PluginInfo.ERROR_PREFIX, TextColors.RED, Messages.YOU_CANT_ATTACK_THIS_FACTION + " " + Messages.YOU_ARE_IN_THE_SAME_ALLIANCE));

    final float neededPowerPercentageToAttack = this.powerConfig.getNeededPowerPercentageToAttack();
    final float attackedFactionMaxPower = super.getPlugin().getPowerManager().getFactionMaxPower(attackedFaction);
    final float attackedFactionPower = super.getPlugin().getPowerManager().getFactionPower(attackedFaction);
    final float playerFactionPower = super.getPlugin().getPowerManager().getFactionPower(playerFaction);

    if(attackedFactionMaxPower * neededPowerPercentageToAttack < attackedFactionPower || playerFactionPower < attackedFactionPower)
        throw new CommandException(Text.of(PluginInfo.ERROR_PREFIX, TextColors.RED, Messages.YOU_CANT_ATTACK_THIS_FACTION + " " + Messages.THEIR_POWER_IS_TO_HIGH));

    int attackTime = this.factionsConfig.getAttackTime();
    Vector3i attackedClaim = player.getLocation().getChunkPosition();

    super.getPlugin().getAttackLogic().informAboutAttack(attackedFaction);
    player.sendMessage(Text.of(PluginInfo.PLUGIN_PREFIX, TextColors.GREEN, Messages.ATTACK_ON_THE_CHUNK_HAS_BEEN_STARTED + " ", MessageLoader.parseMessage(Messages.STAY_IN_THE_CHUNK_FOR_NUMBER_SECONDS_TO_DESTROY_IT, TextColors.GREEN, Collections.singletonMap(Placeholders.NUMBER, Text.of(TextColors.GOLD, attackTime)))));

    super.getPlugin().getAttackLogic().blockClaiming(attackedFaction.getName());
    super.getPlugin().getAttackLogic().attack(player, attackedClaim);

    return CommandResult.success();
}
 
Example 17
Source File: CommandGpReload.java    From GriefPrevention with MIT License 4 votes vote down vote up
@Override
public CommandResult execute(CommandSource src, CommandContext ctx) {
    GriefPreventionPlugin.instance.loadConfig();
    GriefPreventionPlugin.sendMessage(src, GriefPreventionPlugin.instance.messageData.pluginReload.toText());
    return CommandResult.success();
}
 
Example 18
Source File: CommandClaimFlagPlayer.java    From GriefPrevention with MIT License 4 votes vote down vote up
@Override
public CommandResult execute(CommandSource src, CommandContext ctx) {
    Player player;
    try {
        player = GriefPreventionPlugin.checkPlayer(src);
    } catch (CommandException e) {
        src.sendMessage(e.getText());
        return CommandResult.success();
    }

    User user = ctx.<User>getOne("player").get();
    String name = user.getName();
    String flag = ctx.<String>getOne("flag").orElse(null);
    String source = ctx.<String>getOne("source").orElse(null);
    String target = null;
    // Workaround command API issue not handling onlyOne arguments with sequences properly
    List<String> targetValues = new ArrayList<>(ctx.<String>getAll("target"));
    if (targetValues.size() > 0) {
        if (targetValues.size() > 1) {
            target = targetValues.get(1);
        } else {
            target = targetValues.get(0);
        }
    }

    if (source != null && source.equalsIgnoreCase("any")) {
        source = null;
    }

    this.subject = user;
    this.friendlySubjectName = user.getName();
    Tristate value = ctx.<Tristate>getOne("value").orElse(null);
    String context = ctx.<String>getOne("context").orElse(null);
    GPPlayerData playerData = GriefPreventionPlugin.instance.dataStore.getOrCreatePlayerData(player.getWorld(), player.getUniqueId());
    GPClaim claim = GriefPreventionPlugin.instance.dataStore.getClaimAtPlayer(playerData, player.getLocation());

    String reason = ctx.<String>getOne("reason").orElse(null);
    Text reasonText = null;
    if (reason != null) {
        reasonText = TextSerializers.FORMATTING_CODE.deserialize(reason);
    }
    if (flag == null && value == null) {
        showFlagPermissions(src, claim, FlagType.ALL, source);
        return CommandResult.success();
    }

    if (!ClaimFlag.contains(flag)) {
        src.sendMessage(Text.of(TextColors.RED, "Flag not found."));
        return CommandResult.success();
    }
    Context claimContext = claim.getContext();
    if (context != null) {
        claimContext = CommandHelper.validateCustomContext(src, claim, context);
        if (claimContext == null) {
            final Text message = GriefPreventionPlugin.instance.messageData.flagInvalidContext
                    .apply(ImmutableMap.of(
                    "context", context,
                    "flag", flag)).build();
            GriefPreventionPlugin.sendMessage(src, message);
            return CommandResult.success();
        }
    }

    if (user.hasPermission(GPPermissions.COMMAND_ADMIN_CLAIMS) && !src.hasPermission(GPPermissions.SET_ADMIN_FLAGS)) {
        GriefPreventionPlugin.sendMessage(src, GriefPreventionPlugin.instance.messageData.permissionSetAdminFlags.toText());
        return CommandResult.success();
    }

    try (final CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) {
        Sponge.getCauseStackManager().pushCause(src);
        claim.setPermission(user, name, ClaimFlag.getEnum(flag), source, target, value, claimContext, reasonText);
    }
    return CommandResult.success();
}
 
Example 19
Source File: NationJoinExecutor.java    From Nations with MIT License 4 votes vote down vote up
public CommandResult execute(CommandSource src, CommandContext ctx) throws CommandException
{
	if (src instanceof Player)
	{
		Player guestPlayer = (Player) src;
		if (!ctx.<String>getOne("nation").isPresent())
		{
			src.sendMessage(Text.of(TextColors.YELLOW, "/n join <nation>"));
			return CommandResult.success();
		}
		if (DataHandler.getNationOfPlayer(guestPlayer.getUniqueId()) != null)
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_NEEDLEAVE));
			return CommandResult.success();
		}
		String nationName = ctx.<String>getOne("nation").get();
		Nation nation = DataHandler.getNation(nationName);
		if (nation == null)
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_BADNATIONNAME));
			return CommandResult.success();
		}
		
		Request req = DataHandler.getJoinRequest(nation.getUUID(), guestPlayer.getUniqueId());
		if (req != null)
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_ALREADYASKED));
			return CommandResult.success();
		}
		req = DataHandler.getInviteRequest(nation.getUUID(), guestPlayer.getUniqueId());
		if (nation.getFlag("open") || req != null)
		{
			if (req != null)
			{
				DataHandler.removeInviteRequest(req);
			}
			for (UUID uuid : nation.getCitizens())
			{
				Optional<Player> optPlayer = Sponge.getServer().getPlayer(uuid);
				if (optPlayer.isPresent())
					optPlayer.get().sendMessage(Text.of(TextColors.GREEN, LanguageHandler.INFO_JOINNATIONANNOUNCE.replaceAll("\\{PLAYER\\}", guestPlayer.getName())));
			}
			nation.addCitizen(guestPlayer.getUniqueId());
			guestPlayer.sendMessage(Text.of(TextColors.GREEN, LanguageHandler.INFO_JOINNATION.replaceAll("\\{NATION\\}", nation.getName())));
			DataHandler.saveNation(nation.getUUID());
			return CommandResult.success();
		}
		ArrayList<UUID> nationStaff = nation.getStaff();
		List<Player> nationStaffPlayers = nationStaff
				.stream()
				.filter(uuid -> Sponge.getServer().getPlayer(uuid).isPresent())
				.map(uuid -> Sponge.getServer().getPlayer(uuid).get())
				.collect(Collectors.toList());
		
		if (nationStaffPlayers.isEmpty())
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_NOSTAFFONLINE));
			return CommandResult.success();
		}
		DataHandler.addJoinRequest(new Request(nation.getUUID(), guestPlayer.getUniqueId()));
		for (Player p : nationStaffPlayers)
		{
			String str = LanguageHandler.INFO_CLICK_JOINREQUEST.replaceAll("\\{PLAYER\\}", guestPlayer.getName());
			p.sendMessage(Text.builder()
					.append(Text.of(TextColors.AQUA, str.split("\\{CLICKHERE\\}")[0]))
					.append(Text.builder(LanguageHandler.CLICKME)
							.onClick(TextActions.runCommand("/nation invite " + guestPlayer.getName()))
							.color(TextColors.DARK_AQUA)
							.build())
					.append(Text.of(TextColors.AQUA, str.split("\\{CLICKHERE\\}")[1])).build());
		}
		src.sendMessage(Text.of(TextColors.GREEN, LanguageHandler.INFO_INVITSEND.replaceAll("\\{RECEIVER\\}", nationName)));
	}
	else
	{
		src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_NOPLAYER));
	}
	return CommandResult.success();
}
 
Example 20
Source File: NationadminExtraplayerExecutor.java    From Nations with MIT License 4 votes vote down vote up
public CommandResult execute(CommandSource src, CommandContext ctx) throws CommandException
{
	if (!ctx.<String>getOne("player").isPresent() || !ctx.<String>getOne("give|take|set").isPresent() || !ctx.<String>getOne("amount").isPresent())
	{
		src.sendMessage(Text.of(TextColors.YELLOW, "/na extraplayer <give|take|set> <player> <amount>"));
		return CommandResult.success();
	}
	String playerName = ctx.<String>getOne("player").get();
	Integer amount = Integer.valueOf(ctx.<Integer>getOne("amount").get());
	String operation = ctx.<String>getOne("give|take|set").get();
	
	UUID playerUUID = DataHandler.getPlayerUUID(playerName);
	if (playerUUID == null)
	{
		src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_BADPLAYERNAME));
		return CommandResult.success();
	}
	
	Nation nation = DataHandler.getNationOfPlayer(playerUUID);
	if (nation == null)
	{
		src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_PLAYERNOTINNATION));
		return CommandResult.success();
	}
	if (operation.equalsIgnoreCase("give"))
	{
		nation.addExtras(amount);
	}
	else if (operation.equalsIgnoreCase("take"))
	{
		nation.removeExtras(amount);
	}
	else if (operation.equalsIgnoreCase("set"))
	{
		nation.setExtras(amount);
	}
	else
	{
		src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_BADARG_GTS));
		return CommandResult.success();
	}
	DataHandler.saveNation(nation.getUUID());
	src.sendMessage(Text.of(TextColors.GREEN, LanguageHandler.SUCCESS_GENERAL));
	return CommandResult.success();
}