Search in sources :

Example 1 with BatchedCommand

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

the class BatchEditLineHandler method doHandle.

/* (non-Javadoc)
     * @see org.jboss.as.cli.handlers.CommandHandlerWithHelp#doHandle(org.jboss.as.cli.CommandContext)
     */
@Override
protected void doHandle(CommandContext ctx) throws CommandFormatException {
    BatchManager batchManager = ctx.getBatchManager();
    if (!batchManager.isBatchActive()) {
        throw new CommandFormatException("No active batch.");
    }
    Batch batch = batchManager.getActiveBatch();
    final int batchSize = batch.size();
    if (batchSize == 0) {
        throw new CommandFormatException("The batch is empty.");
    }
    String argsStr = ctx.getArgumentsString();
    if (argsStr == null) {
        throw new CommandFormatException("Missing line number.");
    }
    int i = 0;
    while (i < argsStr.length()) {
        if (Character.isWhitespace(argsStr.charAt(i))) {
            break;
        }
        ++i;
    }
    if (i == argsStr.length()) {
        throw new CommandFormatException("Missing the new command line after the index.");
    }
    String intStr = argsStr.substring(0, i);
    int lineNumber;
    try {
        lineNumber = Integer.parseInt(intStr);
    } catch (NumberFormatException e) {
        throw new CommandFormatException("Failed to parse line number '" + intStr + "': " + e.getLocalizedMessage());
    }
    if (lineNumber < 1 || lineNumber > batchSize) {
        throw new CommandFormatException(lineNumber + " isn't in range [1.." + batchSize + "].");
    }
    String editedLine = argsStr.substring(i).trim();
    if (editedLine.length() == 0) {
        throw new CommandFormatException("Missing the new command line after the index.");
    }
    if (editedLine.charAt(0) == '"') {
        if (editedLine.length() > 1 && editedLine.charAt(editedLine.length() - 1) == '"') {
            editedLine = editedLine.substring(1, editedLine.length() - 1);
        }
    }
    BatchedCommand newCmd = ctx.toBatchedCommand(editedLine);
    batch.set(lineNumber - 1, newCmd);
    ctx.printLine("#" + lineNumber + " " + newCmd.getCommand());
}
Also used : Batch(org.jboss.as.cli.batch.Batch) CommandFormatException(org.jboss.as.cli.CommandFormatException) BatchManager(org.jboss.as.cli.batch.BatchManager) BatchedCommand(org.jboss.as.cli.batch.BatchedCommand)

Example 2 with BatchedCommand

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

the class BatchListHandler method doHandle.

/* (non-Javadoc)
     * @see org.jboss.as.cli.handlers.CommandHandlerWithHelp#doHandle(org.jboss.as.cli.CommandContext)
     */
@Override
protected void doHandle(CommandContext ctx) throws CommandFormatException {
    BatchManager batchManager = ctx.getBatchManager();
    if (!batchManager.isBatchActive()) {
        throw new CommandFormatException("No active batch.");
    }
    Batch activeBatch = batchManager.getActiveBatch();
    List<BatchedCommand> commands = activeBatch.getCommands();
    if (!commands.isEmpty()) {
        for (int i = 0; i < commands.size(); ++i) {
            BatchedCommand cmd = commands.get(i);
            ctx.printLine("#" + (i + 1) + ' ' + cmd.getCommand());
        }
    } else {
        ctx.printLine("The batch is empty.");
    }
}
Also used : Batch(org.jboss.as.cli.batch.Batch) CommandFormatException(org.jboss.as.cli.CommandFormatException) BatchManager(org.jboss.as.cli.batch.BatchManager) BatchedCommand(org.jboss.as.cli.batch.BatchedCommand)

Example 3 with BatchedCommand

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

the class BatchRunHandler 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 boolean v = verbose.isPresent(ctx.getParsedCommandLine());
    final OperationResponse response;
    boolean failed = false;
    boolean hasFile = file.getValue(ctx.getParsedCommandLine()) != null;
    try {
        final ModelNode request = buildRequest(ctx);
        OperationBuilder builder = new OperationBuilder(request, true);
        for (String path : getAttachments(ctx).getAttachedFiles()) {
            builder.addFileAsAttachment(new File(path));
        }
        final ModelControllerClient client = ctx.getModelControllerClient();
        try {
            response = client.executeOperation(builder.build(), OperationMessageHandler.DISCARD);
        } catch (Exception e) {
            throw new CommandFormatException("Failed to perform operation: " + e.getLocalizedMessage());
        }
        if (!Util.isSuccess(response.getResponseNode())) {
            String msg = formatBatchError(ctx, response.getResponseNode());
            if (msg == null) {
                msg = Util.getFailureDescription(response.getResponseNode());
            }
            throw new CommandFormatException(msg);
        }
        ModelNode steps = response.getResponseNode().get(Util.RESULT);
        if (steps.isDefined()) {
            // Dispatch to non null response handlers.
            final Batch batch = ctx.getBatchManager().getActiveBatch();
            int i = 1;
            for (BatchedCommand cmd : batch.getCommands()) {
                ModelNode step = steps.get("step-" + i);
                if (step.isDefined()) {
                    if (cmd.getResponseHandler() != null) {
                        cmd.getResponseHandler().handleResponse(step, response);
                    }
                    i += 1;
                }
            }
        }
    } catch (CommandLineException e) {
        failed = true;
        if (hasFile) {
            throw new CommandLineException("The batch failed with the following error: ", e);
        } else {
            throw new CommandLineException("The batch failed with the following error " + "(you are remaining in the batch editing mode to have a chance to correct the error)", e);
        }
    } finally {
        // With a file, the batch is discarded, whatever the result.
        if (hasFile) {
            ctx.getBatchManager().discardActiveBatch();
        } else if (!failed) {
            if (ctx.getBatchManager().isBatchActive()) {
                ctx.getBatchManager().discardActiveBatch();
            }
        }
    }
    if (v) {
        ctx.printDMR(response.getResponseNode());
    } else {
        ctx.printLine("The batch executed successfully");
        super.handleResponse(ctx, response.getResponseNode(), true);
    }
}
Also used : OperationBuilder(org.jboss.as.controller.client.OperationBuilder) IOException(java.io.IOException) CommandLineException(org.jboss.as.cli.CommandLineException) CommandFormatException(org.jboss.as.cli.CommandFormatException) CommandLineException(org.jboss.as.cli.CommandLineException) ModelControllerClient(org.jboss.as.controller.client.ModelControllerClient) Batch(org.jboss.as.cli.batch.Batch) CommandFormatException(org.jboss.as.cli.CommandFormatException) OperationResponse(org.jboss.as.controller.client.OperationResponse) ModelNode(org.jboss.dmr.ModelNode) File(java.io.File) BatchedCommand(org.jboss.as.cli.batch.BatchedCommand)

Example 4 with BatchedCommand

use of org.jboss.as.cli.batch.BatchedCommand 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 5 with BatchedCommand

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

the class CommandContextImpl method handleLegacyCommand.

private void handleLegacyCommand(String opLine, CommandHandler handler, boolean direct) throws CommandLineException {
    if (isBatchMode() && handler.isBatchMode(this)) {
        if (!(handler instanceof OperationCommand)) {
            throw new CommandLineException("The command is not allowed in a batch.");
        } else {
            try {
                Batch batch = getBatchManager().getActiveBatch();
                HandledRequest request = ((OperationCommand) handler).buildHandledRequest(this, batch.getAttachments());
                BatchedCommand batchedCmd = new DefaultBatchedCommand(this, opLine, request.getRequest(), request.getResponseHandler());
                batch.add(batchedCmd);
            } catch (CommandFormatException e) {
                throw new CommandFormatException("Failed to add to batch '" + opLine + "'", e);
            }
        }
    } else if (direct) {
        handler.handle(CommandContextImpl.this);
    } else {
        execute(() -> {
            executor.execute(handler, timeout, TimeUnit.SECONDS);
            return null;
        }, opLine);
    }
}
Also used : OperationCommand(org.jboss.as.cli.OperationCommand) Batch(org.jboss.as.cli.batch.Batch) CommandFormatException(org.jboss.as.cli.CommandFormatException) HandledRequest(org.jboss.as.cli.OperationCommand.HandledRequest) DefaultBatchedCommand(org.jboss.as.cli.batch.impl.DefaultBatchedCommand) CommandLineException(org.jboss.as.cli.CommandLineException) DefaultBatchedCommand(org.jboss.as.cli.batch.impl.DefaultBatchedCommand) BatchedCommand(org.jboss.as.cli.batch.BatchedCommand)

Aggregations

BatchedCommand (org.jboss.as.cli.batch.BatchedCommand)9 CommandFormatException (org.jboss.as.cli.CommandFormatException)8 Batch (org.jboss.as.cli.batch.Batch)7 CommandLineException (org.jboss.as.cli.CommandLineException)5 IOException (java.io.IOException)4 BatchManager (org.jboss.as.cli.batch.BatchManager)4 ModelNode (org.jboss.dmr.ModelNode)4 File (java.io.File)3 BufferedReader (java.io.BufferedReader)2 FileReader (java.io.FileReader)2 DefaultBatchedCommand (org.jboss.as.cli.batch.impl.DefaultBatchedCommand)2 OperationResponse (org.jboss.as.controller.client.OperationResponse)2 AccessDeniedException (java.nio.file.AccessDeniedException)1 ArrayList (java.util.ArrayList)1 CommandNotFoundException (org.aesh.command.CommandNotFoundException)1 CommandLineParserException (org.aesh.command.parser.CommandLineParserException)1 OptionValidatorException (org.aesh.command.validator.OptionValidatorException)1 CommandContext (org.jboss.as.cli.CommandContext)1 CommandHandler (org.jboss.as.cli.CommandHandler)1 OperationCommand (org.jboss.as.cli.OperationCommand)1