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:de.fraunhofer.fokus.redistest.DoInterestingThings.java

License:Creative Commons License

public void doIt(final Vertx vertx, final JsonObject redisConfig, String uuid, Logger logger,
        Handler<AsyncResult<JsonArray>> handler) {
    String zSetName = String.format(ZSET_NAME_FORMAT, uuid);
    final RangeLimitOptions rangeLimitOptions = (RangeLimitOptions) new RangeLimitOptions().setLimit(0,
            Constants.MAX_SEARCH_RESULTS);

    /*/*from  w  w  w . j a  va  2 s.  c o  m*/
     * To prevent errors in streams due to empty result set and to enable subscription
     * a dummy element will be prepended to the result set and removed in the subscription
     */
    final List<JsonArray> secureResultList = new ArrayList<JsonArray>();
    secureResultList.add(new JsonArray().add("default"));

    Single.using(DisposableRedisConnection::new, f -> f.create(vertx, redisConfig, logger), f -> f.dispose())
            .subscribe(redisClient -> {
                // emulate searech time in database
                //               vertx.setTimer(40,  xx->{
                Observable.range(1, 40)
                        .map(x -> new JsonObject().put(Constants.KEY_TYPE, Constants.KEY_DICE_OBJECT)
                                .put(Constants.KEY_RECORD_ID, String.valueOf(x))
                                .put(Constants.KEY_DICE_VALUE, x * 0.1).put(Constants.KEY_FAMILYNAME, x * 0.1)
                                .put(Constants.KEY_FIRSTNAME, 1))
                        .filter(x -> x != null) //remove results where comparison has been stopped due to bad dice values
                        // side effect - store objects in redis   
                        .subscribe(res -> {
                            String handle = res.getString(Constants.KEY_RECORD_ID);
                            String hashName = String.format(HASH_NAME_FORMAT, handle);
                            Single.zip(
                                    redisClient.rxZadd(zSetName, res.getDouble(Constants.KEY_DICE_VALUE),
                                            handle),
                                    redisClient.rxExpire(hashName, Constants.EXPIRE_AFTER),
                                    redisClient.rxHmset(hashName, res), (a, b, c) -> {
                                        return res;
                                    }).subscribe(r -> {
                                        // do nothing
                                    }, t -> handler.handle(Future.failedFuture(t)));
                        }, t -> handler.handle(Future.failedFuture(t)), () -> { //set expiration and retrieve record_ids
                            Observable
                                    .zip(redisClient.rxExpire(zSetName, Constants.EXPIRE_AFTER).toObservable(), // set expiration
                                            redisClient
                                                    .rxZrevrangebyscore(zSetName, "1", "0", rangeLimitOptions)
                                                    .toObservable(), // list of record_ids as JsonArray
                                            (a, b) -> Observable.from(b))
                                    .flatMap(x -> x)
                                    .map(handle -> redisClient
                                            .rxHgetall(String.format(HASH_NAME_FORMAT, handle)).toObservable()) // retrieve hash from redis
                                    .flatMap(x -> x).map(json -> toEntry(json))
                                    .collect(() -> new JsonArray(), (eList, e) -> eList.add(e))
                                    .subscribe(collectedJson -> handler
                                            .handle(Future.succeededFuture(collectedJson)), t -> {
                                                System.out.println("XXXX: " + t);
                                                logger.error("XXX", t);
                                                handler.handle(Future.failedFuture(t));
                                            });
                            //                        });
                        });
            }, t -> {
                CharArrayWriter cw = new CharArrayWriter();
                PrintWriter w = new PrintWriter(cw);
                t.printStackTrace(w);
                w.close();
                logger.error("trace", cw.toString());
                logger.error("YYY", t);
                handler.handle(Future.failedFuture(t));
            });

}

From source file:de.fraunhofer.fokus.redistest.Dummy.java

License:Creative Commons License

public void dummy(Vertx vertx, Query query, Logger logger, Handler<AsyncResult<JsonArray>> handler) {
    vertx.setTimer(4, res -> {//from www  .java 2  s. c om
        handler.handle(Future.succeededFuture(new JsonArray()));
    });

}

From source file:de.neofonie.deployer.DeployerVerticle.java

License:Open Source License

/**
 * Start the deployer.//from  ww  w. ja v  a 2  s .  c  o  m
 *
 * @param startFuture
 */
@Override
public void start(final Future<Void> startFuture) {

    // load the deployer.json when available
    JsonObject configuration = this.loadConfiguration();

    if (configuration != null) {

        deployed = new JsonArray();

        // assign loopback to this handler
        vertx.eventBus().localConsumer(LOOPBACK, this::deployVerticle);

        // copy the current verticle configuration
        workingCopy = configuration.getJsonObject(VERTICLES, new JsonObject()).copy();

        // set the global configuration
        globalConfig = configuration.getJsonObject(CONFIG, new JsonObject());

        // start iterations
        vertx.eventBus().send(LOOPBACK, null, (AsyncResult<Message<Boolean>> event) -> {
            if (event.succeeded() && event.result().body()) {
                LOG.log(Level.INFO, "Deployed {0} Verticles: {1}",
                        new Object[] { this.deployed.size(), deployed });
                startFuture.complete();
            } else {
                LOG.log(Level.SEVERE, "Deployment stopped: {0}", event.cause().getMessage());
                startFuture.fail(event.cause());
            }
        });
    } else {
        LOG.info("No deployer.json found on the classpath.");
    }
}

From source file:docoverride.json.Examples.java

License:Open Source License

public void example3() {
    JsonArray array = new JsonArray();
    array.add("foo").add(123).add(false);
}

From source file:examples.AuthJDBCExamples.java

License:Open Source License

public void example9(JDBCAuth auth, SQLConnection conn) {

    String salt = auth.generateSalt();
    String hash = auth.computeHash("sausages", salt);
    // save to the database
    conn.updateWithParams("INSERT INTO user VALUES (?, ?, ?)", new JsonArray().add("tim").add(hash).add(salt),
            res -> {//from   ww  w.  j  a  va2  s  .  com
                if (res.succeeded()) {
                    // success!
                }
            });
}

From source file:examples.ConfigExamples.java

License:Apache License

public void env3() {
    ConfigStoreOptions json = new ConfigStoreOptions().setType("env")
            .setConfig(new JsonObject().put("keys", new JsonArray().add("SERVICE1_HOST").add("SERVICE2_HOST")));
}

From source file:examples.ConfigExamples.java

License:Apache License

public void dir() {
    ConfigStoreOptions dir = new ConfigStoreOptions().setType("directory")
            .setConfig(new JsonObject().put("path", "config").put("filesets",
                    new JsonArray().add(new JsonObject().put("pattern", "dir/*json")).add(
                            new JsonObject().put("pattern", "dir/*.properties").put("format", "properties"))));

    ConfigStoreOptions dirWithRawData = new ConfigStoreOptions().setType("directory")
            .setConfig(new JsonObject().put("path", "config").put("filesets",
                    new JsonArray().add(new JsonObject().put("pattern", "dir/*json"))
                            .add(new JsonObject().put("pattern", "dir/*.properties").put("format", "properties")
                                    .put("raw-data", true))));
}

From source file:examples.ConfigGitExamples.java

License:Apache License

public void example1(Vertx vertx) {

    ConfigStoreOptions git = new ConfigStoreOptions().setType("git")
            .setConfig(new JsonObject().put("url", "https://github.com/cescoffier/vertx-config-test.git")
                    .put("path", "local")
                    .put("filesets", new JsonArray().add(new JsonObject().put("pattern", "*.json"))));

    ConfigRetriever retriever = ConfigRetriever.create(vertx, new ConfigRetrieverOptions().addStore(git));
}

From source file:examples.MongoClientExamples.java

License:Open Source License

public void example12(MongoClient mongoClient) {
    JsonObject command = new JsonObject().put("aggregate", "collection_name").put("pipeline", new JsonArray());
    mongoClient.runCommand("aggregate", command, res -> {
        if (res.succeeded()) {
            JsonArray resArr = res.result().getJsonArray("result");
            // etc
        } else {/*www  .j  ava2 s  . com*/
            res.cause().printStackTrace();
        }
    });
}

From source file:fr.wseduc.rack.controllers.RackController.java

License:Open Source License

private void copyFiles(final HttpServerRequest request, final JsonArray idsArray, final String folder,
        final UserInfos user, final String destinationCollection) {

    String criteria = "{ \"_id\" : { \"$in\" : " + idsArray.encode() + "}";
    criteria += ", \"to\" : \"" + user.getUserId() + "\" }";

    mongo.find(collection, new JsonObject(criteria), new Handler<Message<JsonObject>>() {

        private void persist(final JsonArray insert, int remains) {
            if (remains == 0) {
                mongo.insert(destinationCollection, insert, new Handler<Message<JsonObject>>() {
                    @Override/*from www.  j  av  a2  s . co m*/
                    public void handle(Message<JsonObject> inserted) {
                        if ("ok".equals(inserted.body().getString("status"))) {
                            /* Increment quota */
                            long totalSize = 0l;
                            for (Object insertion : insert) {
                                JsonObject added = (JsonObject) insertion;
                                totalSize += added.getJsonObject("metadata", new JsonObject()).getLong("size",
                                        0l);
                            }
                            updateUserQuota(user.getUserId(), totalSize);
                            renderJson(request, inserted.body());
                        } else {
                            renderError(request, inserted.body());
                        }
                    }
                });
            }
        }

        @Override
        public void handle(Message<JsonObject> r) {
            JsonObject src = r.body();
            if ("ok".equals(src.getString("status")) && src.getJsonArray("results") != null) {
                final JsonArray origs = src.getJsonArray("results");
                final JsonArray insert = new JsonArray();
                final AtomicInteger number = new AtomicInteger(origs.size());

                emptySize(user, new Handler<Long>() {

                    @Override
                    public void handle(Long emptySize) {
                        long size = 0;

                        /* Get total file size */
                        for (Object o : origs) {
                            if (!(o instanceof JsonObject))
                                continue;
                            JsonObject metadata = ((JsonObject) o).getJsonObject("metadata");
                            if (metadata != null) {
                                size += metadata.getLong("size", 0l);
                            }
                        }
                        /* If total file size is too big (> quota left) */
                        if (size > emptySize) {
                            badRequest(request, "files.too.large");
                            return;
                        }

                        /* Process */
                        for (Object o : origs) {
                            JsonObject orig = (JsonObject) o;
                            final JsonObject dest = orig.copy();
                            String now = MongoDb.formatDate(new Date());
                            dest.remove("_id");
                            dest.remove("protected");
                            dest.remove("comments");
                            dest.put("application", WORKSPACE_NAME);

                            dest.put("owner", user.getUserId());
                            dest.put("ownerName", dest.getString("toName"));
                            dest.remove("to");
                            dest.remove("from");
                            dest.remove("toName");
                            dest.remove("fromName");

                            dest.put("created", now);
                            dest.put("modified", now);
                            if (folder != null && !folder.trim().isEmpty()) {
                                dest.put("folder", folder);
                            } else {
                                dest.remove("folder");
                            }
                            insert.add(dest);
                            final String filePath = orig.getString("file");

                            if (folder != null && !folder.trim().isEmpty()) {

                                //If the document has a new parent folder, replicate sharing rights
                                String parentName, parentFolder;
                                if (folder.lastIndexOf('_') < 0) {
                                    parentName = folder;
                                    parentFolder = folder;
                                } else if (filePath != null) {
                                    String[] splittedPath = folder.split("_");
                                    parentName = splittedPath[splittedPath.length - 1];
                                    parentFolder = folder;
                                } else {
                                    String[] splittedPath = folder.split("_");
                                    parentName = splittedPath[splittedPath.length - 2];
                                    parentFolder = folder.substring(0, folder.lastIndexOf("_"));
                                }

                                QueryBuilder parentFolderQuery = QueryBuilder.start("owner")
                                        .is(user.getUserId()).and("folder").is(parentFolder).and("name")
                                        .is(parentName);

                                mongo.findOne(collection, MongoQueryBuilder.build(parentFolderQuery),
                                        new Handler<Message<JsonObject>>() {
                                            @Override
                                            public void handle(Message<JsonObject> event) {
                                                if ("ok".equals(event.body().getString("status"))) {
                                                    JsonObject parent = event.body().getJsonObject("result");
                                                    if (parent != null && parent.getJsonArray("shared") != null
                                                            && parent.getJsonArray("shared").size() > 0)
                                                        dest.put("shared", parent.getJsonArray("shared"));

                                                    if (filePath != null) {
                                                        storage.copyFile(filePath, new Handler<JsonObject>() {
                                                            @Override
                                                            public void handle(JsonObject event) {
                                                                if (event != null && "ok"
                                                                        .equals(event.getString("status"))) {
                                                                    dest.put("file", event.getString("_id"));
                                                                    persist(insert, number.decrementAndGet());
                                                                }
                                                            }
                                                        });
                                                    } else {
                                                        persist(insert, number.decrementAndGet());
                                                    }
                                                } else {
                                                    renderJson(request, event.body(), 404);
                                                }
                                            }
                                        });

                            } else if (filePath != null) {
                                storage.copyFile(filePath, new Handler<JsonObject>() {

                                    @Override
                                    public void handle(JsonObject event) {
                                        if (event != null && "ok".equals(event.getString("status"))) {
                                            dest.put("file", event.getString("_id"));
                                            persist(insert, number.decrementAndGet());
                                        }
                                    }
                                });
                            } else {
                                persist(insert, number.decrementAndGet());
                            }
                        }
                    }
                });
            } else {
                notFound(request, src.toString());
            }
        }
    });

}