Search in sources :

Example 21 with CommandExecutionException

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

the class CodeGenUtils method writeFile.

public static void writeFile(File source, File dest, Map<String, String> tokens, String lang) throws CommandExecutionException {
    if (!source.exists()) {
        return;
    }
    if (tokens == null) {
        tokens = new HashMap<String, String>();
    }
    tokens.put(Tokens.User, System.getProperty("user.name"));
    tokens.put(Tokens.Date, Lang.toString(new Date(), Lang.DEFAULT_DATE_TIME_FORMAT, Locale.getDefault()));
    boolean isYamlSpec = source.getName().endsWith(BlueNimble.SpecLangs.Json) && BlueNimble.SpecLangs.Yaml.equals(lang);
    boolean deleteSource = false;
    if (dest == null) {
        if (isYamlSpec) {
            dest = new File(source.getParentFile(), source.getName().substring(0, source.getName().lastIndexOf(Lang.DOT)) + Lang.DOT + BlueNimble.SpecLangs.Yaml);
            deleteSource = true;
        } else {
            dest = source;
        }
    }
    InputStream is = null;
    OutputStream os = null;
    try {
        is = new FileInputStream(source);
        String content = IOUtils.toString(is);
        IOUtils.closeQuietly(is);
        Set<String> keys = tokens.keySet();
        for (String k : keys) {
            content = Lang.replace(content, Delimiters.Start + k + Delimiters.End, tokens.get(k));
        }
        os = new FileOutputStream(dest);
        // if Yaml
        if (isYamlSpec) {
            SpecUtils.toYaml(content, os);
        } else {
            IOUtils.copy(new ByteArrayInputStream(content.getBytes()), os);
        }
        if (deleteSource) {
            FileUtils.delete(source);
        }
    } catch (Exception ex) {
        throw new CommandExecutionException(ex.getMessage(), ex);
    } finally {
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
    }
}
Also used : FileInputStream(java.io.FileInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) Date(java.util.Date) FileInputStream(java.io.FileInputStream) CommandExecutionException(com.bluenimble.platform.cli.command.CommandExecutionException) ByteArrayInputStream(java.io.ByteArrayInputStream) FileOutputStream(java.io.FileOutputStream) CommandExecutionException(com.bluenimble.platform.cli.command.CommandExecutionException) File(java.io.File)

Example 22 with CommandExecutionException

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

the class RemoteUtils method processRequest.

public static CommandResult processRequest(Tool tool, JsonObject source, final Map<String, String> options) throws CommandExecutionException {
    if (Lang.isDebugMode()) {
        tool.printer().content("Remote Command", source.toString());
    }
    JsonObject oKeys = null;
    Keys keys = BlueNimble.keys();
    if (keys != null) {
        oKeys = keys.json();
    } else {
        oKeys = new JsonObject();
    }
    @SuppressWarnings("unchecked") Map<String, Object> vars = (Map<String, Object>) tool.getContext(Tool.ROOT_CTX).get(ToolContext.VARS);
    Object oTrustAll = vars.get(DefaultVars.SslTrust);
    if (oTrustAll == null) {
        Http.setTrustAll(false);
    } else {
        Http.setTrustAll(Lang.TrueValues.contains(String.valueOf(oTrustAll)));
    }
    boolean isOutFile = AbstractTool.CMD_OUT_FILE.equals(vars.get(AbstractTool.CMD_OUT));
    List<Object> streams = new ArrayList<Object>();
    HttpResponse response = null;
    try {
        HttpRequest request = request(oKeys, Json.getObject(source, Spec.request.class.getSimpleName()), tool, BlueNimble.Config, options, streams);
        response = Http.send(request);
        String contentType = response.getContentType();
        if (contentType == null) {
            contentType = ApiContentTypes.Text;
        }
        int indexOfSemi = contentType.indexOf(Lang.SEMICOLON);
        if (indexOfSemi > 0) {
            contentType = contentType.substring(0, indexOfSemi).trim();
        }
        OutputStream out = System.out;
        if (Printable.contains(contentType) && !isOutFile) {
            out = new ByteArrayOutputStream();
            response.getBody().dump(out, Encodings.UTF8, null);
        }
        List<HttpHeader> rHeaders = response.getHeaders();
        if (rHeaders != null && !rHeaders.isEmpty()) {
            JsonObject oHeaders = new JsonObject();
            for (HttpHeader h : rHeaders) {
                oHeaders.set(h.getName(), Lang.join(h.getValues(), Lang.COMMA));
            }
            vars.put(RemoteResponseHeaders, oHeaders);
        }
        if (contentType.startsWith(ApiContentTypes.Json)) {
            JsonObject result = new JsonObject(new String(((ByteArrayOutputStream) out).toByteArray()));
            String trace = null;
            if (response.getStatus() >= 400) {
                trace = result.getString("trace");
                result.remove("trace");
            }
            if (trace != null && Lang.isDebugMode()) {
                vars.put(RemoteResponseError, trace);
            }
            if (response.getStatus() < 400) {
                return new DefaultCommandResult(CommandResult.OK, result);
            } else {
                return new DefaultCommandResult(CommandResult.KO, result);
            }
        } else if (contentType.startsWith(ApiContentTypes.Yaml)) {
            Yaml yaml = new Yaml();
            String ys = new String(((ByteArrayOutputStream) out).toByteArray());
            ys = Lang.replace(ys, Lang.TAB, "  ");
            @SuppressWarnings("unchecked") Map<String, Object> map = yaml.loadAs(ys, Map.class);
            Object trace = null;
            if (response.getStatus() >= 400) {
                trace = map.get("trace");
                map.remove("trace");
            }
            if (trace != null && Lang.isDebugMode()) {
                vars.put(RemoteResponseError, trace);
            }
            if (response.getStatus() < 400) {
                return new DefaultCommandResult(CommandResult.OK, new YamlObject(map));
            } else {
                return new DefaultCommandResult(CommandResult.KO, new YamlObject(map));
            }
        } else if (contentType.startsWith(ApiContentTypes.Text) || contentType.startsWith(ApiContentTypes.Html)) {
            String content = new String(((ByteArrayOutputStream) out).toByteArray());
            if (response.getStatus() < 400) {
                return new DefaultCommandResult(CommandResult.OK, content);
            } else {
                return new DefaultCommandResult(CommandResult.KO, content);
            }
        } else {
            if (response.getStatus() < 400) {
                if (isOutFile) {
                    return new DefaultCommandResult(CommandResult.OK, response.getBody().get(0).toInputStream());
                } else {
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    response.getBody().dump(baos, Encodings.UTF8, null);
                    return new DefaultCommandResult(CommandResult.OK, new String(((ByteArrayOutputStream) baos).toByteArray()));
                }
            } else {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                response.getBody().dump(baos, Encodings.UTF8, null);
                return new DefaultCommandResult(CommandResult.KO, new String(((ByteArrayOutputStream) baos).toByteArray()));
            }
        }
    } catch (Exception e) {
        throw new CommandExecutionException(e.getMessage(), e);
    } finally {
        if (streams != null) {
            for (Object s : streams) {
                if (s instanceof InputStream) {
                    IOUtils.closeQuietly((InputStream) s);
                } else if (s instanceof StreamPointer) {
                    StreamPointer sp = (StreamPointer) s;
                    IOUtils.closeQuietly(sp.getStream());
                    if (sp.shouldDelete()) {
                        try {
                            FileUtils.delete(sp.getPointer());
                        } catch (IOException e) {
                        // IGNORE
                        }
                    }
                }
            }
        }
    }
}
Also used : ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) ArrayList(java.util.ArrayList) JsonObject(com.bluenimble.platform.json.JsonObject) StreamPointer(com.bluenimble.platform.cli.command.parser.converters.StreamPointer) DefaultCommandResult(com.bluenimble.platform.cli.command.impls.DefaultCommandResult) HttpHeader(com.bluenimble.platform.http.HttpHeader) HttpRequest(com.bluenimble.platform.http.request.HttpRequest) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) HttpResponse(com.bluenimble.platform.http.response.HttpResponse) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) HttpEndpoint(com.bluenimble.platform.http.HttpEndpoint) Yaml(org.yaml.snakeyaml.Yaml) CommandExecutionException(com.bluenimble.platform.cli.command.CommandExecutionException) IOException(java.io.IOException) Keys(com.bluenimble.platform.icli.mgm.Keys) YamlObject(com.bluenimble.platform.cli.impls.YamlObject) JsonObject(com.bluenimble.platform.json.JsonObject) CommandExecutionException(com.bluenimble.platform.cli.command.CommandExecutionException) YamlObject(com.bluenimble.platform.cli.impls.YamlObject) Spec(com.bluenimble.platform.icli.mgm.commands.mgm.RemoteCommand.Spec) Map(java.util.Map) HashMap(java.util.HashMap)

Example 23 with CommandExecutionException

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

the class SpecUtils method read.

@SuppressWarnings("unchecked")
public static JsonObject read(File apiFolder) throws CommandExecutionException {
    File fApi = new File(apiFolder, "api.json");
    if (fApi.exists()) {
        try {
            return Json.load(fApi);
        } catch (Exception ex) {
            throw new CommandExecutionException("can't read api spec file " + fApi.getName() + ". Reason: " + ex.getMessage(), ex);
        }
    } else {
        fApi = new File(apiFolder, "api.yaml");
    }
    if (!fApi.exists() || fApi.isDirectory()) {
        throw new CommandExecutionException("api spec file not found");
    }
    // it's yaml
    Yaml yaml = new Yaml();
    InputStream is = null;
    try {
        is = new FileInputStream(fApi);
        return new JsonObject(yaml.loadAs(is, Map.class), true);
    } catch (Exception ex) {
        throw new CommandExecutionException(ex.getMessage(), ex);
    } finally {
        IOUtils.closeQuietly(is);
    }
}
Also used : FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) JsonObject(com.bluenimble.platform.json.JsonObject) CommandExecutionException(com.bluenimble.platform.cli.command.CommandExecutionException) File(java.io.File) Map(java.util.Map) CommandExecutionException(com.bluenimble.platform.cli.command.CommandExecutionException) Yaml(org.yaml.snakeyaml.Yaml) FileInputStream(java.io.FileInputStream)

Example 24 with CommandExecutionException

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

the class MacroSourceCommand method execute.

@Override
public CommandResult execute(final Tool tool, Map<String, CommandOption> options) throws CommandExecutionException {
    InputStream input = null;
    SimpleBindings bindings = new SimpleBindings();
    String command = (String) tool.currentContext().get(ToolContext.CommandLine);
    if (!Lang.isNullOrEmpty(command)) {
        bindings.put("Command", command);
    }
    bindings.put("Home", BlueNimble.Work);
    bindings.put("Config", BlueNimble.Config);
    bindings.put("Tool", new JsTool(tool));
    bindings.put(JavaClass, new Function<String, Class<?>>() {

        @Override
        public Class<?> apply(String type) {
            try {
                return MacroSourceCommand.class.getClassLoader().loadClass(type);
            } catch (ClassNotFoundException cnfe) {
                throw new RuntimeException(cnfe);
            }
        }
    });
    bindings.put("Vars", tool.getContext(Tool.ROOT_CTX).get(ToolContext.VARS));
    Keys keys = BlueNimble.keys();
    if (keys != null) {
        bindings.put("Keys", keys.json());
    }
    try {
        input = new FileInputStream(script);
        List<InputStream> blocks = new ArrayList<InputStream>();
        blocks.add(new ByteArrayInputStream(Native.getBytes()));
        blocks.add(input);
        Engine.eval(new InputStreamReader(new SequenceInputStream(Collections.enumeration(blocks))), bindings);
    } catch (Exception e) {
        throw new CommandExecutionException(e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(input);
    }
    return null;
}
Also used : JsTool(com.bluenimble.platform.icli.mgm.utils.JsTool) InputStreamReader(java.io.InputStreamReader) ByteArrayInputStream(java.io.ByteArrayInputStream) SequenceInputStream(java.io.SequenceInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) FileInputStream(java.io.FileInputStream) CommandExecutionException(com.bluenimble.platform.cli.command.CommandExecutionException) SequenceInputStream(java.io.SequenceInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) SimpleBindings(javax.script.SimpleBindings) Keys(com.bluenimble.platform.icli.mgm.Keys) CommandExecutionException(com.bluenimble.platform.cli.command.CommandExecutionException)

Example 25 with CommandExecutionException

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

the class CreateApiContextHandler method execute.

@Override
public CommandResult execute(Tool tool, String... args) throws CommandExecutionException {
    if (args == null || args.length < 1) {
        throw new CommandExecutionException("api or function namespace required. ex. cli api myNamespace");
    }
    String namespace = args[0];
    String contextName = namespace;
    if (args.length > 1) {
        contextName = args[1];
    }
    if (contextName.equalsIgnoreCase("global")) {
        return new DefaultCommandResult(CommandResult.KO, "Invalid context name");
    }
    File apiFolder = new File(BlueNimble.Workspace, namespace);
    if (!apiFolder.exists()) {
        return new DefaultCommandResult(CommandResult.KO, "api not found in workspace");
    }
    File contextFolder = new File(BlueNimble.Work, contextName);
    if (contextFolder.exists()) {
        try {
            FileUtils.delete(contextFolder);
        } catch (IOException e) {
            throw new CommandExecutionException(e.getMessage(), e);
        }
    }
    // create the context folder
    contextFolder.mkdir();
    return new DefaultCommandResult(CommandResult.OK, null);
}
Also used : DefaultCommandResult(com.bluenimble.platform.cli.command.impls.DefaultCommandResult) CommandExecutionException(com.bluenimble.platform.cli.command.CommandExecutionException) IOException(java.io.IOException) 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