Search in sources :

Example 6 with CommandExecutionException

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

the class ScriptSourceCommand method execute.

@SuppressWarnings("unchecked")
@Override
public CommandResult execute(Tool tool, Map<String, CommandOption> options) throws CommandExecutionException {
    BufferedReader reader = null;
    if (!script.exists()) {
        throw new CommandExecutionException("Script file " + script.getAbsolutePath() + " not found");
    }
    String cmd = (String) tool.currentContext().get(ToolContext.CommandLine);
    if (!Lang.isNullOrEmpty(cmd)) {
        Map<String, Object> vars = (Map<String, Object>) tool.getContext(Tool.ROOT_CTX).get(ToolContext.VARS);
        String[] args = args(cmd);
        for (int i = 0; i < args.length; i++) {
            vars.put("arg." + i, args[i]);
        }
    }
    try {
        reader = new BufferedReader(new InputStreamReader(new FileInputStream(script)));
        CommandResult result = runCommands(name, reader, tool);
        if (result != null) {
            return result;
        }
    } catch (Exception ex) {
        throw new CommandExecutionException(ex.getMessage(), ex);
    } finally {
        IOUtils.closeQuietly(reader);
    }
    return null;
}
Also used : InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) CommandExecutionException(com.bluenimble.platform.cli.command.CommandExecutionException) Map(java.util.Map) FileInputStream(java.io.FileInputStream) CommandExecutionException(com.bluenimble.platform.cli.command.CommandExecutionException) IOException(java.io.IOException) CommandResult(com.bluenimble.platform.cli.command.CommandResult) DefaultCommandResult(com.bluenimble.platform.cli.command.impls.DefaultCommandResult)

Example 7 with CommandExecutionException

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

the class ScriptSourceCommand method runCommands.

private CommandResult runCommands(String name, BufferedReader reader, Tool tool) throws CommandExecutionException {
    try {
        int res;
        String s;
        while ((s = reader.readLine()) != null) {
            if (Lang.isNullOrEmpty(s)) {
                continue;
            }
            if (s.trim().startsWith("#")) {
                continue;
            }
            res = tool.processCommand(s);
            if (res == Tool.FAILURE) {
                return new DefaultCommandResult(CommandResult.KO, "'" + name + "' Script is stopped due to errors");
            }
        }
    } catch (IOException e) {
        throw new CommandExecutionException(e.getMessage(), e);
    } finally {
        try {
            reader.close();
        } catch (IOException ioex) {
        // IGNORE
        }
    }
    return null;
}
Also used : DefaultCommandResult(com.bluenimble.platform.cli.command.impls.DefaultCommandResult) CommandExecutionException(com.bluenimble.platform.cli.command.CommandExecutionException) IOException(java.io.IOException)

Example 8 with CommandExecutionException

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

the class CodeGenUtils method writeService.

public static void writeService(Tool tool, String verb, String model, File specsFolder, File functionsFolder) throws CommandExecutionException {
    String path = null;
    if (Lang.SLASH.equals(model)) {
        verb = "root";
        model = Lang.BLANK;
    } else if (model != null && model.startsWith(Lang.SLASH)) {
        int indexOfSlash = model.lastIndexOf(Lang.SLASH);
        if (indexOfSlash > 0) {
            path = model.substring(1, indexOfSlash);
        } else {
            path = Lang.BLANK;
        }
        model = model.substring(indexOfSlash + 1);
    }
    if (Lang.STAR.equals(verb)) {
        writeService(tool, ApiVerb.GET.name().toLowerCase(), model, specsFolder, functionsFolder);
        writeService(tool, ApiVerb.POST.name().toLowerCase(), model, specsFolder, functionsFolder);
        writeService(tool, ApiVerb.PUT.name().toLowerCase(), model, specsFolder, functionsFolder);
        writeService(tool, ApiVerb.DELETE.name().toLowerCase(), model, specsFolder, functionsFolder);
        writeService(tool, FindVerb, model, specsFolder, functionsFolder);
        return;
    }
    @SuppressWarnings("unchecked") Map<String, Object> vars = (Map<String, Object>) tool.getContext(Tool.ROOT_CTX).get(ToolContext.VARS);
    String template = (String) vars.get(BlueNimble.DefaultVars.TemplateServices);
    if (Lang.isNullOrEmpty(template)) {
        template = DefaultTemplate;
    }
    File templateFolder = new File(new File(BlueNimble.Home, Templates.class.getSimpleName().toLowerCase() + Lang.SLASH + Templates.Services), template);
    if (!templateFolder.exists()) {
        throw new CommandExecutionException("service template '" + template + "' not installed");
    }
    verb = verb.toLowerCase();
    File verbFolder = null;
    if (path != null) {
        verbFolder = new File(templateFolder, Custom);
    } else {
        verbFolder = new File(templateFolder, verb);
    }
    if (!verbFolder.exists()) {
        return;
    }
    File spec = new File(verbFolder, "spec.json");
    File function = new File(verbFolder, "function.js");
    String models = (model.endsWith("y") ? (model.substring(0, model.length() - 1) + "ies") : model + "s");
    boolean printFolder = false;
    File modelSpecFolder = specsFolder;
    if (!Lang.BLANK.equals(model) && !Lang.BLANK.equals(path)) {
        printFolder = true;
        modelSpecFolder = new File(specsFolder, path == null ? models : path);
    }
    if (!modelSpecFolder.exists()) {
        modelSpecFolder.mkdirs();
    }
    File modelFunctionFolder = functionsFolder;
    if (!Lang.BLANK.equals(model) && !Lang.BLANK.equals(path)) {
        modelFunctionFolder = new File(functionsFolder, path == null ? models : path);
    }
    if (!modelFunctionFolder.exists()) {
        modelFunctionFolder.mkdirs();
    }
    String Model = Lang.BLANK.equals(model) ? Lang.BLANK : model.substring(0, 1).toUpperCase() + model.substring(1);
    String Models = (Model.endsWith("y") ? (Model.substring(0, Model.length() - 1) + "ies") : Model + "s");
    Map<String, String> tokens = new HashMap<String, String>();
    tokens.put(Tokens.Api, Json.getString(BlueNimble.Config, CliSpec.Config.CurrentApi));
    tokens.put(Tokens.model, model);
    tokens.put(Tokens.Model, Model);
    tokens.put(Tokens.models, models);
    tokens.put(Tokens.Models, Models);
    if (path != null) {
        tokens.put(Tokens.Path, path);
    }
    String verbToken = verb;
    if (FindVerb.equals(verb)) {
        verbToken = ApiVerb.GET.name();
        tool.printer().node(0, "'" + verb + " " + models + "' Service");
    } else {
        tool.printer().node(0, "'" + verb + " " + model + "' Service");
    }
    tokens.put(Tokens.Verb, verbToken);
    String specLang = (String) vars.get(BlueNimble.DefaultVars.SpecLanguage);
    if (Lang.isNullOrEmpty(specLang)) {
        specLang = BlueNimble.SpecLangs.Json;
    }
    writeFile(spec, new File(modelSpecFolder, (path == null ? Verbs.get(verb) : Lang.BLANK) + (FindVerb.equals(verb) ? Models : Model) + "." + specLang), tokens, specLang);
    tool.printer().node(1, "    spec file created under 'services/" + (printFolder ? modelSpecFolder.getName() + "/" : "") + (path == null ? Verbs.get(verb) : Lang.BLANK) + (FindVerb.equals(verb) ? Models : Model) + "." + specLang + "'");
    writeFile(function, new File(modelFunctionFolder, (path == null ? Verbs.get(verb) : Lang.BLANK) + (FindVerb.equals(verb) ? Models : Model) + ".js"), tokens, specLang);
    tool.printer().node(1, "function file created under 'functions/" + (printFolder ? modelFunctionFolder.getName() + "/" : "") + (path == null ? Verbs.get(verb) : Lang.BLANK) + (FindVerb.equals(verb) ? Models : Model) + ".js'");
}
Also used : HashMap(java.util.HashMap) Templates(com.bluenimble.platform.icli.mgm.CliSpec.Templates) CommandExecutionException(com.bluenimble.platform.cli.command.CommandExecutionException) HashMap(java.util.HashMap) Map(java.util.Map) File(java.io.File)

Example 9 with CommandExecutionException

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

the class SpecUtils method write.

public static void write(File apiFolder, JsonObject spec) throws CommandExecutionException {
    File fApi = new File(apiFolder, "api." + BlueNimble.SpecLangs.Yaml);
    if (fApi.exists()) {
        // yaml
        OutputStream out = null;
        try {
            out = new FileOutputStream(fApi);
            YamlPrinter yaml = new YamlOutputStreamPrinter(out);
            yaml.print(spec);
        } catch (Exception ex) {
            throw new CommandExecutionException(ex.getMessage(), ex);
        } finally {
            IOUtils.closeQuietly(out);
        }
    } else {
        fApi = new File(apiFolder, "api." + BlueNimble.SpecLangs.Json);
        if (fApi.exists()) {
            try {
                Json.store(spec, fApi);
            } catch (Exception ex) {
                throw new CommandExecutionException(ex.getMessage(), ex);
            }
        }
    }
}
Also used : YamlOutputStreamPrinter(com.bluenimble.platform.json.printers.YamlOutputStreamPrinter) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FileOutputStream(java.io.FileOutputStream) CommandExecutionException(com.bluenimble.platform.cli.command.CommandExecutionException) File(java.io.File) YamlPrinter(com.bluenimble.platform.json.printers.YamlPrinter) CommandExecutionException(com.bluenimble.platform.cli.command.CommandExecutionException)

Example 10 with CommandExecutionException

use of com.bluenimble.platform.cli.command.CommandExecutionException 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)

Aggregations

CommandExecutionException (com.bluenimble.platform.cli.command.CommandExecutionException)35 Map (java.util.Map)20 DefaultCommandResult (com.bluenimble.platform.cli.command.impls.DefaultCommandResult)19 JsonObject (com.bluenimble.platform.json.JsonObject)16 File (java.io.File)16 IOException (java.io.IOException)8 FileInputStream (java.io.FileInputStream)7 InputStream (java.io.InputStream)7 OutputStream (java.io.OutputStream)5 HashMap (java.util.HashMap)5 CommandResult (com.bluenimble.platform.cli.command.CommandResult)4 JsonArray (com.bluenimble.platform.json.JsonArray)4 ByteArrayInputStream (java.io.ByteArrayInputStream)4 FileOutputStream (java.io.FileOutputStream)4 CommandOption (com.bluenimble.platform.cli.command.CommandOption)3 Keys (com.bluenimble.platform.icli.mgm.Keys)3 InputStreamReader (java.io.InputStreamReader)3 CommandHandler (com.bluenimble.platform.cli.command.CommandHandler)2 YamlObject (com.bluenimble.platform.cli.impls.YamlObject)2 Templates (com.bluenimble.platform.icli.mgm.CliSpec.Templates)2