Search in sources :

Example 11 with DefaultCommandResult

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

the class JsonSetHandler method execute.

@Override
public CommandResult execute(Tool tool, String... args) throws CommandExecutionException {
    if (args == null || args.length < 1) {
        throw new CommandExecutionException("json variable name required");
    }
    if (args.length < 2) {
        throw new CommandExecutionException("json property required");
    }
    String var = args[0];
    @SuppressWarnings("unchecked") Map<String, Object> vars = (Map<String, Object>) tool.getContext(Tool.ROOT_CTX).get(ToolContext.VARS);
    Object o = vars.get(var);
    if (o == null) {
        throw new CommandExecutionException("variable '" + var + "' not found");
    }
    if (!(o instanceof JsonObject)) {
        throw new CommandExecutionException("variable '" + var + "' isn't a valid json object");
    }
    JsonObject json = (JsonObject) o;
    String prop = args[1];
    // it's a delete
    int indexOfDot = prop.indexOf(Lang.DOT);
    String value = args[2];
    boolean isJson = false;
    boolean isVar = false;
    Object oValue = null;
    if (value.startsWith("j\\")) {
        value = value.substring(3);
        isJson = true;
    }
    if (value.startsWith("v\\")) {
        value = value.substring(3);
        isVar = true;
    }
    if (Lang.isNullOrEmpty(value)) {
        isJson = false;
    }
    oValue = value;
    if (isJson) {
        try {
            oValue = JsonParser.parse(value);
        } catch (Exception ex) {
            throw new CommandExecutionException(ex.getMessage(), ex);
        }
    }
    if (isVar) {
        oValue = vars.get(value);
    }
    if (indexOfDot <= 0) {
        json.set(prop, oValue);
    } else {
        String[] path = Lang.split(prop, Lang.DOT);
        prop = path[path.length - 1];
        path = Lang.moveRight(path, 1);
        Object child = Json.find(json, path);
        if (child == null) {
            throw new CommandExecutionException(Lang.join(path, Lang.DOT) + " not found");
        }
        if (child instanceof JsonObject) {
            ((JsonObject) child).set(prop, oValue);
        } else if (child instanceof JsonArray) {
            boolean append = false;
            int iProp = -1;
            if (prop.equals(Lang.UNDERSCORE)) {
                append = true;
            } else {
                try {
                    iProp = Integer.valueOf(prop);
                } catch (Exception ex) {
                // ignore
                }
            }
            JsonArray array = (JsonArray) child;
            if (append) {
                array.add(oValue);
            } else {
                if (iProp > -1 && array.count() > iProp) {
                    ((JsonArray) child).add(iProp, oValue);
                }
            }
        }
    }
    return new DefaultCommandResult(CommandResult.OK, json);
}
Also used : JsonObject(com.bluenimble.platform.json.JsonObject) CommandExecutionException(com.bluenimble.platform.cli.command.CommandExecutionException) JsonArray(com.bluenimble.platform.json.JsonArray) DefaultCommandResult(com.bluenimble.platform.cli.command.impls.DefaultCommandResult) CommandExecutionException(com.bluenimble.platform.cli.command.CommandExecutionException) JsonObject(com.bluenimble.platform.json.JsonObject) Map(java.util.Map)

Example 12 with DefaultCommandResult

use of com.bluenimble.platform.cli.command.impls.DefaultCommandResult 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 13 with DefaultCommandResult

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

the class FeaturesCommand method execute.

@Override
public CommandResult execute(Tool tool, Map<String, CommandOption> options) throws CommandExecutionException {
    File features = new File(BlueNimble.Home, "templates/features");
    File[] files = features.listFiles();
    StringBuilder sb = new StringBuilder();
    for (File file : files) {
        sb.append(file.getName().substring(0, file.getName().lastIndexOf(Lang.DOT))).append(Lang.ENDLN);
    }
    tool.printer().content(features.getName(), sb.toString());
    sb.setLength(0);
    return new DefaultCommandResult(CommandResult.OK, null);
}
Also used : DefaultCommandResult(com.bluenimble.platform.cli.command.impls.DefaultCommandResult) File(java.io.File)

Example 14 with DefaultCommandResult

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

Example 15 with DefaultCommandResult

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

the class ApiCommand method execute.

@Override
public CommandResult execute(Tool tool, Map<String, CommandOption> options) throws CommandExecutionException {
    JsonObject config = BlueNimble.Config;
    String apiNs = (String) tool.currentContext().get(ToolContext.CommandLine);
    if (Lang.isNullOrEmpty(apiNs)) {
        String currentApi = Json.getString(config, CliSpec.Config.CurrentApi);
        try {
            if (Lang.isNullOrEmpty(currentApi)) {
                tool.printer().info("use ' api YourApi ' or create a new one using ' create api YourApi '");
            } else {
                tool.printer().content("Current Api", "namespace: " + currentApi + "\npath: $ws/ " + Json.getString(Json.getObject(config, CliSpec.Config.Apis), currentApi));
            }
            return null;
        } catch (Exception ex) {
            throw new CommandExecutionException(ex.getMessage(), ex);
        }
    }
    apiNs = apiNs.trim();
    String apiPath = Json.getString(Json.getObject(config, CliSpec.Config.Apis), apiNs);
    if (Lang.isNullOrEmpty(apiPath)) {
        tool.printer().info("api '" + apiNs + "' not found in workspace");
        return null;
    }
    config.set(CliSpec.Config.CurrentApi, apiNs);
    try {
        BlueNimble.saveConfig();
        tool.printer().content("Current Api", "namespace: " + apiNs + "\npath: $ws/ " + Json.getString(Json.getObject(config, CliSpec.Config.Apis), apiNs));
    } catch (Exception ex) {
        throw new CommandExecutionException(ex.getMessage(), ex);
    }
    return new DefaultCommandResult(CommandResult.OK, null);
}
Also used : DefaultCommandResult(com.bluenimble.platform.cli.command.impls.DefaultCommandResult) JsonObject(com.bluenimble.platform.json.JsonObject) CommandExecutionException(com.bluenimble.platform.cli.command.CommandExecutionException) CommandExecutionException(com.bluenimble.platform.cli.command.CommandExecutionException)

Aggregations

DefaultCommandResult (com.bluenimble.platform.cli.command.impls.DefaultCommandResult)19 CommandExecutionException (com.bluenimble.platform.cli.command.CommandExecutionException)18 JsonObject (com.bluenimble.platform.json.JsonObject)13 Map (java.util.Map)12 File (java.io.File)10 JsonArray (com.bluenimble.platform.json.JsonArray)4 IOException (java.io.IOException)4 HashMap (java.util.HashMap)3 Keys (com.bluenimble.platform.icli.mgm.Keys)2 JsonException (com.bluenimble.platform.json.JsonException)2 FileInputStream (java.io.FileInputStream)2 InputStream (java.io.InputStream)2 OutputStream (java.io.OutputStream)2 StreamPointer (com.bluenimble.platform.cli.command.parser.converters.StreamPointer)1 YamlObject (com.bluenimble.platform.cli.impls.YamlObject)1 HttpEndpoint (com.bluenimble.platform.http.HttpEndpoint)1 HttpHeader (com.bluenimble.platform.http.HttpHeader)1 HttpRequest (com.bluenimble.platform.http.request.HttpRequest)1 HttpResponse (com.bluenimble.platform.http.response.HttpResponse)1 CliSpec (com.bluenimble.platform.icli.mgm.CliSpec)1