Java Code Examples for org.spongepowered.api.command.args.CommandContext#getAll()

The following examples show how to use org.spongepowered.api.command.args.CommandContext#getAll() . 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: PasswordRegisterCommand.java    From FlexibleLogin with MIT License 6 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());
    }

    Collection<String> passwords = args.getAll("password");
    List<String> indexPasswords = Lists.newArrayList(passwords);
    String password = indexPasswords.get(0);
    if (!password.equals(indexPasswords.get(1))) {
        //Check if the first two passwords are equal to prevent typos
        throw new CommandException(settings.getText().getUnequalPasswords());
    }

    if (password.length() < settings.getGeneral().getMinPasswordLength()) {
        throw new CommandException(settings.getText().getTooShortPassword());
    }

    Task.builder()
            //we are executing a SQL Query which is blocking
            .async()
            .execute(new RegisterTask(plugin, protectionManager, (Player) src, password))
            .name("Register Query")
            .submit(plugin);
    return CommandResult.success();
}
 
Example 2
Source File: TeleporthereCommand.java    From UltimateCore with MIT License 6 votes vote down vote up
@Override
public CommandResult execute(CommandSource sender, CommandContext args) throws CommandException {
    checkIfPlayer(sender);
    checkPermission(sender, getPermission());
    Player p = (Player) sender;
    List<Entity> t = new ArrayList<>(args.getAll("entities"));

    Teleportation request = UltimateCore.get().getTeleportService().createTeleportation(sender, t, p::getTransform, teleportRequest -> {
        //Complete
        Messages.send(p, "teleport.command.teleporthere.success.self", "%player%", VariableUtil.getNamesEntity(t));
        for (Entity en : t) {
            if (en instanceof MessageReceiver) {
                Messages.send(((CommandSource) en), "teleport.command.teleporthere.success.others", "%player%", VariableUtil.getNameEntity(p));
            }
        }
    }, (teleportRequest, reason) -> {
    }, true, false);
    request.start();
    return CommandResult.successCount(t.size());
}
 
Example 3
Source File: ItemcanbreakCommand.java    From UltimateCore with MIT License 6 votes vote down vote up
@Override
public CommandResult execute(CommandSource sender, CommandContext args) throws CommandException {
    checkIfPlayer(sender);
    checkPermission(sender, ItemPermissions.UC_ITEM_ITEMCANBREAK_BASE);
    Player p = (Player) sender;

    if (p.getItemInHand(HandTypes.MAIN_HAND).getType().equals(ItemTypes.NONE)) {
        throw new ErrorMessageException(Messages.getFormatted(p, "item.noiteminhand"));
    }
    ItemStack stack = p.getItemInHand(HandTypes.MAIN_HAND);
    Set<BlockType> types = new HashSet<>(args.<BlockType>getAll("blocktypes"));

    stack.offer(Keys.BREAKABLE_BLOCK_TYPES, types);
    p.setItemInHand(HandTypes.MAIN_HAND, stack);
    Text items = Text.joinWith(Text.of(", "), types.stream().map(type -> Text.of(type.getName())).collect(Collectors.toList()));
    Messages.send(sender, "item.command.itemcanbreak.success", "%arg%", items);
    return CommandResult.success();
}
 
Example 4
Source File: ItemcanplaceonCommand.java    From UltimateCore with MIT License 6 votes vote down vote up
@Override
public CommandResult execute(CommandSource sender, CommandContext args) throws CommandException {
    checkIfPlayer(sender);
    checkPermission(sender, ItemPermissions.UC_ITEM_ITEMCANPLACEON_BASE);
    Player p = (Player) sender;

    if (p.getItemInHand(HandTypes.MAIN_HAND).getType().equals(ItemTypes.NONE)) {
        throw new ErrorMessageException(Messages.getFormatted(p, "item.noiteminhand"));
    }
    ItemStack stack = p.getItemInHand(HandTypes.MAIN_HAND);
    Set<BlockType> types = new HashSet<>(args.<BlockType>getAll("blocktypes"));

    stack.offer(Keys.PLACEABLE_BLOCKS, types);
    p.setItemInHand(HandTypes.MAIN_HAND, stack);
    Text items = Text.joinWith(Text.of(", "), types.stream().map(type -> Text.of(type.getName())).collect(Collectors.toList()));
    Messages.send(sender, "item.command.itemcanplaceon.success", "%arg%", items);
    return CommandResult.success();
}
 
Example 5
Source File: VirtualChestCommandAliases.java    From VirtualChest with GNU Lesser General Public License v3.0 5 votes vote down vote up
private CommandResult processAliasCommand(String name, CommandSource src, CommandContext args) throws CommandException
{
    Collection<Player> players = args.getAll("player");
    for (Player player : players)
    {
        commandManager.process(src, "virtualchest open " + name + " " + player.getName());
    }
    return CommandResult.success();
}
 
Example 6
Source File: CommandClaimBook.java    From GriefPrevention with MIT License 5 votes vote down vote up
@Override
public CommandResult execute(CommandSource src, CommandContext ctx) {
    for (Player otherPlayer : ctx.<Player>getAll("player")) {
        WelcomeTask task = new WelcomeTask(otherPlayer);
        task.run();
    }

    return CommandResult.success();
}
 
Example 7
Source File: TestVoteCmd.java    From NuVotifier with GNU General Public License v3.0 5 votes vote down vote up
@Override
public CommandResult execute(CommandSource sender, CommandContext args) throws CommandException {
    Vote v;
    try {
        Collection<String> a = args.getAll("args");
        v = ArgsToVote.parse(a.toArray(new String[0]));
    } catch (IllegalArgumentException e) {
        sender.sendMessage(Text.builder("Error while parsing arguments to create test vote: " + e.getMessage()).color(TextColors.DARK_RED).build());
        sender.sendMessage(Text.builder("Usage hint: /testvote [username] [serviceName=?] [username=?] [address=?] [localTimestamp=?] [timestamp=?]").color(TextColors.GRAY).build());
        return CommandResult.empty();
    }

    plugin.onVoteReceived(v, VotifierSession.ProtocolVersion.TEST, "localhost.test");
    return CommandResult.success();
}
 
Example 8
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 9
Source File: ChangePasswordCommand.java    From FlexibleLogin with MIT License 4 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());
    }

    if (!plugin.getDatabase().isLoggedIn((Player) src)) {
        throw new CommandException(settings.getText().getNotLoggedIn());
    }

    Account account = plugin.getDatabase().getAccount((Player) src).get();

    Collection<String> passwords = args.getAll("password");
    List<String> indexPasswords = Lists.newArrayList(passwords);
    String password = indexPasswords.get(0);
    if (!password.equals(indexPasswords.get(1))) {
        throw new CommandException(settings.getText().getUnequalPasswords());
    }

    try {
        //Check if the first two passwords are equal to prevent typos
        String hash = plugin.getHasher().hash(password);
        Task.builder()
                //we are executing a SQL Query which is blocking
                .async()
                .execute(() -> {
                    account.setPasswordHash(hash);
                    if (plugin.getDatabase().save(account)) {
                        src.sendMessage(settings.getText().getChangePassword());
                    } else {
                        src.sendMessage(settings.getText().getErrorExecutingCommand());
                    }
                })
                .name("Register Query")
                .submit(plugin);
    } catch (Exception ex) {
        logger.error("Error creating hash on change password", ex);
        throw new InvocationCommandException(settings.getText().getErrorExecutingCommand(), ex);
    }

    return CommandResult.success();
}
 
Example 10
Source File: CreateWorldCommand.java    From UltimateCore with MIT License 4 votes vote down vote up
@Override
public CommandResult execute(CommandSource sender, CommandContext args) throws CommandException {
    String name = (String) args.getOne("name").get();
    Optional<DimensionType> dimension = args.getOne("dimension");
    Optional<GeneratorType> generator = args.getOne("generator");
    Collection<WorldGeneratorModifier> wgm = args.getAll("wgm");
    Optional<Long> seed = args.getOne("seed");
    Optional<GameMode> gm = args.getOne("gamemode");
    Optional<Difficulty> diff = args.getOne("difficulty");

    boolean nostructures = args.hasAny("n");
    boolean load = args.<Boolean>getOne("l").orElse(true);
    boolean keepspawnloaded = args.<Boolean>getOne("k").orElse(true);
    boolean allowcommands = args.<Boolean>getOne("c").orElse(true);
    boolean bonuschest = args.<Boolean>getOne("b").orElse(true);

    Path path = Sponge.getGame().getSavesDirectory();
    if (Files.exists(path.resolve(name.toLowerCase())) || Files.exists(path.resolve(name)) || Sponge.getServer().getAllWorldProperties().stream().anyMatch(x -> x.getWorldName().equalsIgnoreCase(name))) {
        throw new ErrorMessageException(Messages.getFormatted(sender, "world.exists", "%name%", name));
    }

    Messages.send(sender, "world.command.world.create.starting", "%name%", name);

    WorldArchetype.Builder archetype = WorldArchetype.builder().enabled(true);
    dimension.ifPresent(archetype::dimension);
    generator.ifPresent(archetype::generator);
    archetype.generatorModifiers(wgm.toArray(new WorldGeneratorModifier[wgm.size()]));
    seed.ifPresent(archetype::seed);
    gm.ifPresent(archetype::gameMode);
    diff.ifPresent(archetype::difficulty);
    archetype.usesMapFeatures(!nostructures);
    archetype.loadsOnStartup(load);
    archetype.keepsSpawnLoaded(keepspawnloaded);
    archetype.commandsAllowed(allowcommands);
    archetype.generateBonusChest(bonuschest);

    WorldProperties props;
    try {
        props = Sponge.getServer().createWorldProperties(name.toLowerCase(), archetype.build(name.toLowerCase(), name));
    } catch (IOException e) {
        throw new ErrorMessageException(Messages.getFormatted(sender, "world.command.world.create.fileerror", "%error%", e.getMessage()));
    }
    Sponge.getServer().saveWorldProperties(props);
    World world = Sponge.getServer().loadWorld(props).orElseThrow(() -> new ErrorMessageException(Messages.getFormatted(sender, "world.command.world.create.loaderror")));
    Messages.send(sender, "world.command.world.create.success", "%name%", world.getName());
    return CommandResult.success();
}