Search in sources :

Example 1 with CommandException

use of org.enginehub.piston.exception.CommandException in project FastAsyncWorldEdit by IntellectualSites.

the class PlatformCommandManager method handleCommandSuggestion.

@Subscribe
public void handleCommandSuggestion(CommandSuggestionEvent event) {
    try {
        String rawArgs = event.getArguments();
        // FAWE start
        // Increase the resulting positions by 1 if we remove a leading `/`
        final int posOffset = rawArgs.startsWith("/") ? 1 : 0;
        String arguments = rawArgs.startsWith("/") ? rawArgs.substring(1) : rawArgs;
        // FAWE end
        List<Substring> split = parseArgs(arguments).collect(Collectors.toList());
        List<String> argStrings = split.stream().map(Substring::getSubstring).collect(Collectors.toList());
        // FAWE start - event & suggestion
        MemoizingValueAccess access = initializeInjectedValues(() -> arguments, event.getActor(), event, true);
        // FAWE end
        ImmutableSet<Suggestion> suggestions;
        try {
            suggestions = commandManager.getSuggestions(access, argStrings);
        } catch (Throwable t) {
            // catch errors which are *not* command exceptions generated by parsers/suggesters
            if (!(t instanceof InputParseException) && !(t instanceof CommandException)) {
                Throwable cause = t;
                // These exceptions can be very nested, and should not be printed as they are not an actual error.
                boolean printError = true;
                while ((cause = cause.getCause()) != null) {
                    if (cause instanceof InputParseException || cause instanceof CommandException) {
                        printError = false;
                        break;
                    }
                }
                if (printError) {
                    LOGGER.error("Unexpected error occurred while generating suggestions for input: {}", arguments, t);
                    return;
                }
            }
            return;
        }
        event.setSuggestions(suggestions.stream().map(suggestion -> {
            int noSlashLength = arguments.length();
            Substring original = suggestion.getReplacedArgument() == split.size() ? Substring.from(arguments, noSlashLength, noSlashLength) : split.get(suggestion.getReplacedArgument());
            return Substring.wrap(suggestion.getSuggestion(), original.getStart() + posOffset, original.getEnd() + posOffset);
        }).collect(Collectors.toList()));
    } catch (ConditionFailedException e) {
        if (e.getCondition() instanceof PermissionCondition) {
            event.setSuggestions(new ArrayList<>());
        }
    }
}
Also used : Substring(com.sk89q.worldedit.internal.util.Substring) MemoizingValueAccess(org.enginehub.piston.inject.MemoizingValueAccess) ArrayList(java.util.ArrayList) CommandException(org.enginehub.piston.exception.CommandException) Suggestion(org.enginehub.piston.suggestion.Suggestion) InputParseException(com.sk89q.worldedit.extension.input.InputParseException) ConditionFailedException(org.enginehub.piston.exception.ConditionFailedException) PermissionCondition(com.sk89q.worldedit.command.util.PermissionCondition) SubCommandPermissionCondition(com.sk89q.worldedit.command.util.SubCommandPermissionCondition) Subscribe(com.sk89q.worldedit.util.eventbus.Subscribe)

Example 2 with CommandException

use of org.enginehub.piston.exception.CommandException in project FastAsyncWorldEdit by IntellectualSites.

the class PlatformCommandManager method initializeInjectedValues.

// FAWE end
// FAWE start - Event & suggestions, make method public
public MemoizingValueAccess initializeInjectedValues(Arguments arguments, Actor actor, Event event, boolean isSuggestions) {
    // FAWE end
    InjectedValueStore store = MapBackedValueStore.create();
    store.injectValue(Key.of(Actor.class), ValueProvider.constant(actor));
    if (actor instanceof Player) {
        store.injectValue(Key.of(Player.class), ValueProvider.constant((Player) actor));
    } else {
        store.injectValue(Key.of(Player.class), context -> {
            throw new CommandException(Caption.of("worldedit.command.player-only"), ImmutableList.of());
        });
    }
    store.injectValue(Key.of(Arguments.class), ValueProvider.constant(arguments));
    store.injectValue(Key.of(LocalSession.class), context -> {
        LocalSession localSession = worldEdit.getSessionManager().get(actor);
        localSession.tellVersion(actor);
        return Optional.of(localSession);
    });
    store.injectValue(Key.of(boolean.class), context -> Optional.of(isSuggestions));
    store.injectValue(Key.of(InjectedValueStore.class), ValueProvider.constant(store));
    store.injectValue(Key.of(Event.class), ValueProvider.constant(event));
    // FAWE start - allow giving editsessions
    if (event instanceof CommandEvent) {
        EditSession session = ((CommandEvent) event).getSession();
        if (session != null) {
            store.injectValue(Key.of(EditSession.class), context -> Optional.of(session));
        }
    }
    // FAWE end
    return MemoizingValueAccess.wrap(MergedValueAccess.of(store, globalInjectedValues));
}
Also used : InjectedValueStore(org.enginehub.piston.inject.InjectedValueStore) Player(com.sk89q.worldedit.entity.Player) Arguments(com.sk89q.worldedit.command.argument.Arguments) LocalSession(com.sk89q.worldedit.LocalSession) CommandEvent(com.sk89q.worldedit.event.platform.CommandEvent) CommandSuggestionEvent(com.sk89q.worldedit.event.platform.CommandSuggestionEvent) Event(com.sk89q.worldedit.event.Event) CommandEvent(com.sk89q.worldedit.event.platform.CommandEvent) CommandException(org.enginehub.piston.exception.CommandException) EditSession(com.sk89q.worldedit.EditSession)

Example 3 with CommandException

use of org.enginehub.piston.exception.CommandException in project FastAsyncWorldEdit by IntellectualSites.

the class CommandLoggingHandler method beforeCall.

@Override
public void beforeCall(Method method, CommandParameters parameters) {
    Logging loggingAnnotation = method.getAnnotation(Logging.class);
    Logging.LogMode logMode;
    StringBuilder builder = new StringBuilder();
    if (loggingAnnotation == null) {
        logMode = null;
    } else {
        logMode = loggingAnnotation.value();
    }
    Optional<Actor> actorOpt = parameters.injectedValue(Key.of(Actor.class));
    if (!actorOpt.isPresent()) {
        return;
    }
    Actor actor = actorOpt.get();
    World world;
    try {
        Optional<World> worldOpt = parameters.injectedValue(Key.of(World.class));
        if (!worldOpt.isPresent()) {
            return;
        }
        world = worldOpt.get();
    } catch (CommandException ex) {
        return;
    }
    builder.append("WorldEdit: ").append(actor.getName());
    builder.append(" (in \"").append(world.getName()).append("\")");
    builder.append(": ").append(parameters.getMetadata().getCalledName());
    builder.append(": ").append(Stream.concat(Stream.of(parameters.getMetadata().getCalledName()), parameters.getMetadata().getArguments().stream()).collect(Collectors.joining(" ")));
    if (logMode != null && actor instanceof Player) {
        Player player = (Player) actor;
        Vector3 position = player.getLocation().toVector();
        LocalSession session = worldEdit.getSessionManager().get(actor);
        switch(logMode) {
            case PLACEMENT:
                try {
                    position = session.getPlacementPosition(actor).toVector3();
                } catch (IncompleteRegionException e) {
                    break;
                }
            case POSITION:
                builder.append(" - Position: ").append(position);
                break;
            case ALL:
                builder.append(" - Position: ").append(position);
            case ORIENTATION_REGION:
                builder.append(" - Orientation: ").append(player.getCardinalDirection().name());
            case REGION:
                try {
                    builder.append(" - Region: ").append(session.getSelection(world));
                } catch (IncompleteRegionException e) {
                    break;
                }
                break;
        }
    }
    logger.info(builder.toString());
}
Also used : Logging(com.sk89q.worldedit.command.util.Logging) Player(com.sk89q.worldedit.entity.Player) Actor(com.sk89q.worldedit.extension.platform.Actor) LocalSession(com.sk89q.worldedit.LocalSession) IncompleteRegionException(com.sk89q.worldedit.IncompleteRegionException) Vector3(com.sk89q.worldedit.math.Vector3) CommandException(org.enginehub.piston.exception.CommandException) World(com.sk89q.worldedit.world.World)

Example 4 with CommandException

use of org.enginehub.piston.exception.CommandException in project FastAsyncWorldEdit by IntellectualSites.

the class PlatformCommandManager method handleCommandTask.

public void handleCommandTask(ThrowableSupplier<Throwable> task, InjectedValueAccess context, @Nullable LocalSession session, CommandEvent event) {
    Actor actor = context.injectedValue(Key.of(Actor.class)).orElseThrow(() -> new IllegalStateException("No player"));
    long start = System.currentTimeMillis();
    try {
        // exceptions and rethrow their converted form, if their is one.
        try {
            Object result = task.get();
        } catch (Throwable t) {
            // Use the exception converter to convert the exception if any of its causes
            // can be converted, otherwise throw the original exception
            Throwable next = t;
            do {
                exceptionConverter.convert(next);
                next = next.getCause();
            } while (next != null);
            throw t;
        }
    } catch (ConditionFailedException e) {
        if (e.getCondition() instanceof PermissionCondition) {
            actor.print(Caption.of("fawe.error.no-perm", StringMan.getString(((PermissionCondition) e.getCondition()).getPermissions())));
        } else {
            actor.print(e.getRichMessage());
        }
    } catch (FaweException e) {
        actor.print(Caption.of("fawe.cancel.reason", e.getComponent()));
    } catch (UsageException e) {
        actor.printError(e.getRichMessage());
    } catch (CommandExecutionException e) {
        handleUnknownException(actor, e.getCause());
    } catch (CommandException e) {
        if (e.getCause() instanceof FaweException) {
            actor.print(Caption.of("fawe.cancel.reason", ((FaweException) e.getCause()).getComponent()));
        } else {
            Component msg = e.getRichMessage();
            if (msg == TextComponent.empty()) {
                List<String> argList = parseArgs(event.getArguments()).map(Substring::getSubstring).collect(Collectors.toList());
                printUsage(actor, argList);
            } else {
                actor.printError(msg);
            }
        }
    } catch (Throwable t) {
        handleUnknownException(actor, t);
    } finally {
        if (context instanceof MemoizingValueAccess) {
            context = ((MemoizingValueAccess) context).snapshotMemory();
        }
        Optional<EditSession> editSessionOpt = context.injectedValue(Key.of(EditSession.class));
        // Require null CommandEvent#getSession as it means the editsession is being handled somewhere else.
        if (editSessionOpt.isPresent() && event.getSession() == null) {
            EditSession editSession = editSessionOpt.get();
            editSession.close();
            session.remember(editSession);
            long time = System.currentTimeMillis() - start;
            double timeS = (time / 1000.0);
            int changed = editSession.getBlockChangeCount();
            double throughput = timeS == 0 ? changed : changed / timeS;
            if (time > 1000) {
                actor.print(Caption.of("worldedit.command.time-elapsed", TextComponent.of(timeS), TextComponent.of(changed), TextComponent.of(Math.round(throughput))));
            }
            worldEdit.flushBlockBag(actor, editSession);
        }
        // TODO: Ping @MattBDev to reimplement 2020-02-04
        // CFICommands.CFISettings cfi = actor.getMeta("CFISettings");
        // if (cfi != null) {
        // HeightMapMCAGenerator gen = cfi.getGenerator();
        // if (gen != null && gen.isModified()) {
        // try {
        // gen.update();
        // CFIChangeSet set = new CFIChangeSet(gen, actor.getUniqueId());
        // session.remember(actor, gen, set, actor.getLimit());
        // } catch (IOException e) {
        // e.printStackTrace();
        // }
        // }
        // }
        Request.reset();
    }
    event.setCancelled(true);
}
Also used : Substring(com.sk89q.worldedit.internal.util.Substring) UsageException(org.enginehub.piston.exception.UsageException) MemoizingValueAccess(org.enginehub.piston.inject.MemoizingValueAccess) FaweException(com.fastasyncworldedit.core.internal.exception.FaweException) CommandException(org.enginehub.piston.exception.CommandException) ConditionFailedException(org.enginehub.piston.exception.ConditionFailedException) PermissionCondition(com.sk89q.worldedit.command.util.PermissionCondition) SubCommandPermissionCondition(com.sk89q.worldedit.command.util.SubCommandPermissionCondition) CommandExecutionException(org.enginehub.piston.exception.CommandExecutionException) ArrayList(java.util.ArrayList) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) EditSession(com.sk89q.worldedit.EditSession) Component(com.sk89q.worldedit.util.formatting.text.Component) TextComponent(com.sk89q.worldedit.util.formatting.text.TextComponent)

Example 5 with CommandException

use of org.enginehub.piston.exception.CommandException in project FastAsyncWorldEdit by IntellectualSites.

the class AsyncCommandBuilder method runTask.

@SuppressWarnings("deprecation")
private T runTask() {
    T result = null;
    try {
        result = callable.call();
        if (consumer != null) {
            consumer.accept(result);
        }
        if (successMessage != null) {
            sender.print(successMessage);
        }
    } catch (Throwable orig) {
        Component failure = failureMessage != null ? failureMessage : TextComponent.of("An error occurred");
        try {
            if (exceptionConverter != null) {
                try {
                    if (orig instanceof com.sk89q.minecraft.util.commands.CommandException) {
                        throw new CommandExecutionException(orig, ImmutableList.of());
                    }
                    exceptionConverter.convert(orig);
                    throw orig;
                } catch (CommandException converted) {
                    Component message;
                    // TODO remove this once WG migrates to piston and can use piston exceptions everywhere
                    message = tryExtractOldCommandException(converted);
                    if (message == null) {
                        if (Strings.isNullOrEmpty(converted.getMessage())) {
                            message = Caption.of("worldedit.error.unknown");
                        } else {
                            message = converted.getRichMessage();
                        }
                    }
                    sender.print(failure.append(TextComponent.of(": ")).append(message));
                }
            } else {
                throw orig;
            }
        } catch (Throwable unknown) {
            sender.print(failure.append(Caption.of("worldedit.command.error.report")));
            LOGGER.error("Uncaught exception occurred in task: " + description, orig);
        }
    }
    return result;
}
Also used : CommandExecutionException(org.enginehub.piston.exception.CommandExecutionException) CommandException(org.enginehub.piston.exception.CommandException) TextComponent(com.sk89q.worldedit.util.formatting.text.TextComponent) Component(com.sk89q.worldedit.util.formatting.text.Component)

Aggregations

CommandException (org.enginehub.piston.exception.CommandException)5 EditSession (com.sk89q.worldedit.EditSession)2 LocalSession (com.sk89q.worldedit.LocalSession)2 PermissionCondition (com.sk89q.worldedit.command.util.PermissionCondition)2 SubCommandPermissionCondition (com.sk89q.worldedit.command.util.SubCommandPermissionCondition)2 Player (com.sk89q.worldedit.entity.Player)2 Substring (com.sk89q.worldedit.internal.util.Substring)2 Component (com.sk89q.worldedit.util.formatting.text.Component)2 TextComponent (com.sk89q.worldedit.util.formatting.text.TextComponent)2 ArrayList (java.util.ArrayList)2 CommandExecutionException (org.enginehub.piston.exception.CommandExecutionException)2 ConditionFailedException (org.enginehub.piston.exception.ConditionFailedException)2 MemoizingValueAccess (org.enginehub.piston.inject.MemoizingValueAccess)2 FaweException (com.fastasyncworldedit.core.internal.exception.FaweException)1 ImmutableList (com.google.common.collect.ImmutableList)1 IncompleteRegionException (com.sk89q.worldedit.IncompleteRegionException)1 Arguments (com.sk89q.worldedit.command.argument.Arguments)1 Logging (com.sk89q.worldedit.command.util.Logging)1 Event (com.sk89q.worldedit.event.Event)1 CommandEvent (com.sk89q.worldedit.event.platform.CommandEvent)1