Search in sources :

Example 1 with DefaultCommandResult

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

the class LoadFeatureHandler method execute.

@Override
public CommandResult execute(Tool tool, String... args) throws CommandExecutionException {
    if (args == null || args.length < 1) {
        throw new CommandExecutionException("feature file path required. ex. load feature aTempate.json");
    }
    String path = args[0];
    File templateFile = new File(path + ".json");
    String name = templateFile.getName();
    if (!templateFile.exists() || !templateFile.isFile()) {
        throw new CommandExecutionException("invalid file path > " + path);
    }
    String key = name.substring(0, name.lastIndexOf(Lang.DOT));
    JsonObject oFeature;
    try {
        oFeature = Json.load(templateFile);
    } catch (Exception e) {
        throw new CommandExecutionException(e.getMessage(), e);
    }
    String provider = key;
    String[] variables = null;
    int indexOfDash = key.indexOf(Lang.DASH);
    if (indexOfDash > 0) {
        provider = key.substring(0, indexOfDash);
        variables = Lang.split(key.substring(indexOfDash + 1), "__", true);
    }
    oFeature.set("name", "default");
    oFeature.set("provider", provider);
    final Map<String, String> mVariables = new HashMap<String, String>();
    if (variables != null && variables.length > 0) {
        for (String v : variables) {
            String vKey = v.substring(0, v.indexOf(Lang.UNDERSCORE));
            String vValue = v.substring(v.indexOf(Lang.UNDERSCORE) + 1);
            mVariables.put(vKey, vValue);
        }
    }
    if (mVariables != null) {
        oFeature = (JsonObject) Json.resolve(oFeature, ExpressionCompiler, new VariableResolver() {

            private static final long serialVersionUID = 1L;

            @Override
            public Object resolve(String namespace, String... property) {
                return mVariables.get(Lang.join(property, Lang.DOT));
            }
        });
    }
    @SuppressWarnings("unchecked") Map<String, Object> vars = (Map<String, Object>) tool.currentContext().get(ToolContext.VARS);
    vars.put(key, oFeature);
    return new DefaultCommandResult(CommandResult.OK, oFeature);
}
Also used : HashMap(java.util.HashMap) JsonObject(com.bluenimble.platform.json.JsonObject) CommandExecutionException(com.bluenimble.platform.cli.command.CommandExecutionException) DefaultCommandResult(com.bluenimble.platform.cli.command.impls.DefaultCommandResult) CommandExecutionException(com.bluenimble.platform.cli.command.CommandExecutionException) JsonObject(com.bluenimble.platform.json.JsonObject) VariableResolver(com.bluenimble.platform.templating.VariableResolver) File(java.io.File) HashMap(java.util.HashMap) Map(java.util.Map)

Example 2 with DefaultCommandResult

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

the class LoadKeysHandler method execute.

@Override
public CommandResult execute(Tool tool, String... args) throws CommandExecutionException {
    if (args == null || args.length < 1) {
        throw new CommandExecutionException("keys file path required. ex. load keys instance-uat.keys");
    }
    @SuppressWarnings("unchecked") Map<String, Object> vars = (Map<String, Object>) tool.getContext(Tool.ROOT_CTX).get(ToolContext.VARS);
    String name = null;
    File keysFile = null;
    String path = args[0];
    if (vars.containsKey(path)) {
        // load from var
        name = args[0];
        if (Lang.isNullOrEmpty((String) vars.get(name))) {
            throw new CommandExecutionException("variable " + name + " is empty");
        }
    } else {
        keysFile = new File(path);
        if (!keysFile.exists() || !keysFile.isFile()) {
            throw new CommandExecutionException("invalid file path > " + path);
        }
        name = args.length > 1 ? args[1] : (keysFile.getName().substring(0, keysFile.getName().indexOf(Lang.DOT)));
    }
    File target = new File(BlueNimble.keysFolder(), name + CliSpec.KeysExt);
    InputStream in = null;
    OutputStream out = null;
    try {
        if (keysFile != null) {
            in = new FileInputStream(keysFile);
        } else {
            in = new ByteArrayInputStream(((String) vars.get(name)).getBytes());
        }
        out = new FileOutputStream(target);
        IOUtils.copy(in, out);
    } catch (Exception e) {
        throw new CommandExecutionException(e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
    }
    return new DefaultCommandResult(CommandResult.OK, "keys " + name + " loaded and sat to be current");
}
Also used : FileInputStream(java.io.FileInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FileInputStream(java.io.FileInputStream) CommandExecutionException(com.bluenimble.platform.cli.command.CommandExecutionException) DefaultCommandResult(com.bluenimble.platform.cli.command.impls.DefaultCommandResult) ByteArrayInputStream(java.io.ByteArrayInputStream) FileOutputStream(java.io.FileOutputStream) CommandExecutionException(com.bluenimble.platform.cli.command.CommandExecutionException) Map(java.util.Map) File(java.io.File)

Example 3 with DefaultCommandResult

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

the class SecureApiHandler method execute.

@Override
public CommandResult execute(Tool tool, String... args) throws CommandExecutionException {
    if (args == null || args.length < 1) {
        throw new CommandExecutionException("Command syntax:\nsecure api [api namespace] [+ seperated list of shemes, default to 'cookie+token'] [+ seperated list of methods, default to 'up']\nTry something like secure api token+cookie up+fb");
    }
    String api = args[0];
    String apiPath = Json.getString(Json.getObject(BlueNimble.Config, CliSpec.Config.Apis), api);
    if (Lang.isNullOrEmpty(apiPath)) {
        throw new CommandExecutionException("api path not found for '" + api + "'");
    }
    File apiFolder = new File(BlueNimble.Workspace, apiPath);
    if (!apiFolder.exists() || !apiFolder.isDirectory()) {
        throw new CommandExecutionException("invalid api folder '" + apiPath + "'");
    }
    // schemes
    String[] schemes = getSchemes(args);
    for (String s : schemes) {
        if (!Schemes.contains(s)) {
            throw new CommandExecutionException("unsupported authentication scheme '" + s + "'");
        }
    }
    boolean oauth = false;
    // methods
    String[] methods = getMethods(args);
    if (methods != null) {
        for (String m : methods) {
            if (!Methods.contains(m)) {
                throw new CommandExecutionException("unsupported authentication method '" + m + "'");
            } else if (!"up".equals(m)) {
                oauth = true;
            }
        }
    }
    // load tplApiSpec
    JsonObject oTplApi = null;
    try {
        oTplApi = Json.load(new File(BlueNimble.Home, "templates/security/api.json"));
    } catch (Exception ex) {
        throw new CommandExecutionException("can't read api template security spec file templates/security/api.json");
    }
    JsonObject tplSchemes = (JsonObject) Json.find(oTplApi, "security", "schemes");
    // read api spec
    JsonObject oApi = SpecUtils.read(apiFolder);
    // add security schemes
    JsonObject oSecurity = Json.getObject(oApi, Api.Spec.Security.class.getSimpleName().toLowerCase());
    if (oSecurity == null) {
        oSecurity = new JsonObject();
        oApi.set(Api.Spec.Security.class.getSimpleName().toLowerCase(), oSecurity);
    }
    JsonObject oSchemes = Json.getObject(oSecurity, Api.Spec.Security.Schemes);
    if (oSchemes == null) {
        oSchemes = new JsonObject();
        oSecurity.set(Api.Spec.Security.Schemes, oSchemes);
    }
    for (String s : schemes) {
        if (!oSchemes.containsKey(s)) {
            oSchemes.set(s, tplSchemes.get(s));
            tool.printer().info("security scheme '" + s + "' added to api '" + api + "'");
        }
    }
    SpecUtils.write(apiFolder, oApi);
    // add services
    if (Lang.existsIn("up", methods)) {
        try {
            addService(tool, api, apiFolder, "signup");
        } catch (Exception ex) {
            throw new CommandExecutionException("An error occured when generating code for Signup service. Cause: " + ex.getMessage(), ex);
        }
        // copy email template
        File emailsTplsFolder = new File(apiFolder, "resources/templates/emails");
        if (!emailsTplsFolder.exists()) {
            emailsTplsFolder.mkdirs();
        }
        File apiSignupTplFile = new File(emailsTplsFolder, "signup.html");
        if (!apiSignupTplFile.exists()) {
            File signupTplFile = new File(BlueNimble.Home, "templates/security/templates/emails/signup.html");
            Map<String, String> tokens = new HashMap<String, String>();
            tokens.put("api", api);
            tokens.put("Api", api.substring(0, 1).toUpperCase() + api.substring(1));
            CodeGenUtils.writeFile(signupTplFile, apiSignupTplFile, tokens, null);
            tool.printer().important("An activation email html file was created! 'templates/emails/" + apiSignupTplFile.getName() + "' It's used by the Signup service" + "\nMake sure that the email feature is added to your space in order to send emails.\nUse command 'add feature' to add an smtp server config");
        }
        try {
            addService(tool, api, apiFolder, "activate");
        } catch (Exception ex) {
            throw new CommandExecutionException("An error occured when generating code for Activate service. Cause: " + ex.getMessage(), ex);
        }
        try {
            addService(tool, api, apiFolder, "login");
        } catch (Exception ex) {
            throw new CommandExecutionException("An error occured when generating code for Login service. Cause: " + ex.getMessage(), ex);
        }
        try {
            addService(tool, api, apiFolder, "changePassword");
        } catch (Exception ex) {
            throw new CommandExecutionException("An error occured when generating code for ChangePassword service. Cause: " + ex.getMessage(), ex);
        }
    }
    if (oauth) {
        @SuppressWarnings("unchecked") Map<String, Object> vars = (Map<String, Object>) tool.getContext(Tool.ROOT_CTX).get(ToolContext.VARS);
        String specLang = (String) vars.get(BlueNimble.DefaultVars.SpecLanguage);
        if (Lang.isNullOrEmpty(specLang)) {
            specLang = BlueNimble.SpecLangs.Json;
        }
        try {
            addService(tool, api, apiFolder, "oAuth");
            tool.printer().important("Make sure that your clientId and sercretId are set in your oauth providers.\nSee service spec file resources/services/security/OAuth." + specLang);
        } catch (Exception ex) {
            throw new CommandExecutionException("An error occured when generating code for oAuth service. Cause: " + ex.getMessage(), ex);
        }
    }
    return new DefaultCommandResult(CommandResult.OK, null);
}
Also used : HashMap(java.util.HashMap) JsonObject(com.bluenimble.platform.json.JsonObject) CommandExecutionException(com.bluenimble.platform.cli.command.CommandExecutionException) DefaultCommandResult(com.bluenimble.platform.cli.command.impls.DefaultCommandResult) CommandExecutionException(com.bluenimble.platform.cli.command.CommandExecutionException) JsonObject(com.bluenimble.platform.json.JsonObject) CliSpec(com.bluenimble.platform.icli.mgm.CliSpec) File(java.io.File) HashMap(java.util.HashMap) Map(java.util.Map)

Example 4 with DefaultCommandResult

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

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

the class KeysCommand method execute.

@Override
public CommandResult execute(Tool tool, Map<String, CommandOption> options) throws CommandExecutionException {
    String cmd = (String) tool.currentContext().get(ToolContext.CommandLine);
    try {
        if ("reload".equals(cmd)) {
            BlueNimble.loadKeys(tool);
        }
        Map<String, Keys> secrets = BlueNimble.allKeys();
        if (secrets == null || secrets.isEmpty()) {
            tool.printer().info("No keys found!");
            return null;
        }
        Iterator<String> secIter = secrets.keySet().iterator();
        while (secIter.hasNext()) {
            String sname = secIter.next();
            Keys s = secrets.get(sname);
            boolean current = BlueNimble.keys() != null && sname.equals(BlueNimble.keys().alias());
            tool.printer().content(// __PS__YELLOW:(C) _|_keyAlias
            current ? PrintSpec.Start + Colors.Yellow + PrintSpec.TextSep + "(C) " + PrintSpec.Split + sname : sname, (Lang.isNullOrEmpty(s.name()) ? Lang.BLANK : "      Name | " + s.name() + Lang.ENDLN) + (Lang.isNullOrEmpty(s.domain()) ? Lang.BLANK : "  Endpoint | " + s.domain() + Lang.ENDLN) + (Lang.isNullOrEmpty(s.issuer()) ? Lang.BLANK : "    Issuer | " + s.issuer() + Lang.ENDLN) + (Lang.isNullOrEmpty(s.whenIssued()) ? Lang.BLANK : "    Issued | " + s.whenIssued() + Lang.ENDLN) + (Lang.isNullOrEmpty(s.expiresOn()) ? Lang.BLANK : "   Expires | " + s.expiresOn() + Lang.ENDLN) + (Lang.isNullOrEmpty(s.stamp()) ? Lang.BLANK : "     Stamp | " + s.stamp() + Lang.ENDLN) + "Access Key | " + s.accessKey());
        }
    } 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) Keys(com.bluenimble.platform.icli.mgm.Keys) 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