Search in sources :

Example 91 with JsonObject

use of com.bluenimble.platform.json.JsonObject in project serverless by bluenimble.

the class SpecUtils method y2j.

public static void y2j(File fileOrFolder, boolean deleteSource) throws Exception {
    if (!fileOrFolder.exists()) {
        return;
    }
    if (fileOrFolder.isDirectory()) {
        File[] files = fileOrFolder.listFiles(new FileFilter() {

            @Override
            public boolean accept(File file) {
                return file.isDirectory() || file.getName().endsWith(".yaml");
            }
        });
        if (files == null || files.length == 0) {
            return;
        }
        for (File f : files) {
            y2j(f, deleteSource);
        }
    } else {
        File jsonFile = new File(fileOrFolder.getParentFile(), fileOrFolder.getName().substring(0, fileOrFolder.getName().lastIndexOf(Lang.DOT)) + ".json");
        Yaml yaml = new Yaml();
        InputStream is = null;
        try {
            is = new FileInputStream(fileOrFolder);
            @SuppressWarnings("unchecked") JsonObject o = new JsonObject(yaml.loadAs(is, Map.class), true);
            Json.store(o, jsonFile);
        } finally {
            IOUtils.closeQuietly(is);
        }
        if (deleteSource) {
            FileUtils.delete(fileOrFolder);
        }
    }
}
Also used : FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) JsonObject(com.bluenimble.platform.json.JsonObject) FileFilter(java.io.FileFilter) File(java.io.File) Map(java.util.Map) Yaml(org.yaml.snakeyaml.Yaml) FileInputStream(java.io.FileInputStream)

Example 92 with JsonObject

use of com.bluenimble.platform.json.JsonObject in project serverless by bluenimble.

the class SpecUtils method j2y.

@SuppressWarnings("unchecked")
public static void j2y(File fileOrFolder, boolean deleteSource) throws Exception {
    if (!fileOrFolder.exists()) {
        return;
    }
    if (fileOrFolder.isDirectory()) {
        File[] files = fileOrFolder.listFiles(new FileFilter() {

            @Override
            public boolean accept(File file) {
                return file.isDirectory() || file.getName().endsWith(".json");
            }
        });
        if (files == null || files.length == 0) {
            return;
        }
        for (File f : files) {
            j2y(f, deleteSource);
        }
    } else {
        File ymlFile = new File(fileOrFolder.getParentFile(), fileOrFolder.getName().substring(0, fileOrFolder.getName().lastIndexOf(Lang.DOT)) + ".yaml");
        OutputStream out = null;
        try {
            out = new FileOutputStream(ymlFile);
            new YamlOutputStreamPrinter(out).print(Json.load(fileOrFolder));
        } finally {
            IOUtils.closeQuietly(out);
        }
        // validate
        Yaml yaml = new Yaml();
        InputStream is = null;
        try {
            is = new FileInputStream(ymlFile);
            new JsonObject(yaml.loadAs(is, Map.class), true);
        } finally {
            IOUtils.closeQuietly(is);
        }
        if (deleteSource) {
            FileUtils.delete(fileOrFolder);
        }
    }
}
Also used : YamlOutputStreamPrinter(com.bluenimble.platform.json.printers.YamlOutputStreamPrinter) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FileOutputStream(java.io.FileOutputStream) JsonObject(com.bluenimble.platform.json.JsonObject) FileFilter(java.io.FileFilter) File(java.io.File) Map(java.util.Map) Yaml(org.yaml.snakeyaml.Yaml) FileInputStream(java.io.FileInputStream)

Example 93 with JsonObject

use of com.bluenimble.platform.json.JsonObject 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 94 with JsonObject

use of com.bluenimble.platform.json.JsonObject in project serverless by bluenimble.

the class MongoDatabasePlugin method createClients.

private void createClients(ApiSpace space) {
    // create factories
    JsonObject dbFeature = Json.getObject(space.getFeatures(), feature);
    if (dbFeature == null || dbFeature.isEmpty()) {
        return;
    }
    Iterator<String> keys = dbFeature.keys();
    while (keys.hasNext()) {
        String key = keys.next();
        JsonObject source = Json.getObject(dbFeature, key);
        if (!MongoDatabasePlugin.this.getName().equalsIgnoreCase(Json.getString(source, ApiSpace.Features.Provider))) {
            continue;
        }
        JsonObject spec = Json.getObject(source, ApiSpace.Features.Spec);
        if (spec == null) {
            continue;
        }
        createClient(key, space, spec);
    }
}
Also used : JsonObject(com.bluenimble.platform.json.JsonObject)

Example 95 with JsonObject

use of com.bluenimble.platform.json.JsonObject in project serverless by bluenimble.

the class MongoDatabasePlugin method dropClients.

private void dropClients(ApiSpace space) {
    JsonObject dbFeature = Json.getObject(space.getFeatures(), feature);
    Set<String> recyclables = space.getRecyclables();
    for (String r : recyclables) {
        if (!r.startsWith(feature + Lang.DOT)) {
            continue;
        }
        String name = r.substring((feature + Lang.DOT).length());
        if (dbFeature == null || dbFeature.containsKey(name)) {
            // it's deleted
            RecyclableClient rf = (RecyclableClient) space.getRecyclable(r);
            // remove from recyclables
            space.removeRecyclable(r);
            // recycle
            rf.recycle();
        }
    }
}
Also used : JsonObject(com.bluenimble.platform.json.JsonObject)

Aggregations

JsonObject (com.bluenimble.platform.json.JsonObject)230 ApiServiceExecutionException (com.bluenimble.platform.api.ApiServiceExecutionException)40 DatabaseObject (com.bluenimble.platform.db.DatabaseObject)37 JsonArray (com.bluenimble.platform.json.JsonArray)37 JsonApiOutput (com.bluenimble.platform.api.impls.JsonApiOutput)34 Database (com.bluenimble.platform.db.Database)29 ApiSpace (com.bluenimble.platform.api.ApiSpace)26 File (java.io.File)25 ApiAccessDeniedException (com.bluenimble.platform.api.ApiAccessDeniedException)23 Map (java.util.Map)22 IOException (java.io.IOException)20 CommandExecutionException (com.bluenimble.platform.cli.command.CommandExecutionException)17 JsonQuery (com.bluenimble.platform.db.query.impls.JsonQuery)16 InputStream (java.io.InputStream)14 Date (java.util.Date)14 DefaultCommandResult (com.bluenimble.platform.cli.command.impls.DefaultCommandResult)13 ApiManagementException (com.bluenimble.platform.api.ApiManagementException)12 DefaultDatabaseObjectSerializer (com.bluenimble.platform.db.impls.DefaultDatabaseObjectSerializer)11 HashMap (java.util.HashMap)11 DatabaseException (com.bluenimble.platform.db.DatabaseException)9