Search in sources :

Example 56 with CommandSource

use of org.spongepowered.api.command.CommandSource in project ProjectWorlds by trentech.

the class CommandRegen method process.

@Override
public CommandResult process(CommandSource source, String arguments) throws CommandException {
    if (arguments.equalsIgnoreCase("regen")) {
        throw new CommandException(getHelp().getUsageText());
    }
    String[] args = arguments.split(" ");
    if (args[args.length - 1].equalsIgnoreCase("--help")) {
        getHelp().execute(source);
        return CommandResult.success();
    }
    String worldName;
    try {
        worldName = args[0];
    } catch (Exception e) {
        throw new CommandException(getHelp().getUsageText());
    }
    Optional<WorldProperties> optionalProperties = Sponge.getServer().getWorldProperties(worldName);
    if (!optionalProperties.isPresent()) {
        throw new CommandException(Text.of(TextColors.RED, worldName, " does not exist"), false);
    }
    WorldProperties properties = optionalProperties.get();
    if (Sponge.getServer().getWorld(properties.getWorldName()).isPresent()) {
        throw new CommandException(Text.of(TextColors.RED, properties.getWorldName(), " must be unloaded before you can regenerate"), false);
    }
    WorldArchetype.Builder builder = WorldArchetype.builder().from(properties);
    String bool;
    try {
        bool = args[1];
        if (!bool.equalsIgnoreCase("true") && !bool.equalsIgnoreCase("false")) {
            source.sendMessage(Text.of(TextColors.YELLOW, bool, " is not a valid Boolean"));
            throw new CommandException(getHelp().getUsageText());
        }
        String seed;
        try {
            seed = args[2];
            try {
                Long s = Long.parseLong(seed);
                builder.seed(s);
            } catch (Exception e) {
                builder.seed(seed.hashCode());
            }
        } catch (Exception e) {
            builder.randomSeed();
        }
    } catch (Exception e) {
    }
    try {
        CompletableFuture<Boolean> delete = Sponge.getServer().deleteWorld(properties);
        while (!delete.isDone()) {
        }
        if (!delete.get()) {
            throw new CommandException(Text.of(TextColors.RED, "Could not delete ", properties.getWorldName()), false);
        }
    } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
    }
    source.sendMessage(Text.of(TextColors.DARK_GREEN, "Regenerating world.."));
    WorldArchetype settings = builder.enabled(true).loadsOnStartup(true).build(properties.getWorldName() + "_" + (ThreadLocalRandom.current().nextInt(100) + 1), properties.getWorldName());
    WorldProperties newProperties;
    try {
        newProperties = Sponge.getServer().createWorldProperties(properties.getWorldName(), settings);
    } catch (IOException e) {
        e.printStackTrace();
        throw new CommandException(Text.of(TextColors.RED, "Something went wrong. Check server log for details"), false);
    }
    Task.builder().delayTicks(20).execute(c -> {
        Optional<World> load = Sponge.getServer().loadWorld(newProperties);
        if (!load.isPresent()) {
            source.sendMessage(Text.of(TextColors.RED, "Could not load ", properties.getWorldName()));
            return;
        }
        Utils.createPlatform(load.get().getSpawnLocation().getRelative(Direction.DOWN));
        source.sendMessage(Text.of(TextColors.DARK_GREEN, properties.getWorldName(), " regenerated successfully"));
    }).submit(Main.getPlugin());
    return CommandResult.success();
}
Also used : CommandResult(org.spongepowered.api.command.CommandResult) Location(org.spongepowered.api.world.Location) Utils(com.gmail.trentech.pjw.utils.Utils) CommandSource(org.spongepowered.api.command.CommandSource) CommandCallable(org.spongepowered.api.command.CommandCallable) Sponge(org.spongepowered.api.Sponge) IOException(java.io.IOException) CompletableFuture(java.util.concurrent.CompletableFuture) ArrayList(java.util.ArrayList) ExecutionException(java.util.concurrent.ExecutionException) CommandException(org.spongepowered.api.command.CommandException) Direction(org.spongepowered.api.util.Direction) WorldArchetype(org.spongepowered.api.world.WorldArchetype) List(java.util.List) Text(org.spongepowered.api.text.Text) Main(com.gmail.trentech.pjw.Main) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) World(org.spongepowered.api.world.World) Task(org.spongepowered.api.scheduler.Task) WorldProperties(org.spongepowered.api.world.storage.WorldProperties) Help(com.gmail.trentech.pjc.help.Help) Optional(java.util.Optional) TextColors(org.spongepowered.api.text.format.TextColors) Optional(java.util.Optional) CommandException(org.spongepowered.api.command.CommandException) IOException(java.io.IOException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) CommandException(org.spongepowered.api.command.CommandException) WorldArchetype(org.spongepowered.api.world.WorldArchetype) ExecutionException(java.util.concurrent.ExecutionException) WorldProperties(org.spongepowered.api.world.storage.WorldProperties)

Example 57 with CommandSource

use of org.spongepowered.api.command.CommandSource in project core by CubeEngine.

the class ConfirmManager method requestConfirmation.

public static void requestConfirmation(I18n i18n, Text msg, CommandSource source, Runnable run) {
    Text confirm = i18n.translate(source, NONE, "Confirm");
    Text cancel = i18n.translate(source, NONE, "Cancel");
    UUID uuid = UUID.randomUUID();
    confirm = confirm.toBuilder().color(TextColors.GOLD).onClick(TextActions.executeCallback(s -> confirm(i18n, source, uuid, run))).build();
    cancel = cancel.toBuilder().color(TextColors.GOLD).onClick(TextActions.executeCallback(s -> cancel(i18n, source, uuid))).build();
    times.put(uuid, System.currentTimeMillis());
    source.sendMessage(msg.toBuilder().append(Text.of(" ")).append(confirm).append(Text.of(" ")).append(cancel).build());
}
Also used : TextActions(org.spongepowered.api.text.action.TextActions) NONE(org.cubeengine.libcube.service.i18n.formatter.MessageType.NONE) Text(org.spongepowered.api.text.Text) I18n(org.cubeengine.libcube.service.i18n.I18n) CommandSource(org.spongepowered.api.command.CommandSource) Map(java.util.Map) HashMap(java.util.HashMap) UUID(java.util.UUID) NEGATIVE(org.cubeengine.libcube.service.i18n.formatter.MessageType.NEGATIVE) POSITIVE(org.cubeengine.libcube.service.i18n.formatter.MessageType.POSITIVE) TextColors(org.spongepowered.api.text.format.TextColors) Text(org.spongepowered.api.text.Text) UUID(java.util.UUID)

Example 58 with CommandSource

use of org.spongepowered.api.command.CommandSource in project core by CubeEngine.

the class HelpCommand method execute.

@Override
public boolean execute(CommandInvocation invocation) {
    if (!(invocation.getCommandSource() instanceof CommandSource)) {
        return false;
    }
    CommandDescriptor descriptor = helpTarget.getDescriptor();
    CommandSource sender = (CommandSource) invocation.getCommandSource();
    TextFormat formatGray = NONE.color(GRAY);
    i18n.send(sender, formatGray, "Description: {input}", i18n.translate(sender, MessageType.NONE, descriptor.getDescription()).toPlain());
    List<String> labels = new ArrayList<>(invocation.getLabels());
    if (labels.isEmpty()) {
        labels.add("");
    }
    if ("?".equals(labels.get(labels.size() - 1))) {
        labels.remove(labels.size() - 1);
    }
    i18n.send(sender, formatGray, "Usage: {input}", descriptor.getUsage(invocation, labels.toArray(new String[labels.size()])));
    sender.sendMessage(Text.of());
    if (helpTarget instanceof DispatcherCommand) {
        Set<CommandBase> commands = helpTarget.getCommands();
        if (!commands.isEmpty() && (commands.size() != 1 || // is Empty ignoring HelpCommand
        !(commands.iterator().next() instanceof HelpCommand))) {
            i18n.send(sender, NEUTRAL, "The following sub-commands are available:");
            sender.sendMessage(Text.of());
            commands.stream().filter(command -> !(command instanceof HelpCommand || command instanceof AliasCommand && commands.contains(((AliasCommand) command).getTarget()))).filter(command -> !(command.getDescriptor() instanceof CubeCommandDescriptor && ((CubeCommandDescriptor) command.getDescriptor()).isCheckPerm() && !sender.hasPermission(((CubeCommandDescriptor) command.getDescriptor()).getPermission().getName()))).forEach(command -> sender.sendMessage(Text.of(YELLOW, command.getDescriptor().getName()).toBuilder().onClick(TextActions.runCommand("/" + (String.join(" ", labels) + " " + command.getDescriptor().getName()).trim() + " ?")).append(Text.of(WHITE, ": ", GRAY, i18n.translate(sender, TextFormat.NONE, command.getDescriptor().getDescription()))).build()));
            sender.sendMessage(Text.of());
        } else if (helpTarget instanceof ParametricContainerCommand) {
            i18n.send(sender, MessageType.NEGATIVE, "No actions are available");
            sender.sendMessage(Text.of());
        }
    }
    /*
        if (descriptor instanceof CubeDescriptor)
        {
            sender.sendTranslated(GRAY, "Detailed help: {input#link:color=INDIGO}", "http://engine.cubeisland.de/c/" + ((CubeDescriptor)descriptor).getModule().getInformation().getName().toLowerCase() + "/" + StringUtils.implode("/", labels));
        }
        */
    return true;
}
Also used : TextActions(org.spongepowered.api.text.action.TextActions) I18n(org.cubeengine.libcube.service.i18n.I18n) CommandSource(org.spongepowered.api.command.CommandSource) CommandBase(org.cubeengine.butler.CommandBase) MessageType(org.cubeengine.libcube.service.i18n.formatter.MessageType) Set(java.util.Set) NEUTRAL(org.cubeengine.libcube.service.i18n.formatter.MessageType.NEUTRAL) Dispatcher(org.cubeengine.butler.Dispatcher) SimpleCommandDescriptor(org.cubeengine.butler.SimpleCommandDescriptor) CommandInvocation(org.cubeengine.butler.CommandInvocation) ArrayList(java.util.ArrayList) CommandDescriptor(org.cubeengine.butler.CommandDescriptor) List(java.util.List) NONE(org.cubeengine.libcube.service.i18n.formatter.MessageType.NONE) Text(org.spongepowered.api.text.Text) TextFormat(org.spongepowered.api.text.format.TextFormat) AliasCommand(org.cubeengine.butler.alias.AliasCommand) DispatcherCommand(org.cubeengine.butler.DispatcherCommand) TextColors(org.spongepowered.api.text.format.TextColors) ParametricContainerCommand(org.cubeengine.butler.parametric.ParametricContainerCommand) ArrayList(java.util.ArrayList) CommandSource(org.spongepowered.api.command.CommandSource) SimpleCommandDescriptor(org.cubeengine.butler.SimpleCommandDescriptor) CommandDescriptor(org.cubeengine.butler.CommandDescriptor) AliasCommand(org.cubeengine.butler.alias.AliasCommand) CommandBase(org.cubeengine.butler.CommandBase) TextFormat(org.spongepowered.api.text.format.TextFormat) ParametricContainerCommand(org.cubeengine.butler.parametric.ParametricContainerCommand) DispatcherCommand(org.cubeengine.butler.DispatcherCommand)

Example 59 with CommandSource

use of org.spongepowered.api.command.CommandSource in project core by CubeEngine.

the class EnchantmentParser method suggest.

@Override
public List<String> suggest(Class clazz, CommandInvocation invocation) {
    CommandSource sender = (CommandSource) invocation.getCommandSource();
    ItemStack item = sender instanceof Player ? ((Player) sender).getItemInHand(HandTypes.MAIN_HAND).orElse(null) : null;
    String token = invocation.currentToken();
    return Sponge.getRegistry().getAllOf(EnchantmentType.class).stream().filter(e -> item == null || e.canBeAppliedToStack(item)).map(e -> e.getTranslation().get().replace(" ", "")).filter(name -> name.toLowerCase().startsWith(token.toLowerCase())).collect(Collectors.toList());
}
Also used : SilentException(org.cubeengine.butler.exception.SilentException) ParserException(org.cubeengine.butler.parameter.argument.ParserException) Game(org.spongepowered.api.Game) EnchantmentType(org.spongepowered.api.item.enchantment.EnchantmentType) NEUTRAL(org.cubeengine.libcube.service.i18n.formatter.MessageType.NEUTRAL) GameRegistry(org.spongepowered.api.GameRegistry) TextActions.showText(org.spongepowered.api.text.action.TextActions.showText) ArgumentParser(org.cubeengine.butler.parameter.argument.ArgumentParser) ItemStack(org.spongepowered.api.item.inventory.ItemStack) Text(org.spongepowered.api.text.Text) Completer(org.cubeengine.butler.parameter.argument.Completer) YELLOW(org.spongepowered.api.text.format.TextColors.YELLOW) TextColors(org.spongepowered.api.text.format.TextColors) DefaultValue(org.cubeengine.butler.parameter.argument.DefaultValue) I18n(org.cubeengine.libcube.service.i18n.I18n) CommandSource(org.spongepowered.api.command.CommandSource) Sponge(org.spongepowered.api.Sponge) EnchantMatcher(org.cubeengine.libcube.service.matcher.EnchantMatcher) POSITIVE(org.cubeengine.libcube.service.i18n.formatter.MessageType.POSITIVE) CommandInvocation(org.cubeengine.butler.CommandInvocation) Collectors(java.util.stream.Collectors) List(java.util.List) HandTypes(org.spongepowered.api.data.type.HandTypes) Player(org.spongepowered.api.entity.living.player.Player) NEGATIVE(org.cubeengine.libcube.service.i18n.formatter.MessageType.NEGATIVE) TooFewArgumentsException(org.cubeengine.butler.parameter.TooFewArgumentsException) Player(org.spongepowered.api.entity.living.player.Player) EnchantmentType(org.spongepowered.api.item.enchantment.EnchantmentType) CommandSource(org.spongepowered.api.command.CommandSource) ItemStack(org.spongepowered.api.item.inventory.ItemStack)

Example 60 with CommandSource

use of org.spongepowered.api.command.CommandSource in project LanternServer by LanternPowered.

the class CommandWeather method completeSpec.

@Override
public void completeSpec(PluginContainer pluginContainer, CommandSpec.Builder specBuilder) {
    specBuilder.arguments(GenericArguments.flags().valueFlag(GenericArguments.world(CommandHelper.WORLD_KEY), "-world", "w").buildWith(GenericArguments.none()), new PatternMatchingCommandElement(Text.of("type")) {

        @Override
        protected Iterable<String> getChoices(CommandSource source) {
            Collection<Weather> weathers = Sponge.getRegistry().getAllOf(Weather.class);
            ImmutableList.Builder<String> builder = ImmutableList.builder();
            for (Weather weather : weathers) {
                builder.add(weather.getId());
                builder.addAll(((LanternWeather) weather).getAliases());
            }
            return builder.build();
        }

        @Override
        protected Object getValue(String choice) throws IllegalArgumentException {
            final Optional<Weather> optWeather = Sponge.getRegistry().getType(Weather.class, choice);
            if (!optWeather.isPresent()) {
                return Sponge.getRegistry().getAllOf(Weather.class).stream().filter(weather -> {
                    for (String alias : ((LanternWeather) weather).getAliases()) {
                        if (alias.equalsIgnoreCase(choice)) {
                            return true;
                        }
                    }
                    return false;
                }).findAny().orElseThrow(() -> new IllegalArgumentException("Invalid input " + choice + " was found"));
            }
            return optWeather.get();
        }
    }, GenericArguments.optional(GenericArguments.integer(Text.of("duration")))).executor((src, args) -> {
        LanternWorldProperties world = CommandHelper.getWorldProperties(src, args);
        WeatherUniverse weatherUniverse = world.getWorld().get().getWeatherUniverse().orElse(null);
        Weather type = args.<Weather>getOne("type").get();
        if (weatherUniverse != null) {
            if (args.hasAny("duration")) {
                weatherUniverse.setWeather(type, args.<Integer>getOne("duration").get() * 20);
            } else {
                weatherUniverse.setWeather(type);
            }
        }
        src.sendMessage(t("Changing to " + type.getName() + " weather"));
        return CommandResult.success();
    });
}
Also used : Weather(org.spongepowered.api.world.weather.Weather) LanternWeather(org.lanternpowered.server.world.weather.LanternWeather) LanternWeather(org.lanternpowered.server.world.weather.LanternWeather) PatternMatchingCommandElement(org.spongepowered.api.command.args.PatternMatchingCommandElement) ImmutableList(com.google.common.collect.ImmutableList) WeatherUniverse(org.spongepowered.api.world.weather.WeatherUniverse) CommandSource(org.spongepowered.api.command.CommandSource) LanternWorldProperties(org.lanternpowered.server.world.LanternWorldProperties)

Aggregations

CommandSource (org.spongepowered.api.command.CommandSource)91 Text (org.spongepowered.api.text.Text)60 CommandResult (org.spongepowered.api.command.CommandResult)48 List (java.util.List)47 CommandContext (org.spongepowered.api.command.args.CommandContext)45 Collectors (java.util.stream.Collectors)37 Sponge (org.spongepowered.api.Sponge)37 Player (org.spongepowered.api.entity.living.player.Player)36 Optional (java.util.Optional)35 TextColors (org.spongepowered.api.text.format.TextColors)30 CommandElement (org.spongepowered.api.command.args.CommandElement)27 TextActions (org.spongepowered.api.text.action.TextActions)27 NonnullByDefault (org.spongepowered.api.util.annotation.NonnullByDefault)25 AbstractCommand (io.github.nucleuspowered.nucleus.internal.command.AbstractCommand)24 Permissions (io.github.nucleuspowered.nucleus.internal.annotations.command.Permissions)23 RegisterCommand (io.github.nucleuspowered.nucleus.internal.annotations.command.RegisterCommand)23 GenericArguments (org.spongepowered.api.command.args.GenericArguments)23 Util (io.github.nucleuspowered.nucleus.Util)20 Nullable (javax.annotation.Nullable)20 Map (java.util.Map)19