Search in sources :

Example 1 with CommandHandler

use of org.jboss.as.cli.CommandHandler in project wildfly-core by wildfly.

the class CommandCommandHandler method doHandle.

/* (non-Javadoc)
     * @see org.jboss.as.cli.handlers.CommandHandlerWithHelp#doHandle(org.jboss.as.cli.CommandContext)
     */
@Override
protected void doHandle(CommandContext ctx) throws CommandLineException {
    final ParsedCommandLine args = ctx.getParsedCommandLine();
    final String action = this.action.getValue(args);
    if (action == null) {
        throw new CommandFormatException("Command is missing.");
    }
    if (action.equals("list")) {
        ctx.printColumns(getExistingCommands());
        return;
    }
    if (action.equals("add")) {
        final String nodePath = this.nodePath.getValue(args, false);
        final String nodeChild = this.nodeChild.getValue(args, false);
        if (nodePath == null && nodeChild == null) {
            throw new CommandFormatException(this.nodePath.getFullName() + " or " + this.nodeChild.getFullName() + " must be defined");
        }
        if (nodePath != null && nodeChild != null) {
            throw new CommandFormatException("Only one of " + this.nodePath.getFullName() + " or " + this.nodeChild.getFullName() + " can be defined");
        }
        boolean isChildPath = nodeChild != null;
        String path = isChildPath ? nodeChild : nodePath;
        final String propName = this.idProperty.getValue(args, false);
        final String cmdName = this.commandName.getValue(args, true);
        validateInput(ctx, path, propName, isChildPath);
        if (cmdRegistry.getCommandHandler(cmdName) != null) {
            throw new CommandFormatException("Command '" + cmdName + "' already registered.");
        }
        cmdRegistry.registerHandler(new GenericTypeOperationHandler(cmdName, ctx, path, propName, isChildPath), cmdName);
        return;
    }
    if (action.equals("remove")) {
        final String cmdName = this.commandName.getValue(args, true);
        CommandHandler handler = cmdRegistry.getCommandHandler(cmdName);
        if (!(handler instanceof GenericTypeOperationHandler)) {
            throw new CommandFormatException("Command '" + cmdName + "' is not a generic type command.");
        }
        cmdRegistry.remove(cmdName);
        return;
    }
    throw new CommandFormatException("Unexpected action: " + action);
}
Also used : CommandFormatException(org.jboss.as.cli.CommandFormatException) ParsedCommandLine(org.jboss.as.cli.operation.ParsedCommandLine) CommandHandler(org.jboss.as.cli.CommandHandler)

Example 2 with CommandHandler

use of org.jboss.as.cli.CommandHandler in project wildfly-core by wildfly.

the class HelpCommand method execute.

@Override
public CommandResult execute(CLICommandInvocation commandInvocation) throws CommandException, InterruptedException {
    CommandContext ctx = commandInvocation.getCommandContext();
    if (command == null || command.isEmpty()) {
        if (commands) {
            return listAvailable(commandInvocation);
        } else {
            ctx.printLine(commandInvocation.getHelpInfo("help"));
        }
        return CommandResult.SUCCESS;
    }
    if (commands) {
        throw new CommandException("commands option not usable with an argument");
    }
    if (command.size() > 2) {
        throw new CommandException("Command has more than one action");
    }
    String mainCommand = command.get(0);
    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < command.size(); i++) {
        builder.append(command.get(i));
        if (i < command.size() - 1) {
            builder.append(" ");
        }
    }
    // An operation?
    if (OperationCommandContainer.isOperation(mainCommand)) {
        try {
            ctx.printLine(getOperationHelp(builder.toString(), commandInvocation.getCommandContext()));
        } catch (Exception ex) {
            ctx.printLine("Error getting operation help: " + ex.getLocalizedMessage());
        }
        return CommandResult.SUCCESS;
    }
    try {
        CommandLineParser parser = aeshRegistry.findCommand(mainCommand, builder.toString());
        // Special case for generic command that generates the help content on the fly.
        if (parser.getProcessedCommand().getCommand() instanceof LegacyCommand) {
            CommandHandler handler = ((LegacyCommand) parser.getProcessedCommand().getCommand()).getCommandHandler();
            if (handler instanceof GenericTypeOperationHandler) {
                try {
                    ((GenericTypeOperationHandler) handler).printDescription(commandInvocation.getCommandContext());
                } catch (CommandLineException ex1) {
                    throw new CommandException(ex1);
                }
            // We can only rely on handler, handler hides the actual file path
            // to its help. eg: remove-batch-line is actually batch-remove-line.txt
            } else if (handler instanceof CommandHandlerWithHelp) {
                try {
                    ((CommandHandlerWithHelp) handler).displayHelp(commandInvocation.getCommandContext());
                } catch (CommandLineException ex1) {
                    throw new CommandException(ex1);
                }
            }
        } else {
            ctx.printLine(parser.printHelp());
        }
    } catch (CommandNotFoundException ex) {
        throw new CommandException("Command " + builder.toString() + " does not exist.");
    }
    return CommandResult.SUCCESS;
}
Also used : CommandHandlerWithHelp(org.jboss.as.cli.handlers.CommandHandlerWithHelp) CommandContext(org.jboss.as.cli.CommandContext) CommandException(org.aesh.command.CommandException) CommandHandler(org.jboss.as.cli.CommandHandler) CommandNotFoundException(org.aesh.command.CommandNotFoundException) CommandException(org.aesh.command.CommandException) CommandLineException(org.jboss.as.cli.CommandLineException) CommandFormatException(org.jboss.as.cli.CommandFormatException) CommandLineException(org.jboss.as.cli.CommandLineException) GenericTypeOperationHandler(org.jboss.as.cli.handlers.GenericTypeOperationHandler) LegacyCommand(org.jboss.as.cli.impl.aesh.cmd.operation.LegacyCommandContainer.LegacyCommand) CommandLineParser(org.aesh.command.impl.parser.CommandLineParser) CommandNotFoundException(org.aesh.command.CommandNotFoundException)

Example 3 with CommandHandler

use of org.jboss.as.cli.CommandHandler in project wildfly-core by wildfly.

the class CommandContextImpl method handleCommand.

private void handleCommand(ParsedCommandLine parsed) throws CommandFormatException, CommandLineException {
    String line = parsed.getOriginalLine();
    try {
        List<CLIExecution> executions = aeshCommands.newExecutions(parsed);
        for (CLIExecution exec : executions) {
            CLICommandInvocation invContext = exec.getInvocation();
            this.invocationContext = invContext;
            String opLine = exec.getLine();
            // implies a split of the main command)
            if (opLine != null && !opLine.equals(line)) {
                resetArgs(opLine);
            }
            Throwable originalException = null;
            try {
                // Could be an operation.
                if (exec.isOperation()) {
                    handleOperation(parsedCmd);
                    continue;
                }
                // Could be a legacy command.
                CommandHandler handler = exec.getLegacyHandler();
                if (handler != null) {
                    handleLegacyCommand(exec.getLine(), handler, false);
                    continue;
                }
            } catch (Throwable ex) {
                if (ex instanceof InterruptedException) {
                    Thread.currentThread().interrupt();
                }
                originalException = ex;
            } finally {
                // OK to be null
                Throwable suppressed = originalException;
                // when calling exec.execute something that we are not doing here.
                if (invContext.getConfiguration().getOutputRedirection() != null) {
                    try {
                        invContext.getConfiguration().getOutputRedirection().close();
                    } catch (IOException ex) {
                        // Message must contain the Exception and the localized message.
                        if (ex instanceof AccessDeniedException) {
                            String message = ex.getMessage();
                            suppressed = new CommandLineException((message != null ? message : line) + " (Access denied)");
                        } else {
                            suppressed = new CommandLineException(ex.toString());
                        }
                        if (originalException != null) {
                            originalException.addSuppressed(suppressed);
                            suppressed = originalException;
                        }
                    }
                }
                if (suppressed != null) {
                    if (suppressed instanceof RuntimeException) {
                        throw (RuntimeException) suppressed;
                    }
                    if (suppressed instanceof Error) {
                        throw (Error) suppressed;
                    }
                    if (suppressed instanceof CommandLineException) {
                        throw (CommandLineException) suppressed;
                    }
                    if (suppressed instanceof CommandLineParserException) {
                        throw (CommandLineParserException) suppressed;
                    }
                    if (suppressed instanceof OptionValidatorException) {
                        throw (OptionValidatorException) suppressed;
                    }
                }
            }
            // child command. This is caused by aesh 2.0 behavior.
            if (isBatchMode()) {
                exec.populateCommand();
            }
            BatchCompliantCommand bc = exec.getBatchCompliant();
            if (isBatchMode() && bc != null) {
                try {
                    Batch batch = getBatchManager().getActiveBatch();
                    BatchCompliantCommand.BatchResponseHandler request = bc.buildBatchResponseHandler(this, batch.getAttachments());
                    // Wrap into legacy API.
                    ResponseHandler rh = null;
                    if (request != null) {
                        rh = (ModelNode step, OperationResponse response) -> {
                            request.handleResponse(step, response);
                        };
                    }
                    BatchedCommand batchedCmd = new DefaultBatchedCommand(this, line, bc.buildRequest(this, batch.getAttachments()), rh);
                    batch.add(batchedCmd);
                } catch (CommandFormatException e) {
                    throw new CommandFormatException("Failed to add to batch '" + line + "'", e);
                }
            } else {
                execute(() -> {
                    executor.execute(aeshCommands.newExecutableBuilder(exec), timeout, TimeUnit.SECONDS);
                    return null;
                }, line);
            }
        }
    } catch (CommandNotFoundException ex) {
        // Commands that are not exposed in completion.
        if (parsedCmd.getFormat() != OperationFormat.INSTANCE) {
            CommandHandler h = cmdRegistry.getCommandHandler(ex.getCommandName().toLowerCase());
            if (h != null) {
                handleLegacyCommand(line, h, false);
                return;
            }
        }
        throw new CommandLineException("Unexpected command '" + line + "'. Type 'help --commands' for the list of supported commands.");
    } catch (IOException ex) {
        throw new CommandLineException(ex);
    } catch (CommandLineParserException | OptionValidatorException ex) {
        throw new CommandFormatException(ex);
    }
}
Also used : AccessDeniedException(java.nio.file.AccessDeniedException) ResponseHandler(org.jboss.as.cli.handlers.ResponseHandler) CLICommandInvocation(org.wildfly.core.cli.command.aesh.CLICommandInvocation) CLIExecution(org.jboss.as.cli.impl.aesh.AeshCommands.CLIExecution) CommandHandler(org.jboss.as.cli.CommandHandler) CommandCommandHandler(org.jboss.as.cli.handlers.CommandCommandHandler) CommandLineException(org.jboss.as.cli.CommandLineException) Batch(org.jboss.as.cli.batch.Batch) DefaultBatchedCommand(org.jboss.as.cli.batch.impl.DefaultBatchedCommand) OptionValidatorException(org.aesh.command.validator.OptionValidatorException) IOException(java.io.IOException) CommandLineParserException(org.aesh.command.parser.CommandLineParserException) CommandFormatException(org.jboss.as.cli.CommandFormatException) ModelNode(org.jboss.dmr.ModelNode) OperationResponse(org.jboss.as.controller.client.OperationResponse) CommandNotFoundException(org.aesh.command.CommandNotFoundException) BatchCompliantCommand(org.wildfly.core.cli.command.BatchCompliantCommand) DefaultBatchedCommand(org.jboss.as.cli.batch.impl.DefaultBatchedCommand) BatchedCommand(org.jboss.as.cli.batch.BatchedCommand)

Example 4 with CommandHandler

use of org.jboss.as.cli.CommandHandler in project wildfly-core by wildfly.

the class CommandContextImpl method buildRequest.

protected HandledRequest buildRequest(String line, boolean batchMode) throws CommandFormatException {
    if (line == null || line.isEmpty()) {
        throw new OperationFormatException("The line is null or empty.");
    }
    final DefaultCallbackHandler originalParsedArguments = this.parsedCmd;
    final String originalCmdLine = this.cmdLine;
    try {
        this.parsedCmd = new DefaultCallbackHandler();
        resetArgs(line);
        if (parsedCmd.getFormat() == OperationFormat.INSTANCE) {
            final ModelNode request = this.parsedCmd.toOperationRequest(this);
            return new HandledRequest(request, null);
        }
        final CommandHandler handler = cmdRegistry.getCommandHandler(parsedCmd.getOperationName());
        if (handler != null) {
            if (batchMode) {
                if (!handler.isBatchMode(this)) {
                    throw new OperationFormatException("The command is not allowed in a batch.");
                }
                Batch batch = getBatchManager().getActiveBatch();
                return ((OperationCommand) handler).buildHandledRequest(this, batch.getAttachments());
            } else if (!(handler instanceof OperationCommand)) {
                throw new OperationFormatException("The command does not translate to an operation request.");
            }
            return new HandledRequest(((OperationCommand) handler).buildRequest(this), null);
        } else {
            return buildAeshCommandRequest(parsedCmd, batchMode);
        }
    } finally {
        clear(Scope.REQUEST);
        this.parsedCmd = originalParsedArguments;
        this.cmdLine = originalCmdLine;
    }
}
Also used : OperationCommand(org.jboss.as.cli.OperationCommand) OperationFormatException(org.jboss.as.cli.operation.OperationFormatException) Batch(org.jboss.as.cli.batch.Batch) HandledRequest(org.jboss.as.cli.OperationCommand.HandledRequest) DefaultCallbackHandler(org.jboss.as.cli.operation.impl.DefaultCallbackHandler) CommandHandler(org.jboss.as.cli.CommandHandler) CommandCommandHandler(org.jboss.as.cli.handlers.CommandCommandHandler) ModelNode(org.jboss.dmr.ModelNode)

Example 5 with CommandHandler

use of org.jboss.as.cli.CommandHandler in project wildfly-core by wildfly.

the class CommandContextImpl method handle.

@Override
public void handle(String line) throws CommandLineException {
    if (line.isEmpty() || line.charAt(0) == '#') {
        // ignore comments
        return;
    }
    int i = line.length() - 1;
    while (i > 0 && line.charAt(i) <= ' ') {
        if (line.charAt(--i) == '\\') {
            break;
        }
    }
    String echoLine = line;
    if (line.charAt(i) == '\\') {
        if (lineBuffer == null) {
            lineBuffer = new StringBuilder();
            origLineBuffer = new StringBuilder();
        }
        lineBuffer.append(line, 0, i);
        lineBuffer.append(' ');
        origLineBuffer.append(line, 0, i);
        origLineBuffer.append('\n');
        return;
    } else if (lineBuffer != null) {
        lineBuffer.append(line);
        origLineBuffer.append(line);
        echoLine = origLineBuffer.toString();
        line = lineBuffer.toString();
        lineBuffer = null;
    }
    if (echoCommand && !INTERACT && redirection == null) {
        printLine(getPrompt() + echoLine);
    }
    if (!INTERACT) {
        // special case for builtins and pre-processing.
        if (console == null) {
            initBasicConsole(null, false);
        }
        line = console.handleBuiltins(line);
        if (line == null) {
            return;
        }
    }
    resetArgs(line);
    /**
     * All kind of command can be handled by handleCommand. In order to stay
     * on the safe side (another parsing is applied on top of operations and
     * legacy commands by aesh, we only use the wrapped approach if an
     * operator is present. This could be simplified when we have confidence
     * that aesh parsing doesn't fail for complex corner cases.
     */
    try {
        if (redirection != null) {
            redirection.target.handle(this);
        } else if (parsedCmd.hasOperator()) {
            handleCommand(parsedCmd);
        } else if (parsedCmd.getFormat() == OperationFormat.INSTANCE) {
            handleOperation(parsedCmd);
        } else {
            final String cmdName = parsedCmd.getOperationName();
            CommandHandler handler = cmdRegistry.getCommandHandler(cmdName.toLowerCase());
            if (handler != null) {
                handleLegacyCommand(line, handler, false);
            } else {
                handleCommand(parsedCmd);
            }
        }
    } catch (CommandLineException e) {
        throw e;
    } catch (Throwable t) {
        if (log.isDebugEnabled()) {
            log.debugf(t, "Failed to handle '%s'", line);
        }
        throw new CommandLineException("Failed to handle '" + line + "'", t);
    } finally {
        // so that getArgumentsString() doesn't return this line
        // during the tab-completion of the next command
        cmdLine = null;
        invocationContext = null;
        clear(Scope.REQUEST);
    }
}
Also used : CommandHandler(org.jboss.as.cli.CommandHandler) CommandCommandHandler(org.jboss.as.cli.handlers.CommandCommandHandler) CommandLineException(org.jboss.as.cli.CommandLineException)

Aggregations

CommandHandler (org.jboss.as.cli.CommandHandler)6 CommandLineException (org.jboss.as.cli.CommandLineException)4 CommandFormatException (org.jboss.as.cli.CommandFormatException)3 CommandCommandHandler (org.jboss.as.cli.handlers.CommandCommandHandler)3 ModelNode (org.jboss.dmr.ModelNode)3 IOException (java.io.IOException)2 CommandNotFoundException (org.aesh.command.CommandNotFoundException)2 CommandContext (org.jboss.as.cli.CommandContext)2 Batch (org.jboss.as.cli.batch.Batch)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 AccessDeniedException (java.nio.file.AccessDeniedException)1 ArrayList (java.util.ArrayList)1 Collection (java.util.Collection)1 List (java.util.List)1 Future (java.util.concurrent.Future)1 TimeUnit (java.util.concurrent.TimeUnit)1 TimeoutException (java.util.concurrent.TimeoutException)1 Inject (javax.inject.Inject)1 CommandException (org.aesh.command.CommandException)1 CommandLineParser (org.aesh.command.impl.parser.CommandLineParser)1