Example usage for io.vertx.core.json JsonObject mergeIn

List of usage examples for io.vertx.core.json JsonObject mergeIn

Introduction

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

Prototype

public JsonObject mergeIn(JsonObject other) 

Source Link

Document

Merge in another JSON object.

Usage

From source file:com.ddp.SimpleREST.java

License:Open Source License

public static void main(String argv[]) {

    VertxOptions options = new VertxOptions().setBlockedThreadCheckInterval(200000000);
    options.setClustered(true);//from www  .  j a v  a  2 s  .  c o  m

    Vertx.clusteredVertx(options, res -> {
        if (res.succeeded()) {
            Vertx vertx = res.result();
            final JsonObject js = new JsonObject();
            vertx.fileSystem().readFile("app-conf.json", result -> {
                if (result.succeeded()) {
                    Buffer buff = result.result();
                    js.mergeIn(new JsonObject(buff.toString()));
                    initConfig(js);
                    DeploymentOptions deploymentOptions = new DeploymentOptions().setConfig(js)
                            .setMaxWorkerExecuteTime(5000).setWorker(true).setWorkerPoolSize(5);
                    vertx.deployVerticle(SimpleREST.class.getName(), deploymentOptions);
                } else {
                    System.err.println("Oh oh ..." + result.cause());
                }
            });

        }
    });
}

From source file:com.github.mcollovati.vertx.vaadin.VaadinVerticle.java

License:Open Source License

@Override
public void start(Future<Void> startFuture) throws Exception {
    log.info("Starting vaadin verticle " + getClass().getName());

    VaadinVerticleConfiguration vaadinVerticleConfiguration = getClass()
            .getAnnotation(VaadinVerticleConfiguration.class);

    JsonObject vaadinConfig = new JsonObject();
    vaadinConfig.put("serviceName", this.deploymentID());
    vaadinConfig.put("mountPoint", Optional.ofNullable(vaadinVerticleConfiguration)
            .map(VaadinVerticleConfiguration::mountPoint).orElse("/"));
    readUiFromEnclosingClass(vaadinConfig);
    readConfigurationAnnotation(vaadinConfig);
    vaadinConfig.mergeIn(config().getJsonObject("vaadin", new JsonObject()));

    String mountPoint = vaadinConfig.getString("mountPoint");
    VertxVaadin vertxVaadin = createVertxVaadin(vaadinConfig);
    vaadinService = vertxVaadin.vaadinService();

    HttpServerOptions serverOptions = new HttpServerOptions().setCompressionSupported(true);
    httpServer = vertx.createHttpServer(serverOptions);

    Router router = Router.router(vertx);
    router.mountSubRouter(mountPoint, vertxVaadin.router());

    httpServer.websocketHandler(vertxVaadin.webSocketHandler());
    httpServer.requestHandler(router::accept).listen(config().getInteger("httpPort", 8080));

    serviceInitialized(vaadinService, router);

    log.info("Started vaadin verticle " + getClass().getName());
    startFuture.complete();// w w  w  . j a va  2s  .co m
}

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

License:Open Source License

/**
 * Iterate and deploy verticles/*from  ww w. ja v  a2  s  .  co  m*/
 */
private void deployVerticle(final Message<JsonObject> event) {

    // iterate over all candidates to be deployed
    Set<String> candidates = this.workingCopy.fieldNames();

    // detach from underlying json
    Map<String, JsonObject> initiants = new HashMap<>();
    candidates.forEach(id -> {
        JsonObject info = this.workingCopy.getJsonObject(id);
        JsonArray dependsOn = info.getJsonArray("dependsOn");
        if (dependsOn != null && deployed.getList().containsAll(dependsOn.getList()) || dependsOn == null
                || dependsOn.isEmpty()) {
            initiants.put(id, info);
        }
    });

    // remove the initiants
    initiants.keySet().forEach(id -> this.workingCopy.remove(id));

    // setup latch for the reply
    CountDownLatch latch = new CountDownLatch(initiants.size());
    if (initiants.isEmpty()) {
        event.reply(Boolean.TRUE);
        return;
    }

    // run over all dependencies
    initiants.forEach((id, info) -> {

        // get the name of the verticle
        String name = info.getString("name");
        final JsonObject localConfig = new JsonObject();
        localConfig.mergeIn(globalConfig);
        localConfig.mergeIn(info.getJsonObject("config", new JsonObject()));

        Handler<AsyncResult<String>> handler = innerEvent -> {
            if (innerEvent.succeeded()) {
                // add service to deployed-list
                deployed.add(id);

                // re-emit
                vertx.eventBus().send(LOOPBACK, workingCopy, (AsyncResult<Message<Boolean>> recursiveReply) -> {
                    // always decrease latch
                    latch.countDown();

                    if (recursiveReply.succeeded() && recursiveReply.result().body()) {
                        if (latch.getCount() == 0) {
                            event.reply(recursiveReply.result().body() & Boolean.TRUE);
                        }
                    } else {
                        event.fail(500, this.getFailure(id, recursiveReply));
                    }
                });

            } else {
                event.fail(500, id + " >> " + innerEvent.cause().getMessage());
            }
        };

        LOG.log(Level.INFO, "Deploying: ''{0}''", new Object[] { id });
        DeploymentOptions deploymentOptions = new DeploymentOptions(info);
        vertx.deployVerticle(name, deploymentOptions.setConfig(localConfig), handler);
    });
}

From source file:io.knotx.launcher.KnotxModuleVerticleFactory.java

License:Apache License

@Override
public void resolve(String id, DeploymentOptions deploymentOptions, ClassLoader classLoader,
        Future<String> resolution) {
    String identifier = VerticleFactory.removePrefix(id);
    String descriptorFile = identifier + ".json";
    try {// www .j a v a  2  s .  com
        JsonObject descriptor = readDescriptor(classLoader, descriptorFile);
        String main = readVerticleMainClass(descriptor, descriptorFile);

        // Any options specified in the module config will override anything specified at deployment time
        // Options and Config specified in knotx starter JSON will override those configurations
        JsonObject depOptions = deploymentOptions.toJson();
        JsonObject depConfig = depOptions.getJsonObject(CONFIG_KEY, new JsonObject());

        JsonObject knotOptions = descriptor.getJsonObject(OPTIONS_KEY, new JsonObject());
        JsonObject knotConfig = knotOptions.getJsonObject(CONFIG_KEY, new JsonObject());
        depOptions.mergeIn(knotOptions);
        depOptions.put(CONFIG_KEY, JsonObjectUtil.deepMerge(knotConfig, depConfig));

        JsonObject serviceDescriptor = new JsonObject().put(OPTIONS_KEY, depOptions);

        // Any options or config provided by system properties will override anything specified
        // at deployment time and on starter Json config
        serviceDescriptor = overrideConfigWithSystemProperties(identifier, serviceDescriptor);

        deploymentOptions.fromJson(serviceDescriptor.getJsonObject(OPTIONS_KEY));
        resolution.complete(main);
    } catch (Exception e) {
        resolution.fail(e);
    }
}

From source file:io.nitor.api.backend.PropertiesLauncher.java

License:Apache License

@Override
public void beforeDeployingVerticle(DeploymentOptions deploymentOptions) {
    JsonObject conf = readDefaultsConf();
    JsonObject inputConf = deploymentOptions.getConfig();
    if (inputConf != null) {
        conf.mergeIn(inputConf);
    }/*from www  . j a v  a 2s  . c  om*/

    override(conf, "");
    deploymentOptions.setConfig(conf);
}

From source file:net.kuujo.vertigo.deployment.impl.LocalDeploymentManager.java

License:Apache License

@Override
public DeploymentManager deployNetwork(NetworkContext network, Handler<AsyncResult<Void>> doneHandler) {

    // Add to local map to make it accessible from the component.start() methods
    vertx.sharedData().<String, NetworkContext>getLocalMap(NETWORKS_KEY).put(network.name(), network);

    CountingCompletionHandler<Void> counter = new CountingCompletionHandler<Void>(network.components().size())
            .setHandler(result -> {//from   ww w  .ja v  a 2 s  . c o  m
                if (result.failed()) {
                    vertx.sharedData().<String, NetworkContext>getLocalMap(NETWORKS_KEY).remove(network.name());
                }
                doneHandler.handle(result);
            });

    for (ComponentContext component : network.components()) {

        JsonObject config = new JsonObject().put("vertigo_component_context", component.toJson());

        if (component.config() != null) {
            config.mergeIn(component.config());
        }

        DeploymentOptions options = new DeploymentOptions().setConfig(config).setWorker(component.worker())
                .setMultiThreaded(component.multiThreaded());

        vertx.deployVerticle(component.main(), options, result -> {
            if (result.failed()) {
                counter.fail(result.cause());
            } else {
                vertx.sharedData().<String, String>getLocalMap(network.name()).put(component.address(),
                        result.result());
                counter.succeed();
            }
        });
    }
    return this;
}

From source file:net.kuujo.vertigo.VertigoOptions.java

License:Apache License

public VertigoOptions(JsonObject options) {
    super(options);
    options.mergeIn(Configs.load());
}

From source file:org.entcore.common.events.impl.GenericEventStore.java

License:Open Source License

private JsonObject generateEvent(String eventType, UserInfos user, HttpServerRequest request,
        JsonObject customAttributes) {/* w w w  .  j  a  va  2  s. com*/
    JsonObject event = new JsonObject();
    if (customAttributes != null && customAttributes.size() > 0) {
        event.mergeIn(customAttributes);
    }
    event.put("event-type", eventType).put("module", module).put("date", System.currentTimeMillis());
    if (user != null) {
        event.put("userId", user.getUserId()).put("profil", user.getType());
        if (user.getStructures() != null) {
            event.put("structures", new fr.wseduc.webutils.collections.JsonArray(user.getStructures()));
        }
        if (user.getClasses() != null) {
            event.put("classes", new fr.wseduc.webutils.collections.JsonArray(user.getClasses()));
        }
        if (user.getGroupsIds() != null) {
            event.put("groups", new fr.wseduc.webutils.collections.JsonArray(user.getGroupsIds()));
        }
    }
    if (request != null) {
        event.put("referer", request.headers().get("Referer"));
        event.put("sessionId", CookieHelper.getInstance().getSigned("oneSessionId", request));
    }
    return event;
}

From source file:org.entcore.common.neo4j.Neo4jResult.java

License:Open Source License

public static Either<String, JsonObject> fullNodeMerge(String nodeAttr, Message<JsonObject> res,
        String... otherNodes) {/*from  w  w  w . j a  va  2  s .co  m*/
    Either<String, JsonObject> r = validUniqueResult(res);
    if (r.isRight() && r.right().getValue().size() > 0) {
        JsonObject j = r.right().getValue();
        JsonObject data = j.getJsonObject(nodeAttr, new JsonObject()).getJsonObject("data");
        if (otherNodes != null && otherNodes.length > 0) {
            for (String attr : otherNodes) {
                Object e = j.getValue(attr);
                if (e == null)
                    continue;
                if (e instanceof JsonObject) {
                    data.put(attr, ((JsonObject) e).getJsonObject("data"));
                } else if (e instanceof JsonArray) {
                    JsonArray a = new fr.wseduc.webutils.collections.JsonArray();
                    for (Object o : (JsonArray) e) {
                        if (!(o instanceof JsonObject))
                            continue;
                        JsonObject jo = (JsonObject) o;
                        a.add(jo.getJsonObject("data"));
                    }
                    data.put(attr, a);
                }
                j.remove(attr);
            }
        }
        if (data != null) {
            j.remove(nodeAttr);
            return new Either.Right<>(data.mergeIn(j));
        }
    }
    return r;
}

From source file:org.entcore.communication.services.impl.DefaultCommunicationService.java

License:Open Source License

@Override
public void visibleUsers(String userId, String structureId, JsonArray expectedTypes, boolean itSelf,
        boolean myGroup, boolean profile, String preFilter, String customReturn, JsonObject additionnalParams,
        String userProfile, final Handler<Either<String, JsonArray>> handler) {
    StringBuilder query = new StringBuilder();
    JsonObject params = new JsonObject();
    String condition = itSelf ? "" : "AND m.id <> {userId} ";
    StringBuilder union = null;//from   w  w w.  j  av  a2  s.  c o  m
    String conditionUnion = itSelf ? "" : "AND m.id <> {userId} ";
    if (structureId != null && !structureId.trim().isEmpty()) {
        query.append("MATCH (n:User)-[:COMMUNIQUE*1..3]->m-[:DEPENDS*1..2]->(s:Structure {id:{schoolId}})"); //TODO manage leaf
        params.put("schoolId", structureId);
    } else {
        String l = (myGroup) ? " (length(p) >= 2 OR m.users <> 'INCOMING')" : " length(p) >= 2";
        query.append(
                " MATCH p=(n:User)-[:COMMUNIQUE*0..2]->ipg" + "-[:COMMUNIQUE*0..1]->g<-[:DEPENDS*0..1]-m ");
        condition += "AND ((" + l
                + " AND (length(p) < 3 OR (ipg:Group AND (m:User OR g<-[:DEPENDS]-m) AND length(p) = 3)))) ";
        if (userProfile == null || "Student".equals(userProfile) || "Relative".equals(userProfile)) {
            union = new StringBuilder("MATCH p=(n:User)-[:COMMUNIQUE_DIRECT]->m "
                    + "WHERE n.id = {userId} AND (NOT(HAS(m.blocked)) OR m.blocked = false) ");
        }
    }
    query.append("WHERE n.id = {userId} AND (NOT(HAS(m.blocked)) OR m.blocked = false) ");
    if (preFilter != null) {
        query.append(preFilter);
        if (union != null) {
            union.append(preFilter);
            union.append(conditionUnion);
        }
    }
    query.append(condition);
    if (expectedTypes != null && expectedTypes.size() > 0) {
        query.append("AND (");
        StringBuilder types = new StringBuilder();
        for (Object o : expectedTypes) {
            if (!(o instanceof String))
                continue;
            String t = (String) o;
            types.append(" OR m:").append(t);
        }
        query.append(types.substring(4)).append(") ");
        if (union != null) {
            union.append("AND (").append(types.substring(4)).append(") ");
        }
    }
    String pcr = " ";
    String pr = "";
    if (profile) {
        query.append(
                "OPTIONAL MATCH m-[:IN*0..1]->pgp-[:DEPENDS*0..1]->(pg:ProfileGroup)-[:HAS_PROFILE]->(profile:Profile) ");
        pcr = ", profile ";
        pr = "profile.name as type, ";
        if (union != null) {
            union.append(
                    "OPTIONAL MATCH m-[:IN*0..1]->pgp-[:DEPENDS*0..1]->(pg:ProfileGroup)-[:HAS_PROFILE]->(profile:Profile) ");
        }
    }
    if (customReturn != null && !customReturn.trim().isEmpty()) {
        query.append("WITH DISTINCT m as visibles").append(pcr);
        query.append(customReturn);
        if (union != null) {
            union.append("WITH DISTINCT m as visibles").append(pcr);
            union.append(customReturn);
        }
    } else {
        query.append("RETURN distinct m.id as id, m.name as name, "
                + "m.login as login, m.displayName as username, ").append(pr)
                .append("m.lastName as lastName, m.firstName as firstName, m.profiles as profiles "
                        + "ORDER BY name, username ");
        if (union != null) {
            union.append("RETURN distinct m.id as id, m.name as name, "
                    + "m.login as login, m.displayName as username, ").append(pr)
                    .append("m.lastName as lastName, m.firstName as firstName, m.profiles as profiles "
                            + "ORDER BY name, username ");
        }
    }
    params.put("userId", userId);
    if (additionnalParams != null) {
        params.mergeIn(additionnalParams);
    }
    String q;
    if (union != null) {
        q = query.append(" union ").append(union.toString()).toString();
    } else {
        q = query.toString();
    }
    neo4j.execute(q, params, validResultHandler(handler));
}