use of org.spongepowered.api.command.CommandPermissionException in project SpongeCommon by SpongePowered.
the class MinecraftCommandWrapper method process.
@Override
public CommandResult process(CommandSource source, String arguments) throws CommandException {
if (!testPermission(source)) {
throw new CommandPermissionException(Text.of(SpongeImpl.getGame().getRegistry().getTranslationById(TRANSLATION_NO_PERMISSION).get()));
}
CommandHandler handler = (CommandHandler) SpongeImpl.getServer().getCommandManager();
final ICommandSender mcSender = WrapperICommandSender.of(source);
final String[] splitArgs = splitArgs(arguments);
int usernameIndex = 0;
try {
usernameIndex = handler.getUsernameIndex(this.command, splitArgs);
} catch (net.minecraft.command.CommandException e) {
throw new RuntimeException(e);
}
int successCount = 0;
if (!throwEvent(mcSender, splitArgs)) {
return CommandResult.empty();
}
// Below this is copied from CommandHandler.execute. This might need to be updated between versions.
int affectedEntities = 1;
if (usernameIndex > -1) {
List<Entity> list = null;
try {
list = EntitySelector.matchEntities(mcSender, splitArgs[usernameIndex], Entity.class);
} catch (net.minecraft.command.CommandException e) {
throw new RuntimeException(e);
}
String previousNameVal = splitArgs[usernameIndex];
affectedEntities = list.size();
((IMixinCommandHandler) handler).setExpandedSelector(true);
for (Entity entity : list) {
splitArgs[usernameIndex] = entity.getCachedUniqueIdString();
if (tryExecute(handler, mcSender, splitArgs, arguments)) {
++successCount;
}
}
splitArgs[usernameIndex] = previousNameVal;
((IMixinCommandHandler) handler).setExpandedSelector(false);
} else {
if (tryExecute(handler, mcSender, splitArgs, arguments)) {
++successCount;
}
}
return CommandResult.builder().affectedEntities(affectedEntities).successCount(successCount).build();
}
use of org.spongepowered.api.command.CommandPermissionException in project SpongeCommon by SpongePowered.
the class SpongeCommandManager method process.
@Override
public CommandResult process(CommandSource source, String commandLine) {
final String[] argSplit = commandLine.split(" ", 2);
Sponge.getCauseStackManager().pushCause(source);
final SendCommandEvent event = SpongeEventFactory.createSendCommandEvent(Sponge.getCauseStackManager().getCurrentCause(), argSplit.length > 1 ? argSplit[1] : "", argSplit[0], CommandResult.empty());
Sponge.getGame().getEventManager().post(event);
Sponge.getCauseStackManager().popCause();
if (event.isCancelled()) {
return event.getResult();
}
// Only the first part of argSplit is used at the moment, do the other in the future if needed.
argSplit[0] = event.getCommand();
commandLine = event.getCommand();
if (!event.getArguments().isEmpty()) {
commandLine = commandLine + ' ' + event.getArguments();
}
try {
try (StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame();
// Since we know we are in the main thread, this is safe to do without a thread check
CommandPhaseContext context = GeneralPhase.State.COMMAND.createPhaseContext().source(source).addCaptures().addEntityDropCaptures().buildAndSwitch()) {
if (source instanceof EntityPlayer) {
// Enable player inventory capture
((IMixinInventoryPlayer) ((EntityPlayer) source).inventory).setCapture(true);
}
Sponge.getCauseStackManager().pushCause(source);
final CommandResult result = this.dispatcher.process(source, commandLine);
return result;
} catch (InvocationCommandException ex) {
if (ex.getCause() != null) {
throw ex.getCause();
}
} catch (CommandPermissionException ex) {
Text text = ex.getText();
if (text != null) {
source.sendMessage(error(text));
}
} catch (CommandException ex) {
Text text = ex.getText();
if (text != null) {
source.sendMessage(error(text));
}
if (ex.shouldIncludeUsage()) {
final Optional<CommandMapping> mapping = this.dispatcher.get(argSplit[0], source);
if (mapping.isPresent()) {
Text usage;
if (ex instanceof ArgumentParseException.WithUsage) {
usage = ((ArgumentParseException.WithUsage) ex).getUsage();
} else {
usage = mapping.get().getCallable().getUsage(source);
}
source.sendMessage(error(t("Usage: /%s %s", argSplit[0], usage)));
}
}
}
} catch (Throwable thr) {
Text.Builder excBuilder;
if (thr instanceof TextMessageException) {
Text text = ((TextMessageException) thr).getText();
excBuilder = text == null ? Text.builder("null") : Text.builder();
} else {
excBuilder = Text.builder(String.valueOf(thr.getMessage()));
}
if (source.hasPermission("sponge.debug.hover-stacktrace")) {
final StringWriter writer = new StringWriter();
thr.printStackTrace(new PrintWriter(writer));
excBuilder.onHover(TextActions.showText(Text.of(writer.toString().replace("\t", " ").replace("\r\n", "\n").replace("\r", // I mean I guess somebody could be running this on like OS 9?
"\n"))));
}
source.sendMessage(error(t("Error occurred while executing command: %s", excBuilder.build())));
this.logger.error(TextSerializers.PLAIN.serialize(t("Error occurred while executing command '%s' for source %s: %s", commandLine, source.toString(), String.valueOf(thr.getMessage()))), thr);
}
return CommandResult.empty();
}
use of org.spongepowered.api.command.CommandPermissionException in project LanternServer by LanternPowered.
the class LanternCommandManager method process.
@Override
public CommandResult process(CommandSource source, String commandLine) {
checkNotNull(source, "source");
final String[] argSplit = commandLine.split(" ", 2);
final CauseStack causeStack = CauseStack.currentOrEmpty();
try (CauseStack.Frame frame = causeStack.pushCauseFrame()) {
frame.pushCause(source);
final SendCommandEvent event = SpongeEventFactory.createSendCommandEvent(frame.getCurrentCause(), argSplit.length > 1 ? argSplit[1] : "", argSplit[0], CommandResult.empty());
Sponge.getGame().getEventManager().post(event);
if (event.isCancelled()) {
return event.getResult();
}
// Only the first part of argSplit is used at the moment, do the other in the future if needed.
argSplit[0] = event.getCommand();
commandLine = event.getCommand();
if (!event.getArguments().isEmpty()) {
commandLine = commandLine + ' ' + event.getArguments();
}
try {
return this.dispatcher.process(source, commandLine);
} catch (InvocationCommandException ex) {
if (ex.getCause() != null) {
throw ex.getCause();
}
} catch (CommandPermissionException ex) {
Text text = ex.getText();
if (text != null) {
source.sendMessage(error(text));
}
} catch (CommandException ex) {
Text text = ex.getText();
if (text != null) {
source.sendMessage(error(text));
}
if (ex.shouldIncludeUsage()) {
final Optional<CommandMapping> mapping = this.dispatcher.get(argSplit[0], source);
mapping.ifPresent(commandMapping -> source.sendMessage(error(t("commands.generic.usage", t("/%s %s", argSplit[0], commandMapping.getCallable().getUsage(source))))));
}
}
} catch (Throwable thr) {
final Text.Builder excBuilder;
if (thr instanceof TextMessageException) {
final Text text = ((TextMessageException) thr).getText();
excBuilder = text == null ? Text.builder("null") : Text.builder().append(text);
} else {
excBuilder = Text.builder(String.valueOf(thr.getMessage()));
}
if (source.hasPermission("sponge.debug.hover-stacktrace")) {
final StringWriter writer = new StringWriter();
thr.printStackTrace(new PrintWriter(writer));
excBuilder.onHover(TextActions.showText(Text.of(writer.toString().replace("\t", " ").replace("\r\n", "\n").replace("\r", // I mean I guess somebody could be running this on like OS 9?
"\n"))));
}
source.sendMessage(error(t("Error occurred while executing command: %s", excBuilder.build())));
this.logger.error(LanternTexts.toLegacy(t("Error occurred while executing command '%s' for source %s: %s", commandLine, source.toString(), String.valueOf(thr.getMessage()))), thr);
}
return CommandResult.empty();
}
use of org.spongepowered.api.command.CommandPermissionException in project Nucleus by NucleusPowered.
the class AbstractCommand method process.
private CommandResult process(CommandSource source, String command, String arguments, CommandArgs args) throws CommandException {
// Phase one: child command processing. Keep track of all thrown arguments.
List<Tuple<String, CommandException>> thrown = Lists.newArrayList();
final CommandContext context = new CommandContext();
T castedSource;
try {
// If we have a child command to execute, then we execute it.
if (args.hasNext() && this.dispatcher.containsAlias(args.peek())) {
Object state = args.getState();
String next = args.next();
try {
// If this works, then we're A-OK.
CommandCallable callable = this.dispatcher.get(next.toLowerCase()).get().getCallable();
if (callable instanceof AbstractCommand) {
return ((AbstractCommand) callable).process(source, command + " " + next, arguments, args);
}
return callable.process(source, arguments);
} catch (NucleusCommandException e) {
// Didn't work out. Let's move on.
thrown.addAll(e.getExceptions());
if (!e.isAllowFallback()) {
throw e;
}
} catch (CommandException e) {
// If the Exception is _not_ of right type, wrap it and add it. This shouldn't happen though.
thrown.add(Tuple.of(command + " " + next, e));
} finally {
args.setState(state);
}
}
// Phase one: test for what is required
if (requiresEconomy && !plugin.getEconHelper().economyServiceExists()) {
source.sendMessage(NucleusPlugin.getNucleus().getMessageProvider().getTextMessageWithFormat("command.economyrequired"));
return CommandResult.empty();
}
// Phase two: source type - test to see if the person in question can execute this command.
castedSource = checkSourceType(source);
// Phase three - test the permission.
if (!testPermissionOnSubject(castedSource)) {
throw new CommandPermissionException();
}
if (!this.hasExecutor) {
if (thrown.isEmpty()) {
// OK, we just process the usage command instead.
return this.usageCommand.process(source, "", args.nextIfPresent().map(String::toLowerCase).orElse(null));
} else {
throw new NucleusCommandException(thrown);
}
}
// Phase four - create the context and parse the arguments.
this.argumentParser.parse(source, args, context);
if (args.hasNext()) {
thrown.add(Tuple.of(command, new NucleusArgumentParseException(Text.of(TextColors.RED, "Too many arguments"), args.getRaw(), args.getRawPosition(), Text.of(getSimpleUsage(source)), getChildrenUsage(source).orElse(null), true)));
throw new NucleusCommandException(thrown, allowFallback(source, args, context));
}
} catch (NucleusCommandException nce) {
throw nce;
} catch (ArgumentParseException ape) {
// get the command to get the usage/subs from.
thrown.add(Tuple.of(command, NucleusArgumentParseException.from(ape, Text.of(getSimpleUsage(source)), getChildrenUsage(source).orElse(null))));
throw new NucleusCommandException(thrown, allowFallback(source, args, context));
} catch (CommandException ex) {
// Errors at this point are expected, so we'll run with it - no need for debug mode checks.
thrown.add(Tuple.of(command, ex));
throw new NucleusCommandException(thrown, allowFallback(source, args, context));
} catch (Throwable throwable) {
String m;
if (throwable.getMessage() == null) {
m = "null";
} else {
m = throwable.getMessage();
}
thrown.add(Tuple.of(command, new CommandException(Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("command.exception.unexpected", m), throwable)));
// this is on demand, so we should throw it.
throwable.printStackTrace();
throw new NucleusCommandException(thrown, allowFallback(source, args, context));
}
try {
commandTimings.startTimingIfSync();
ContinueMode mode = preProcessChecks(castedSource, context);
if (!mode.cont) {
return mode.returnType;
}
if (castedSource instanceof Player) {
@SuppressWarnings("unchecked") ContinueMode cm = runChecks((Player) castedSource, context);
if (!cm.cont) {
return cm.returnType;
}
}
// If we're running async...
if (isAsync) {
// Create an executor that runs the command async.
plugin.getLogger().debug("Running " + this.getClass().getName() + " in async mode.");
Sponge.getScheduler().createAsyncExecutor(plugin).execute(() -> onExecute(castedSource, context));
// Tell Sponge we're done.
return CommandResult.success();
}
return onExecute(castedSource, context);
} finally {
commandTimings.stopTimingIfSync();
}
}
Aggregations