Example usage for io.vertx.core.json JsonArray add

List of usage examples for io.vertx.core.json JsonArray add

Introduction

In this page you can find the example usage for io.vertx.core.json JsonArray add.

Prototype

public JsonArray add(Object value) 

Source Link

Document

Add an Object to the JSON array.

Usage

From source file:FileAccess.java

public JsonObject getProjectStructure(String projectId) {
    JsonObject projectStructure = new JsonObject();

    JsonArray rootFolder = new JsonArray();

    JsonArray rootFile = new JsonArray();

    List<String> rootDirectorys = vertx.fileSystem().readDirBlocking("project/" + projectId);

    System.out.println(new JsonArray(rootDirectorys).toString());

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    for (String directory : rootDirectorys) {
        System.out.println(directory + "directory");
        FileProps something = vertx.fileSystem().lpropsBlocking(directory);
        if (something.isDirectory()) {
            JsonObject directoryJSON = new JsonObject();
            String splitDirectory[] = directory.split("\\\\");
            directoryJSON.put("name", splitDirectory[splitDirectory.length - 1]);
            //                tinggal tambahkan encode menggunakan base 64 agar tidak terdeteksi titik.
            String id = splitDirectory[splitDirectory.length - 2];
            String tmpId = new Base32().encodeAsString(splitDirectory[splitDirectory.length - 1].getBytes())
                    .replace("=", "0");
            directoryJSON.put("id", tmpId);
            directoryJSON.put("create_date", dateFormat.format(new Date(something.creationTime())));
            directoryJSON.put("modify_date", dateFormat.format(new Date(something.lastModifiedTime())));
            rootFolder.add(directoryJSON);

            List<String> subDirectorysFiles = vertx.fileSystem().readDirBlocking(directory);
            JsonArray subFiles = new JsonArray();
            for (String subDirectoryFile : subDirectorysFiles) {
                JsonObject fileJSON = new JsonObject();
                String splitFile[] = subDirectoryFile.split("\\\\");
                fileJSON.put("name", splitFile[splitFile.length - 1]);
                fileJSON.put("id", new Base32().encodeAsString(
                        (splitFile[splitFile.length - 2] + "/" + splitFile[splitFile.length - 1]).getBytes())
                        .replace("=", "0"));
                fileJSON.put("create_date", dateFormat.format(new Date(something.creationTime())));
                fileJSON.put("modify_date", dateFormat.format(new Date(something.lastModifiedTime())));

                subFiles.add(fileJSON);/*from w w w  .  ja v  a2s .c  o  m*/
            }
            directoryJSON.put("files", subFiles);

        } else {
            JsonObject fileJSON = new JsonObject();
            String splitFile[] = directory.split("\\\\");
            fileJSON.put("name", splitFile[splitFile.length - 1]);
            fileJSON.put("id",
                    new Base32().encodeAsString(splitFile[splitFile.length - 1].getBytes()).replace("=", "0"));
            fileJSON.put("create_date", dateFormat.format(new Date(something.creationTime())));
            fileJSON.put("modify_date", dateFormat.format(new Date(something.lastModifiedTime())));
            rootFile.add(fileJSON);
        }
    }

    projectStructure.put("folders", rootFolder);
    projectStructure.put("files", rootFile);

    System.out.println(projectStructure.toString());
    return projectStructure;
}

From source file:RestAPI.java

private void handleListProducts(RoutingContext routingContext) {
    JsonArray arr = new JsonArray();
    products.forEach((k, v) -> arr.add(v));
    routingContext.response().putHeader("content-type", "application/json").end(arr.encodePrettily());
}

From source file:cm.study.vertx.database.WikiDatabaseServiceVertxProxyHandler.java

License:Apache License

private Handler<AsyncResult<List<Character>>> createListCharHandler(Message msg) {
    return res -> {
        if (res.failed()) {
            if (res.cause() instanceof ServiceException) {
                msg.reply(res.cause());//from   w  ww .  j a v  a  2  s .c  om
            } else {
                msg.reply(new ServiceException(-1, res.cause().getMessage()));
            }
        } else {
            JsonArray arr = new JsonArray();
            for (Character chr : res.result()) {
                arr.add((int) chr);
            }
            msg.reply(arr);
        }
    };
}

From source file:cm.study.vertx.database.WikiDatabaseServiceVertxProxyHandler.java

License:Apache License

private Handler<AsyncResult<Set<Character>>> createSetCharHandler(Message msg) {
    return res -> {
        if (res.failed()) {
            if (res.cause() instanceof ServiceException) {
                msg.reply(res.cause());// w  w  w  . java 2s. c  o  m
            } else {
                msg.reply(new ServiceException(-1, res.cause().getMessage()));
            }
        } else {
            JsonArray arr = new JsonArray();
            for (Character chr : res.result()) {
                arr.add((int) chr);
            }
            msg.reply(arr);
        }
    };
}

From source file:com.chibchasoft.vertx.verticle.deployment.DependentsDeployment.java

License:Open Source License

/**
 * Returns a JsonObject populated with the information from this object
 * @return The JsonObject/*  w w w. j av a  2  s.c  o  m*/
 */
public JsonObject toJson() {
    JsonObject json = new JsonObject();
    if (this.getConfigurations() != null) {
        JsonArray array = new JsonArray();
        this.getConfigurations().forEach(item -> array.add(item.toJson()));
        json.put("configurations", array);
    }
    return json;
}

From source file:com.chibchasoft.vertx.verticle.deployment.DeploymentConfiguration.java

License:Open Source License

/**
 * Returns a JsonObject populated with the information from this object
 * @return The JsonObject/*from ww w . j a va  2s .  c  o  m*/
 */
public JsonObject toJson() {
    JsonObject json = new JsonObject();
    json.put("name", name);
    if (deploymentOptions != null) {
        JsonObject depOptJson = new JsonObject();
        DeploymentOptionsConverter.toJson(deploymentOptions, depOptJson);
        json.put("deploymentOptions", depOptJson);
    }
    if (this.getDependents() != null) {
        JsonArray array = new JsonArray();
        this.getDependents().forEach(item -> array.add(item.toJson()));
        json.put("dependents", array);
    }
    return json;
}

From source file:com.cyngn.vertx.opentsdb.Util.java

License:Apache License

/**
 * Add another metric to a bulk metric.//from  www. j a v  a  2  s. c om
 *
 * @param bulkMetricObj the bulk metric obj to add more metrics to
 * @param metricToAdd the properly constructed individual metric object
 */
public static void addBulkMetric(JsonObject bulkMetricObj, JsonObject metricToAdd) {
    JsonArray metricHolder = bulkMetricObj.getJsonArray(MetricsParser.METRICS_FIELD);
    if (metricHolder == null) {
        throw new IllegalArgumentException(
                "Could not find a valid " + MetricsParser.METRICS_FIELD + " in the object");
    }

    metricHolder.add(metricToAdd);
}

From source file:com.deblox.releaseboard.ReleaseBoardVerticle.java

License:Apache License

/**
 * Start the verticle/*from  w w w .  j  a va 2  s  .  co  m*/
 *
 * @param startFuture
 * @throws Exception
 */
public void start(Future<Void> startFuture) throws Exception {

    logger.info("starup with config: " + config().toString());

    // get expire_release in seconds
    int expire_timeout = config().getInteger("expire_timeout", 86000);

    // map of releases, should contain date events were fired in  / updated also
    releasesData = new HashMap<>();

    stateFile = config().getString("state_file", "/state.json");

    // connect to the eventbus
    eb = vertx.eventBus();

    // load the state file if exists
    vertx.fileSystem().exists(stateFile, h -> {
        if (h.succeeded()) {
            try {
                JsonArray history = Util.loadConfig(stateFile).getJsonArray("releases");
                for (Object release : history) {
                    JsonObject releaseJson = new JsonObject(release.toString());
                    logger.info("loading release: " + releaseJson.getString("id"));
                    releasesData.put(releaseJson.getString("id"), releaseJson.getJsonObject("data"));
                }

            } catch (IOException e) {
                logger.warn("unable to load state file, it will be created / overwritten");
                e.printStackTrace();
            }

        }
    });

    /*
     * listen for release events from other verticles / clients
     *
     * example release-event published direct to the eventbus ( see Server.java )
     *
            
      {
          "code": 205,
          "component": "maximus",
          "environment": "CI1",
          "status": "Deploy Succeeded",
          "version": "1.0.0.309"
      }
            
     *
     *
     */
    eb.consumer("release-event", event -> {
        logger.info(event.body().toString());

        JsonObject body = null;

        // create a json object from the message
        try {
            body = new JsonObject(event.body().toString());
        } catch (Exception e) {
            logger.warn("not a json object");
            event.reply(new JsonObject().put("result", "failure").put("reason", "that wasn't json"));
        }

        // create check if a id is specified, else combine component and version
        body.put("id", body.getString("id", body.getValue("component") + "-" + body.getValue("version")));

        // used for marking expired messages when time is not enough or too much
        body.put("expired", false);

        // add the date now
        body.put("date", LocalDateTime.now().format(formatter));

        // pop the old matching JIRA release
        releasesData.remove(body.getString("id"));

        // put the updated one
        releasesData.put(body.getString("id"), body);

        event.reply(new JsonObject().put("result", "success"));

    });

    // expire a release event and remove it from the map
    eb.consumer("expire-release-event", event -> {
        try {
            logger.info("delete event: " + event.body().toString());
            JsonObject request = new JsonObject(event.body().toString());
            releasesData.remove(request.getString("id"));

            // forulate the expire message
            JsonObject msg = new JsonObject().put("topic", "releases").put("action", "expire");
            JsonArray arr = new JsonArray().add(request.getString("id"));
            msg.put("data", arr);

            eb.publish("releases", msg);

            event.reply(new JsonObject().put("result", "success"));
        } catch (Exception e) {
            event.reply(new JsonObject().put("result", "error"));
        }
    });

    vertx.setPeriodic(10000, tid -> {

        JsonObject msg = new JsonObject();
        msg.put("topic", "releases");
        msg.put("action", "default");

        JsonArray rel = new JsonArray();

        Iterator<Map.Entry<String, JsonObject>> iter = releasesData.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<String, JsonObject> entry = iter.next();
            rel.add(entry.getValue());
        }

        msg.put("data", rel);

        eb.publish("releases", msg);

    });

    // periodically expire old releases in the map
    vertx.setPeriodic(config().getInteger("check_expiry", 1000), res -> {
        // iterate over map, check dates for each, expire as needed

        Iterator<Map.Entry<String, JsonObject>> iter = releasesData.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<String, JsonObject> entry = iter.next();

            logger.debug("checking expiry on " + entry.getKey() + " v " + entry.getValue());

            // now
            LocalDateTime now = LocalDateTime.now();

            // then
            LocalDateTime then = LocalDateTime.parse(entry.getValue().getString("date"), formatter);

            // delta
            Long delta = now.toEpochSecond(ZoneOffset.UTC) - then.toEpochSecond(ZoneOffset.UTC);

            if (delta >= expire_timeout) {
                logger.info("expiring stale release: " + entry.getValue() + " delta: " + delta.toString());
                iter.remove();
            }

        }

    });

    // save the current pile of releases into a JSON periodically
    vertx.setPeriodic(config().getInteger("save_interval", 60000), t -> {
        saveState();
    });

    startFuture.complete();

}

From source file:com.deblox.releaseboard.ReleaseBoardVerticle.java

License:Apache License

public void saveState() {
    logger.info("saving state");
    JsonObject db = new JsonObject();
    JsonArray releases = new JsonArray();

    Iterator<Map.Entry<String, JsonObject>> iter = releasesData.entrySet().iterator();
    while (iter.hasNext()) {
        Map.Entry<String, JsonObject> entry = iter.next();
        JsonObject rel = new JsonObject();
        rel.put("id", entry.getKey());
        rel.put("data", entry.getValue());
        releases.add(rel);
    }//from www  .j  av  a2  s . com

    db.put("releases", releases);

    vertx.fileSystem().exists(stateFile, te -> {
        if (te.succeeded()) {
            if (te.result().booleanValue()) {
                vertx.fileSystem().deleteBlocking(stateFile);
                vertx.fileSystem().createFileBlocking(stateFile);
            } else {
                vertx.fileSystem().createFileBlocking(stateFile);
            }

        } else {
            logger.warn("unable to check if file exists: " + stateFile);
        }

        vertx.fileSystem().open(stateFile, new OpenOptions().setCreate(true).setWrite(true), r -> {
            if (r.succeeded()) {
                AsyncFile file = r.result();
                file.write(Buffer.buffer(db.toString()));
                file.close();
            } else {
                logger.warn(r.cause());
            }
        });

    });

}

From source file:com.emikra.vertx.oak.OakServiceVertxProxyHandler.java

License:Apache License

private Handler<AsyncResult<List<Character>>> createListCharHandler(Message msg) {
    return res -> {
        if (res.failed()) {
            msg.fail(-1, res.cause().getMessage());
        } else {//from ww w  .j  a  v  a  2 s . co m
            JsonArray arr = new JsonArray();
            for (Character chr : res.result()) {
                arr.add((int) chr);
            }
            msg.reply(arr);
        }
    };
}