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

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

Introduction

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

Prototype

public JsonArray() 

Source Link

Document

Create an empty instance

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);/* w w  w .ja  v  a2 s.  com*/
            }
            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());//  w ww  . j  av a2 s.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: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());/*from w  ww.  j av a  2 s. 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:co.runrightfast.vertx.core.impl.VertxServiceImpl.java

License:Apache License

private Optional<JsonArray> toJsonObject(final List<Match> matches) {
    if (CollectionUtils.isEmpty(matches)) {
        return Optional.empty();
    }//from  w  w  w  . java 2 s . c om

    final JsonArray jsonArray = new JsonArray();
    matches.stream().map(match -> new JsonObject().put("value", match.getValue()).put("type", match.getType()))
            .forEach(jsonArray::add);

    return Optional.of(jsonArray);
}

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/*from w w  w  . j a  v  a 2s.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// www .  j  av a 2 s. com
 */
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

/**
 * Create a bulk metric object for sending to the OpenTsDb lib
 *
 * @param metric the first metric to put in the bulk requests
 * @return the properly constructed metric object
 *//*w w  w . j a  v a  2s.  c o  m*/
public static JsonObject createBulkMetric(JsonObject metric) {
    return new JsonObject().put(OpenTsDbService.ACTION_FIELD, OpenTsDbService.ADD_ALL_COMMAND)
            .put(MetricsParser.METRICS_FIELD, new JsonArray().add(metric));
}

From source file:com.deblox.Boot.java

License:Apache License

@Override
public void start(final Future<Void> startedResult) {

    logger.info("\n"
            + "                       ?                       \n"
            + "                                                            \n"
            + "                                     ?                              \n"
            + "                                                           \n"
            + "                                                          \n"
            + "                                  ?                                     \n"
            + "                                                                   \n"
            + "                                      1.0\n"
            + "                                                         https://github.com/unixunion/deblox-vertx-template                  \n");

    config = config();/*from w ww .j  ava 2 s  .  c o  m*/

    eb = vertx.eventBus();

    // warn a brother!
    if (config.equals(new JsonObject())) {
        logger.warn("you have no config here!");
    } else {
        logger.info("config: " + config);
    }

    // Start each class mentioned in services
    for (final Object serviceClassName : config.getJsonArray("services", new JsonArray())) {

        logger.info("deploying service: " + serviceClassName);

        // get the config for the named service
        JsonObject serviceConfigJson = config.getJsonObject(serviceClassName.toString(), new JsonObject());
        logger.info("serviceConfigJson: " + serviceConfigJson);

        // See DeploymentOptions.fromJson for all the possible configurables
        DeploymentOptions serviceConfig = new DeploymentOptions(serviceConfigJson);

        vertx.deployVerticle(serviceClassName.toString(), serviceConfig, res -> {

            if (res.succeeded()) {
                logger.info("successfully deployed service: " + serviceClassName);

            } else {
                logger.error("failure while deploying service: " + serviceClassName);
                res.cause().printStackTrace();
            }

        });

    }

    // for testing purposes, we need a litte delay since its less code than wait implement all verticles to boot.
    vertx.setTimer(1000, event -> {
        startedResult.complete();
        logger.info("startup complete");
    });

}

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

License:Apache License

/**
 * Start the verticle//from www . j  a  v a2  s.c  o 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();

}