Search in sources :

Example 11 with ParsedCommandLine

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

the class CommandLineArgumentsTestCase method testOutputTarget.

@Test
public void testOutputTarget() throws Exception {
    ParsedCommandLine args = parse("cmd --name=value value1 --name1 > output.target");
    assertTrue(args.hasProperties());
    assertTrue(args.hasProperty("--name"));
    assertEquals("value", args.getPropertyValue("--name"));
    assertTrue(args.hasProperty("--name1"));
    assertTrue(args.getPropertyValue("--name1").equals("true"));
    List<String> otherArgs = args.getOtherProperties();
    assertEquals(1, otherArgs.size());
    assertEquals("value1", otherArgs.get(0));
    assertTrue("No operator", args.hasOperator());
}
Also used : ParsedCommandLine(org.jboss.as.cli.operation.ParsedCommandLine) Test(org.junit.Test)

Example 12 with ParsedCommandLine

use of org.jboss.as.cli.operation.ParsedCommandLine 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 13 with ParsedCommandLine

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

the class DeployHandler method buildRequestWithoutHeaders.

@Override
public ModelNode buildRequestWithoutHeaders(CommandContext ctx) throws CommandFormatException {
    ParsedCommandLine args = ctx.getParsedCommandLine();
    boolean l = this.l.isPresent(args);
    if (!args.hasProperties() || l) {
        throw new CommandFormatException("No Option");
    }
    final boolean unmanaged = this.unmanaged.isPresent(args);
    final String path = this.path.getValue(args);
    final String name = this.name.getValue(args);
    final String rtName = this.rtName.getValue(args);
    final String url = this.url.getValue(args);
    final boolean force = this.force.isPresent(args);
    final boolean disabled = this.disabled.isPresent(args);
    final boolean enabled = this.enabled.isPresent(args);
    final String serverGroups = this.serverGroups.getValue(args);
    final boolean allServerGroups = this.allServerGroups.isPresent(args);
    final ModelNode headersNode = headers.toModelNode(ctx);
    if (headersNode != null && headersNode.getType() != ModelType.OBJECT) {
        throw new CommandFormatException("--headers option has wrong value '" + headersNode + "'");
    }
    if (path == null && url == null) {
        if (name == null) {
            throw new CommandFormatException("Filesystem path, --url or --name is " + " required.");
        }
        if (name.equals(ALL)) {
            if (force || disabled) {
                throw new CommandFormatException("force and disabled can't be used " + "when deploying all disabled deployments");
            }
            EnableAllCommand command = new EnableAllCommand(ctx);
            command.allServerGroups = allServerGroups;
            command.headers = headersNode;
            command.serverGroups = serverGroups;
            return command.buildRequest(ctx);
        } else {
            EnableCommand command = new EnableCommand(ctx);
            command.allServerGroups = allServerGroups;
            command.headers = headersNode;
            command.serverGroups = serverGroups;
            command.name = name;
            return command.buildRequest(ctx);
        }
    }
    if (path != null) {
        if (url != null) {
            throw new CommandFormatException("Filesystem path and --url can't be used together.");
        }
        File f = new File(path);
        DMRCommand c;
        if (DeployArchiveCommand.isCliArchive(f)) {
            DeployArchiveCommand command = new DeployArchiveCommand(ctx);
            command.file = f;
            command.script = this.script.getValue(args);
            c = command;
        } else {
            DeployFileCommand command = new DeployFileCommand(ctx, REPLACE_OPTION);
            command.allServerGroups = allServerGroups;
            command.disabled = disabled;
            command.enabled = enabled;
            command.file = f;
            command.replace = force;
            command.headers = headersNode;
            command.name = name;
            command.runtimeName = rtName;
            command.serverGroups = serverGroups;
            command.unmanaged = unmanaged;
            c = command;
        }
        return c.buildRequest(ctx);
    }
    if (url != null) {
        if (path != null) {
            throw new CommandFormatException("Filesystem path and --url can't be " + "used together.");
        }
        DeployUrlCommand command = new DeployUrlCommand(ctx, REPLACE_OPTION);
        command.allServerGroups = allServerGroups;
        command.disabled = disabled;
        command.enabled = enabled;
        try {
            command.deploymentUrl = new URL(url);
        } catch (MalformedURLException ex) {
            throw new CommandFormatException(ex);
        }
        command.replace = force;
        command.headers = headersNode;
        command.runtimeName = rtName;
        command.serverGroups = serverGroups;
        return command.buildRequest(ctx);
    }
    throw new CommandFormatException("Invalid Options.");
}
Also used : MalformedURLException(java.net.MalformedURLException) URL(java.net.URL) DMRCommand(org.wildfly.core.cli.command.DMRCommand) DeployUrlCommand(org.jboss.as.cli.impl.aesh.cmd.deployment.DeployUrlCommand) EnableAllCommand(org.jboss.as.cli.impl.aesh.cmd.deployment.EnableAllCommand) CommandFormatException(org.jboss.as.cli.CommandFormatException) EnableCommand(org.jboss.as.cli.impl.aesh.cmd.deployment.EnableCommand) DeployFileCommand(org.jboss.as.cli.impl.aesh.cmd.deployment.DeployFileCommand) ParsedCommandLine(org.jboss.as.cli.operation.ParsedCommandLine) DeployArchiveCommand(org.jboss.as.cli.impl.aesh.cmd.deployment.DeployArchiveCommand) ModelNode(org.jboss.dmr.ModelNode) File(java.io.File)

Example 14 with ParsedCommandLine

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

the class EmbedServerHandler method doHandle.

@Override
protected void doHandle(CommandContext ctx) throws CommandLineException {
    final ParsedCommandLine parsedCmd = ctx.getParsedCommandLine();
    final File jbossHome = getJBossHome(parsedCmd);
    // set up the expected properties
    final String baseDir = WildFlySecurityManager.getPropertyPrivileged(JBOSS_SERVER_BASE_DIR, jbossHome + File.separator + "standalone");
    String xml = serverConfig.getValue(parsedCmd);
    if (xml == null) {
        xml = dashC.getValue(parsedCmd);
    }
    boolean adminOnlySetting = true;
    String adminProp = adminOnly.getValue(parsedCmd);
    if (adminProp != null && "false".equalsIgnoreCase(adminProp)) {
        adminOnlySetting = false;
    }
    boolean startEmpty = emptyConfig.isPresent(parsedCmd);
    boolean removeConfig = startEmpty && removeExisting.isPresent(parsedCmd);
    final List<String> args = parsedCmd.getOtherProperties();
    if (!args.isEmpty()) {
        if (args.size() != 1) {
            throw new CommandFormatException("The command accepts 0 unnamed argument(s) but received: " + args);
        }
    }
    Long bootTimeout = null;
    String timeoutString = timeout.getValue(parsedCmd);
    if (timeout.isPresent(parsedCmd) && (timeoutString == null || timeoutString.isEmpty())) {
        throw new CommandFormatException("The --timeout parameter requires a value.");
    }
    if (timeoutString != null) {
        bootTimeout = TimeUnit.SECONDS.toNanos(Long.parseLong(timeoutString));
    }
    String stdOutString = stdOutHandling.getValue(parsedCmd);
    if (stdOutHandling.isPresent(parsedCmd)) {
        if (stdOutString == null || stdOutString.isEmpty()) {
            throw new CommandFormatException("The --std-out parameter requires a value { echo, discard }.");
        }
        if (!(stdOutString.equals(ECHO) || stdOutString.equals(DISCARD_STDOUT))) {
            throw new CommandFormatException("The --std-out parameter should be one of { echo, discard }.");
        }
    }
    final EnvironmentRestorer restorer = new EnvironmentRestorer(JBOSS_SERVER_LOG_DIR);
    boolean ok = false;
    ThreadLocalContextSelector contextSelector = null;
    try {
        Contexts defaultContexts = restorer.getDefaultContexts();
        StdioContext discardStdoutContext = null;
        if (!ECHO.equalsIgnoreCase(stdOutHandling.getValue(parsedCmd))) {
            PrintStream nullStream = new UncloseablePrintStream(NullOutputStream.getInstance());
            StdioContext currentContext = defaultContexts.getStdioContext();
            discardStdoutContext = StdioContext.create(currentContext.getIn(), nullStream, currentContext.getErr());
        }
        // Configure and get the log context, default to baseDir
        String serverLogDir = WildFlySecurityManager.getPropertyPrivileged(JBOSS_SERVER_LOG_DIR, null);
        if (serverLogDir == null) {
            serverLogDir = baseDir + File.separator + "log";
            WildFlySecurityManager.setPropertyPrivileged(JBOSS_SERVER_LOG_DIR, serverLogDir);
        }
        final String serverCfgDir = WildFlySecurityManager.getPropertyPrivileged(JBOSS_SERVER_CONFIG_DIR, baseDir + File.separator + "configuration");
        final LogContext embeddedLogContext = EmbeddedLogContext.configureLogContext(new File(serverLogDir), new File(serverCfgDir), "server.log", ctx);
        Contexts localContexts = new Contexts(embeddedLogContext, discardStdoutContext);
        contextSelector = new ThreadLocalContextSelector(localContexts, defaultContexts);
        contextSelector.pushLocal();
        StdioContext.setStdioContextSelector(contextSelector);
        LogContext.setLogContextSelector(contextSelector);
        List<String> cmdsList = new ArrayList<>();
        if (xml == null && (parsedCmd.hasProperty("--server-config") || parsedCmd.hasProperty("-c"))) {
            throw new CommandFormatException("The --server-config (or -c) parameter requires a value.");
        }
        if (xml != null) {
            xml = xml.trim();
            if (xml.length() == 0) {
                throw new CommandFormatException("The --server-config parameter requires a value.");
            }
            if (!xml.endsWith(".xml")) {
                throw new CommandFormatException("The --server-config filename must end with .xml.");
            }
            cmdsList.add("--server-config=" + xml);
        }
        // if --empty-config is present but the config file already exists we error unless --remove-config has also been used
        if (startEmpty && !removeConfig) {
            String configFileName = xml == null ? "standalone.xml" : xml;
            File configFile = new File(serverCfgDir + File.separator + configFileName);
            if (configFile.exists()) {
                throw new CommandFormatException("The configuration file " + configFileName + " already exists, please use --remove-existing if you wish to overwrite.");
            }
        }
        if (adminOnlySetting) {
            cmdsList.add("--admin-only");
        }
        if (startEmpty) {
            cmdsList.add("--internal-empty-config");
            if (removeConfig) {
                cmdsList.add("--internal-remove-config");
            }
        }
        String[] cmds = cmdsList.toArray(new String[cmdsList.size()]);
        final Configuration.Builder configBuilder;
        if (this.jbossHome == null) {
            // Modular environment, note that the jbossHome here is resolved from the JBOSS_HOME environment
            // variable and should never be null according to the getJBossHome() method.
            configBuilder = Configuration.Builder.of(jbossHome).setModuleLoader(ModuleLoader.forClass(getClass())).setCommandArguments(cmds);
        } else {
            configBuilder = Configuration.Builder.of(jbossHome.getAbsoluteFile()).addSystemPackages(EmbeddedControllerHandlerRegistrar.EXTENDED_SYSTEM_PKGS).setCommandArguments(cmds);
        }
        // Disables the logging subsystem from registering an embedded log context if the subsystem is present
        WildFlySecurityManager.setPropertyPrivileged("org.wildfly.logging.embedded", "false");
        final EmbeddedManagedProcess server = EmbeddedProcessFactory.createStandaloneServer(configBuilder.build());
        server.start();
        serverReference.set(new EmbeddedProcessLaunch(server, restorer, false));
        ModelControllerClient mcc = new ThreadContextsModelControllerClient(server.getModelControllerClient(), contextSelector);
        if (bootTimeout == null || bootTimeout > 0) {
            // Poll for server state. Alternative would be to get ControlledProcessStateService
            // and do reflection stuff to read the state and register for change notifications
            long expired = bootTimeout == null ? Long.MAX_VALUE : System.nanoTime() + bootTimeout;
            String status = "starting";
            final ModelNode getStateOp = new ModelNode();
            getStateOp.get(ClientConstants.OP).set(ClientConstants.READ_ATTRIBUTE_OPERATION);
            getStateOp.get(ClientConstants.NAME).set("server-state");
            do {
                try {
                    final ModelNode response = mcc.execute(getStateOp);
                    if (Util.isSuccess(response)) {
                        status = response.get(ClientConstants.RESULT).asString();
                    }
                } catch (Exception e) {
                // ignore and try again
                }
                if ("starting".equals(status)) {
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        throw new CommandLineException("Interrupted while waiting for embedded server to start");
                    }
                } else {
                    break;
                }
            } while (System.nanoTime() < expired);
            if ("starting".equals(status)) {
                // we'll assume the loop didn't run for decades
                assert bootTimeout != null;
                // Stop server and restore environment
                StopEmbeddedServerHandler.cleanup(serverReference);
                throw new CommandLineException("Embedded server did not exit 'starting' status within " + TimeUnit.NANOSECONDS.toSeconds(bootTimeout) + " seconds");
            }
        }
        // Expose the client to the rest of the CLI last so nothing can be done with
        // it until we're ready
        ctx.bindClient(mcc);
        // Stop the server on any disconnect event
        ctx.addEventListener(new CliEventListener() {

            @Override
            public void cliEvent(CliEvent event, CommandContext ctx) {
                if (event == CliEvent.DISCONNECTED) {
                    StopEmbeddedServerHandler.cleanup(serverReference);
                }
            }
        });
        ok = true;
    } catch (RuntimeException | EmbeddedProcessStartException e) {
        throw new CommandLineException("Cannot start embedded server", e);
    } finally {
        if (!ok) {
            ctx.disconnectController();
            restorer.restoreEnvironment();
        } else if (contextSelector != null) {
            contextSelector.restore(null);
        }
    }
}
Also used : EmbeddedProcessStartException(org.wildfly.core.embedded.EmbeddedProcessStartException) Configuration(org.wildfly.core.embedded.Configuration) CommandContext(org.jboss.as.cli.CommandContext) CliEventListener(org.jboss.as.cli.CliEventListener) ArrayList(java.util.ArrayList) EmbeddedManagedProcess(org.wildfly.core.embedded.EmbeddedManagedProcess) StdioContext(org.jboss.stdio.StdioContext) CommandLineException(org.jboss.as.cli.CommandLineException) ModelControllerClient(org.jboss.as.controller.client.ModelControllerClient) PrintStream(java.io.PrintStream) LogContext(org.jboss.logmanager.LogContext) EmbeddedProcessStartException(org.wildfly.core.embedded.EmbeddedProcessStartException) CommandLineException(org.jboss.as.cli.CommandLineException) CommandFormatException(org.jboss.as.cli.CommandFormatException) CommandFormatException(org.jboss.as.cli.CommandFormatException) ParsedCommandLine(org.jboss.as.cli.operation.ParsedCommandLine) CliEvent(org.jboss.as.cli.CliEvent) ModelNode(org.jboss.dmr.ModelNode) File(java.io.File)

Example 15 with ParsedCommandLine

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

the class DefaultOperationCandidatesProvider method getPropertiesFromPropList.

protected List<CommandArgument> getPropertiesFromPropList(List<Property> propList, CommandContext ctx, String operationName, OperationRequestAddress address) {
    final Map<String, CommandLineCompleterFactory> globalOpProps = globalOpPropCompleters.get(operationName);
    List<CommandArgument> result = new ArrayList<CommandArgument>(propList.size());
    String radical = null;
    if (ctx.getParsedCommandLine().getLastParsedPropertyValue() == null) {
        radical = ctx.getParsedCommandLine().getLastParsedPropertyName();
        // Check if the property is completely specified and is negated
        if (ctx.getParsedCommandLine().isLastPropertyNegated()) {
            for (Property prop : propList) {
                if (radical.equals(prop.getName())) {
                    radical = null;
                    break;
                }
            }
        }
    }
    final PropertyVisibility visibility = new PropertyVisibility(propList, ctx.getParsedCommandLine().getPropertyNames(), radical);
    for (final Property prop : propList) {
        final CommandLineCompleter completer = getCompleter(globalOpProps, prop, ctx, operationName, address);
        result.add(new CommandArgument() {

            final String argName = prop.getName();

            @Override
            public String getFullName() {
                return argName;
            }

            @Override
            public String getDecoratedName() {
                return visibility.getName(prop);
            }

            @Override
            public String getShortName() {
                return null;
            }

            @Override
            public int getIndex() {
                return -1;
            }

            @Override
            public boolean isPresent(ParsedCommandLine args) throws CommandFormatException {
                return args.hasProperty(argName);
            }

            @Override
            public boolean canAppearNext(CommandContext ctx) throws CommandFormatException {
                return visibility.canAppearNext(prop);
            }

            @Override
            public String getValue(ParsedCommandLine args) throws CommandFormatException {
                return args.getPropertyValue(argName);
            }

            @Override
            public String getValue(ParsedCommandLine args, boolean required) throws CommandFormatException {
                if (!isPresent(args)) {
                    throw new CommandFormatException("Property '" + argName + "' is missing required value.");
                }
                return args.getPropertyValue(argName);
            }

            @Override
            public boolean isValueComplete(ParsedCommandLine args) throws CommandFormatException {
                if (!isPresent(args)) {
                    return false;
                }
                if (argName.equals(args.getLastParsedPropertyName())) {
                    return false;
                }
                return true;
            }

            @Override
            public boolean isValueRequired() {
                boolean required = true;
                ModelNode mn = prop.getValue().get("type");
                if (mn != null) {
                    // No value required for boolean
                    required = mn.asType() != ModelType.BOOLEAN;
                }
                return required;
            }

            @Override
            public CommandLineCompleter getValueCompleter() {
                return completer;
            }
        });
    }
    return result;
}
Also used : CommandContext(org.jboss.as.cli.CommandContext) CommandArgument(org.jboss.as.cli.CommandArgument) ArrayList(java.util.ArrayList) CommandLineCompleter(org.jboss.as.cli.CommandLineCompleter) CommandFormatException(org.jboss.as.cli.CommandFormatException) ParsedCommandLine(org.jboss.as.cli.operation.ParsedCommandLine) ModelNode(org.jboss.dmr.ModelNode) Property(org.jboss.dmr.Property)

Aggregations

ParsedCommandLine (org.jboss.as.cli.operation.ParsedCommandLine)95 Test (org.junit.Test)42 CommandFormatException (org.jboss.as.cli.CommandFormatException)38 ModelNode (org.jboss.dmr.ModelNode)26 CommandLineException (org.jboss.as.cli.CommandLineException)14 OperationRequestAddress (org.jboss.as.cli.operation.OperationRequestAddress)14 File (java.io.File)12 IOException (java.io.IOException)10 ArrayList (java.util.ArrayList)9 DefaultOperationRequestAddress (org.jboss.as.cli.operation.impl.DefaultOperationRequestAddress)8 ModelControllerClient (org.jboss.as.controller.client.ModelControllerClient)8 CommandArgument (org.jboss.as.cli.CommandArgument)4 CommandContext (org.jboss.as.cli.CommandContext)4 OperationFormatException (org.jboss.as.cli.operation.OperationFormatException)4 ZipException (java.util.zip.ZipException)3 XMLStreamException (javax.xml.stream.XMLStreamException)3 CommandException (org.aesh.command.CommandException)3 BatchManager (org.jboss.as.cli.batch.BatchManager)3 CommandLineParser (org.jboss.as.cli.operation.CommandLineParser)3 DefaultCallbackHandler (org.jboss.as.cli.operation.impl.DefaultCallbackHandler)3