Search in sources :

Example 1 with Command

use of com.bluenimble.platform.cli.command.Command in project serverless by bluenimble.

the class AbstractTool method startup.

@Override
public void startup(String[] args) throws ToolStartupException {
    for (Command command : getCommands()) {
        command.onStartup(this);
    }
    startTime = new Date();
    writeln(Lang.BLANK);
    printer.textLn(0, getDescription(), FColor.CYAN.name(), null);
    writeln(Lang.BLANK);
    writeln(Lang.BLANK);
    printer.textLn(0, startTime.toString(), FColor.YELLOW.name(), null);
    try {
        prompt();
        onReady();
        prompt();
    } catch (Throwable th) {
    // IGNORE
    }
    addShutdownHook();
    // signle run
    if (args != null && args.length > 0) {
        for (int i = 0; i < args.length; i++) {
            try {
                processCommand(args[i]);
            } catch (IOException e) {
                throw new ToolStartupException(e);
            }
        }
        try {
            processCommand("quit");
        } catch (IOException e) {
            throw new ToolStartupException(e);
        }
        return;
    }
}
Also used : Command(com.bluenimble.platform.cli.command.Command) IOException(java.io.IOException) ToolStartupException(com.bluenimble.platform.cli.ToolStartupException) Date(java.util.Date)

Example 2 with Command

use of com.bluenimble.platform.cli.command.Command in project serverless by bluenimble.

the class AbstractTool method processCommand.

@SuppressWarnings({ "unchecked" })
@Override
public int processCommand(String cmdLine) throws IOException {
    if (!isAllowed()) {
        writeln("not allowed to write commands.");
        return FAILURE;
    }
    if (cmdLine == null) {
        cmdLine = readLine();
    }
    if (cmdLine == null || cmdLine.trim().isEmpty()) {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
        }
        return SUCCESS;
    }
    String delimeter = getDelimeter();
    if (!delimeter.equals("\n")) {
        runingCommand.setCmdLine(runingCommand.getCmdLine() + "\n" + cmdLine);
        if (!cmdLine.endsWith(currentContext.getDelimiter())) {
            return UNTERMINATED;
        } else {
            cmdLine = runingCommand.getCmdLine();
            runingCommand.setCmdLine("");
        }
    }
    if (!delimeter.equals("\n")) {
        cmdLine = cmdLine.substring(0, cmdLine.length() - delimeter.length());
    }
    String commandName;
    String params;
    String out = null;
    cmdLine = cmdLine.trim();
    // multiple commands
    if (cmdLine.indexOf(COMMAND_CHAINING_TOKEN) > 0) {
        String[] aCommands = Lang.split(cmdLine, COMMAND_CHAINING_TOKEN, true);
        for (String cmd : aCommands) {
            processCommand(cmd);
        }
        return MULTIPLE;
    }
    final Map<String, Object> vars = (Map<String, Object>) getContext(Tool.ROOT_CTX).get(ToolContext.VARS);
    Calendar now = Calendar.getInstance();
    vars.put("day", now.get(Calendar.DAY_OF_MONTH));
    vars.put("month", now.get(Calendar.MONTH) + 1);
    vars.put("year", now.get(Calendar.YEAR));
    vars.put("hour", now.get(Calendar.HOUR));
    vars.put("min", now.get(Calendar.MINUTE));
    vars.put("sec", now.get(Calendar.SECOND));
    vars.put("uuid", Lang.UUID(20).toString());
    cmdLine = Lang.resolve(cmdLine, ExpStart, ExpEnd, new Lang.VariableResolver() {

        @Override
        public String resolve(String ns, String p) {
            Object o = vars.get(ns == null ? p : ns + Lang.DOT + p);
            if (o == null) {
                return null;
            }
            return String.valueOf(o);
        }
    });
    int indexOfSpace = cmdLine.indexOf(' ');
    if (indexOfSpace > 0) {
        commandName = cmdLine.substring(0, indexOfSpace);
        params = cmdLine.substring(indexOfSpace + 1);
        int outIndex = params.lastIndexOf(OUT_TOKEN);
        if (outIndex >= 0) {
            out = params.substring(outIndex + OUT_TOKEN.length());
            params = params.substring(0, outIndex);
        }
    } else {
        commandName = cmdLine;
        params = null;
    }
    if (Lang.isNullOrEmpty(out)) {
        out = null;
    } else {
        out = out.trim();
        if (out.startsWith(FilePrefix)) {
            vars.put(CMD_OUT, CMD_OUT_FILE);
        }
    }
    commandName = commandName.trim().toLowerCase();
    params = onCommand(commandName, params);
    Command cmd = getCommand(commandName);
    if (cmd == null) {
        String synCommandName = getCommandForSynonym(commandName);
        if (synCommandName != null) {
            cmd = getCommand(synCommandName);
        }
    }
    if (cmd != null) {
        if (!cmd.forContext(currentContext)) {
            printer.error("Command [" + commandName + "] not found in current context");
        } else {
            history.add(cmdLine);
            if (!cmd.isSingleton(this)) {
                try {
                    cmd = (Command) cmd.getClass().newInstance();
                } catch (Throwable th) {
                    if (isTestMode()) {
                        printer().content(th.getMessage(), Lang.toString(th));
                    }
                    onException(cmd, th);
                    return FAILURE;
                }
            }
            CommandResult result = null;
            try {
                final Map<String, CommandOption> options = commandParser.parse(cmd, params);
                if (options != null && !options.isEmpty()) {
                    Iterator<CommandOption> optIter = options.values().iterator();
                    while (optIter.hasNext()) {
                        CommandOption option = optIter.next();
                        if (option.isMasked() && option.acceptsArgs() != CommandOption.NO_ARG && option.getArgsCount() == 0) {
                            if (System.console() != null) {
                                char[] aArg = System.console().readPassword("\t- " + option.label() + "? ");
                                if ((aArg == null || aArg.length == 0)) {
                                    printer.error("'" + option.label() + "' requires at least one argument.");
                                }
                                option.addArg(new String(aArg));
                            } else {
                                printer.error("'" + option.label() + "' requires at least one argument.");
                                return FAILURE;
                            }
                        }
                    }
                }
                if (Lang.AMP.equals(out)) {
                    final Command tCmd = cmd;
                    new Thread() {

                        public void run() {
                            try {
                                tCmd.execute(AbstractTool.this, options);
                            } catch (CommandExecutionException th) {
                                if (isTestMode()) {
                                    th.printStackTrace(System.out);
                                }
                                try {
                                    onException(tCmd, th);
                                } catch (IOException ioex) {
                                // ignore
                                }
                            }
                        }
                    }.start();
                    printer.info("command is running in background");
                } else {
                    result = cmd.execute(this, options);
                }
            } catch (Throwable th) {
                if (isTestMode()) {
                    printer.content("Error", Lang.toString(Lang.getRootCause(th)));
                } else {
                    onException(cmd, th);
                }
                return FAILURE;
            }
            if (result != null) {
                if (result.getType() == CommandResult.OK) {
                    if (out != null && !Lang.AMP.equals(out) && result.getContent() != null) {
                        if (out.startsWith(FilePrefix)) {
                            out = out.substring(FilePrefix.length());
                            InputStream is = null;
                            if (result.getContent() instanceof InputStream) {
                                is = (InputStream) result.getContent();
                            } else {
                                Object content = result.getContent();
                                if (content instanceof YamlObject) {
                                    content = ((YamlObject) content).toJson();
                                }
                                is = new ByteArrayInputStream(content.toString().getBytes());
                            }
                            OutputStream os = null;
                            try {
                                os = new FileOutputStream(new File(out));
                                IOUtils.copy(is, os);
                            } catch (Exception e) {
                                onException(cmd, e);
                                return FAILURE;
                            } finally {
                                IOUtils.closeQuietly(os);
                                IOUtils.closeQuietly(is);
                                vars.remove(CMD_OUT);
                            }
                        } else {
                            Object content = result.getContent();
                            if (content instanceof YamlObject) {
                                content = ((YamlObject) content).toJson();
                            }
                            vars.put(out, content);
                        }
                    } else if (result.getContent() != null) {
                        if (result.getContent() instanceof JsonObject) {
                            printer().success(Lang.BLANK);
                            if (printer().isOn()) {
                                ((JsonObject) result.getContent()).write(new FriendlyJsonEmitter(this));
                                writeln(Lang.BLANK);
                            }
                        } else if (result.getContent() instanceof YamlObject) {
                            printer().success(Lang.BLANK);
                            if (printer().isOn()) {
                                YamlObject yaml = (YamlObject) result.getContent();
                                yaml.print(this, 4);
                                writeln(Lang.BLANK);
                            }
                        } else if (result.getContent() instanceof InputStream) {
                            System.out.println("result.getContent () instanceof InputStream");
                            OutputStream os = null;
                            try {
                                os = new FileOutputStream(new File(out));
                                IOUtils.copy(new ByteArrayInputStream(result.getContent().toString().getBytes()), os);
                            } catch (Exception e) {
                                onException(cmd, e);
                                return FAILURE;
                            } finally {
                                IOUtils.closeQuietly(os);
                            }
                        } else {
                            printer().success(String.valueOf(result.getContent()));
                            if (printer().isOn()) {
                                writeln(Lang.BLANK);
                            }
                        }
                    }
                } else if (result.getContent() != null) {
                    if (result.getContent() instanceof JsonObject) {
                        printer().error(Lang.BLANK);
                        ((JsonObject) result.getContent()).write(new FriendlyJsonEmitter(this));
                        writeln(Lang.BLANK);
                    } else if (result.getContent() instanceof YamlObject) {
                        printer().error(Lang.BLANK);
                        if (printer().isOn()) {
                            YamlObject yaml = (YamlObject) result.getContent();
                            yaml.print(this, 4);
                            writeln(Lang.BLANK);
                        }
                    } else {
                        printer.error(String.valueOf(result.getContent()));
                        writeln(Lang.BLANK);
                    }
                }
            }
        }
    } else {
        printer.error("command '" + commandName + "' not found. Type in 'help' to list all available commands");
    }
    return SUCCESS;
}
Also used : CommandOption(com.bluenimble.platform.cli.command.CommandOption) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) JsonObject(com.bluenimble.platform.json.JsonObject) FriendlyJsonEmitter(com.bluenimble.platform.cli.printing.impls.FriendlyJsonEmitter) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Calendar(java.util.Calendar) IOException(java.io.IOException) InstallI18nException(com.bluenimble.platform.cli.InstallI18nException) CommandExecutionException(com.bluenimble.platform.cli.command.CommandExecutionException) ToolStartupException(com.bluenimble.platform.cli.ToolStartupException) IOException(java.io.IOException) CommandResult(com.bluenimble.platform.cli.command.CommandResult) Command(com.bluenimble.platform.cli.command.Command) ByteArrayInputStream(java.io.ByteArrayInputStream) FileOutputStream(java.io.FileOutputStream) JsonObject(com.bluenimble.platform.json.JsonObject) CommandExecutionException(com.bluenimble.platform.cli.command.CommandExecutionException) Map(java.util.Map) File(java.io.File)

Example 3 with Command

use of com.bluenimble.platform.cli.command.Command in project serverless by bluenimble.

the class BlueNimble method loadScripts.

private void loadScripts(File scripts) {
    if (!scripts.exists() || !scripts.isDirectory()) {
        scripts.mkdir();
        return;
    }
    File[] folders = scripts.listFiles(new FileFilter() {

        @Override
        public boolean accept(File f) {
            return f.isDirectory();
        }
    });
    for (File fld : folders) {
        String ctx = fld.getName();
        if (GlobalContext.equals(ctx)) {
            ctx = Tool.ROOT_CTX;
        } else {
            ToolContext toolContext = getContext(ctx);
            if (toolContext == null) {
                addContext(new ToolContextImpl(ctx));
            }
        }
        File[] files = fld.listFiles(new FileFilter() {

            @Override
            public boolean accept(File f) {
                return f.isFile() && (f.getName().endsWith(MacroExt) || f.getName().endsWith(ScriptExt));
            }
        });
        String name = null;
        for (File f : files) {
            name = f.getName().substring(0, f.getName().lastIndexOf(Lang.DOT));
            try {
                Command c = null;
                if (f.getName().endsWith(MacroExt)) {
                    c = new MacroSourceCommand(ctx, name, f);
                } else if (f.getName().endsWith(ScriptExt)) {
                    c = new ScriptSourceCommand(ctx, name, f);
                }
                if (c != null) {
                    addCommand(c);
                }
            } catch (Exception e) {
                System.out.println("ERROR: Can't load command " + name + ". Cause: " + e.getMessage());
            }
        }
    }
}
Also used : ScriptSourceCommand(com.bluenimble.platform.icli.mgm.commands.mgm.ScriptSourceCommand) SecureCommand(com.bluenimble.platform.icli.mgm.commands.dev.SecureCommand) FeaturesCommand(com.bluenimble.platform.icli.mgm.commands.dev.FeaturesCommand) KeysCommand(com.bluenimble.platform.icli.mgm.commands.dev.KeysCommand) UseCommand(com.bluenimble.platform.icli.mgm.commands.dev.UseCommand) HttpCommand(com.bluenimble.platform.icli.mgm.commands.dev.HttpCommand) CreateCommand(com.bluenimble.platform.icli.mgm.commands.dev.CreateCommand) MacroSourceCommand(com.bluenimble.platform.icli.mgm.commands.mgm.MacroSourceCommand) ApiCommand(com.bluenimble.platform.icli.mgm.commands.dev.ApiCommand) WorkspaceCommand(com.bluenimble.platform.icli.mgm.commands.dev.WorkspaceCommand) Command(com.bluenimble.platform.cli.command.Command) ScriptSourceCommand(com.bluenimble.platform.icli.mgm.commands.mgm.ScriptSourceCommand) RemoteCommand(com.bluenimble.platform.icli.mgm.commands.mgm.RemoteCommand) LoadCommand(com.bluenimble.platform.icli.mgm.commands.dev.LoadCommand) ToolContextImpl(com.bluenimble.platform.cli.impls.ToolContextImpl) ToolContext(com.bluenimble.platform.cli.ToolContext) MacroSourceCommand(com.bluenimble.platform.icli.mgm.commands.mgm.MacroSourceCommand) FileFilter(java.io.FileFilter) File(java.io.File) InstallI18nException(com.bluenimble.platform.cli.InstallI18nException) ToolStartupException(com.bluenimble.platform.cli.ToolStartupException) IOException(java.io.IOException)

Example 4 with Command

use of com.bluenimble.platform.cli.command.Command in project serverless by bluenimble.

the class ManCommand method execute.

@Override
public CommandResult execute(Tool tool, Map<String, CommandOption> options) throws CommandExecutionException {
    CommandOption co = options.get(CommandOption.CMD_LINE);
    if (co == null || co.getArg(0) == null) {
        return new DefaultCommandResult(CommandResult.KO, "Specify a command");
    }
    String commandName = (String) co.getArg(0);
    commandName = commandName.trim();
    int indexOfSpace = commandName.indexOf(Lang.SPACE);
    if (indexOfSpace > 0) {
        commandName = commandName.substring(0, indexOfSpace);
    }
    Command command = tool.getCommand(commandName);
    String man = null;
    if (command == null) {
        man = tool.getManual(commandName);
        if (man == null) {
            return new DefaultCommandResult(CommandResult.KO, "Command not found in any context");
        }
    }
    if (command != null && !command.forContext(tool.currentContext())) {
        return new DefaultCommandResult(CommandResult.KO, "Command not accessible by the current context");
    }
    if (man == null) {
        man = command.manual();
        if (man == null || man.trim().isEmpty()) {
            man = command.describe();
        }
    }
    return new DefaultCommandResult(CommandResult.OK, man);
}
Also used : CommandOption(com.bluenimble.platform.cli.command.CommandOption) Command(com.bluenimble.platform.cli.command.Command)

Example 5 with Command

use of com.bluenimble.platform.cli.command.Command in project serverless by bluenimble.

the class PojoTool method _getCommand.

public Command _getCommand(String commandName, boolean checkSynonym) {
    if (commandName == null) {
        return null;
    }
    String commandKey = currentContext().getName() + Lang.SLASH + commandName.toLowerCase();
    Command command = commands.get(commandKey);
    if (command == null) {
        command = commands.get(ROOT_CTX + Lang.SLASH + commandName.toLowerCase());
    }
    if (command != null) {
        return command;
    }
    if (!checkSynonym) {
        return null;
    }
    String commandForSyn = getCommandForSynonym(commandKey);
    if (commandForSyn == null) {
        return null;
    }
    return getCommand(commandForSyn);
}
Also used : HistofCommand(com.bluenimble.platform.cli.command.impls.HistofCommand) SplitCommand(com.bluenimble.platform.cli.command.impls.SplitCommand) WGetCommand(com.bluenimble.platform.cli.command.impls.WGetCommand) DelimeterCommand(com.bluenimble.platform.cli.command.impls.DelimeterCommand) ManCommand(com.bluenimble.platform.cli.command.impls.ManCommand) EchoCommand(com.bluenimble.platform.cli.command.impls.EchoCommand) QuitCommand(com.bluenimble.platform.cli.command.impls.QuitCommand) VarsCommand(com.bluenimble.platform.cli.command.impls.VarsCommand) ChangeContextCommand(com.bluenimble.platform.cli.command.impls.ChangeContextCommand) UnSetCommand(com.bluenimble.platform.cli.command.impls.UnSetCommand) Command(com.bluenimble.platform.cli.command.Command) JsonCommand(com.bluenimble.platform.cli.command.impls.JsonCommand) ExitCommand(com.bluenimble.platform.cli.command.impls.ExitCommand) ScriptCommand(com.bluenimble.platform.cli.command.impls.ScriptCommand) ClearCommand(com.bluenimble.platform.cli.command.impls.ClearCommand) HelpCommand(com.bluenimble.platform.cli.command.impls.HelpCommand) SetCommand(com.bluenimble.platform.cli.command.impls.SetCommand) HistoCommand(com.bluenimble.platform.cli.command.impls.HistoCommand) DebugCommand(com.bluenimble.platform.cli.command.impls.DebugCommand)

Aggregations

Command (com.bluenimble.platform.cli.command.Command)5 ToolStartupException (com.bluenimble.platform.cli.ToolStartupException)3 IOException (java.io.IOException)3 InstallI18nException (com.bluenimble.platform.cli.InstallI18nException)2 CommandOption (com.bluenimble.platform.cli.command.CommandOption)2 File (java.io.File)2 ToolContext (com.bluenimble.platform.cli.ToolContext)1 CommandExecutionException (com.bluenimble.platform.cli.command.CommandExecutionException)1 CommandResult (com.bluenimble.platform.cli.command.CommandResult)1 ChangeContextCommand (com.bluenimble.platform.cli.command.impls.ChangeContextCommand)1 ClearCommand (com.bluenimble.platform.cli.command.impls.ClearCommand)1 DebugCommand (com.bluenimble.platform.cli.command.impls.DebugCommand)1 DelimeterCommand (com.bluenimble.platform.cli.command.impls.DelimeterCommand)1 EchoCommand (com.bluenimble.platform.cli.command.impls.EchoCommand)1 ExitCommand (com.bluenimble.platform.cli.command.impls.ExitCommand)1 HelpCommand (com.bluenimble.platform.cli.command.impls.HelpCommand)1 HistoCommand (com.bluenimble.platform.cli.command.impls.HistoCommand)1 HistofCommand (com.bluenimble.platform.cli.command.impls.HistofCommand)1 JsonCommand (com.bluenimble.platform.cli.command.impls.JsonCommand)1 ManCommand (com.bluenimble.platform.cli.command.impls.ManCommand)1