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

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

Introduction

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

Prototype

public JsonObject getJsonObject(String key) 

Source Link

Document

Get the JsonObject value with the specified key

Usage

From source file:org.entcore.directory.controllers.UserBookController.java

License:Open Source License

private void getUserPrefs(final UserInfos user, final HttpServerRequest request, final String application,
        final Handler<Either<String, JsonObject>> handler) {
    if (user != null) {
        UserUtils.getSession(eb, request, new Handler<JsonObject>() {
            public void handle(JsonObject session) {
                final JsonObject cache = session.getJsonObject("cache");

                if (cache.containsKey("preferences")) {
                    handler.handle(new Either.Right<String, JsonObject>(new JsonObject().put("preference",
                            cache.getJsonObject("preferences").getString(application))));
                } else {
                    refreshPreferences(user, request, new Handler<Either<String, JsonObject>>() {
                        public void handle(Either<String, JsonObject> event) {
                            if (event.isLeft()) {
                                log.error(event.left().getValue());
                                handler.handle(
                                        new Either.Left<String, JsonObject>("refresh.preferences.failed"));
                            } else {
                                handler.handle(new Either.Right<String, JsonObject>(new JsonObject()
                                        .put("preference", event.right().getValue().getString(application))));
                            }/*from   www .  j av  a 2 s. co  m*/
                        }
                    });
                }
            }
        });
    } else {
        handler.handle(new Either.Left<String, JsonObject>("bad.user"));
    }
}

From source file:org.entcore.directory.controllers.UserBookController.java

License:Open Source License

@Put("/preference/:application")
@SecuredAction(value = "user.preference", type = ActionType.AUTHENTICATED)
public void updatePreference(final HttpServerRequest request) {
    UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() {
        @Override/*  w ww .  j a  v  a2  s.c  om*/
        public void handle(final UserInfos user) {
            if (user != null) {
                final JsonObject params = new JsonObject().put("userId", user.getUserId());
                final String application = request.params().get("application").replaceAll("\\W+", "");
                request.bodyHandler(new Handler<Buffer>() {
                    @Override
                    public void handle(Buffer body) {
                        params.put("conf", body.toString("UTF-8"));
                        String query = "MATCH (u:User {id:{userId}})"
                                + "MERGE (u)-[:PREFERS]->(uac:UserAppConf)" + " ON CREATE SET uac."
                                + application + " = {conf}" + " ON MATCH SET uac." + application + " = {conf}";
                        neo.execute(query, params,
                                validUniqueResultHandler(new Handler<Either<String, JsonObject>>() {
                                    @Override
                                    public void handle(Either<String, JsonObject> result) {
                                        if (result.isRight()) {
                                            renderJson(request, result.right().getValue());

                                            UserUtils.getSession(eb, request, new Handler<JsonObject>() {
                                                public void handle(JsonObject session) {
                                                    final JsonObject cache = session.getJsonObject("cache");

                                                    if (cache.containsKey("preferences")) {
                                                        JsonObject prefs = cache.getJsonObject("preferences");
                                                        prefs.put(application, params.getString("conf"));
                                                        if ("theme".equals(application)) {
                                                            prefs.remove(THEME_ATTRIBUTE + getHost(request));
                                                        }
                                                        UserUtils.addSessionAttribute(eb, user.getUserId(),
                                                                "preferences", prefs, new Handler<Boolean>() {
                                                                    public void handle(Boolean event) {
                                                                        UserUtils.removeSessionAttribute(eb,
                                                                                user.getUserId(),
                                                                                THEME_ATTRIBUTE
                                                                                        + getHost(request),
                                                                                null);
                                                                        if (!event)
                                                                            log.error(
                                                                                    "Could not add preferences attribute to session.");
                                                                    }
                                                                });
                                                    }
                                                }
                                            });
                                        } else {
                                            leftToResponse(request, result.left());
                                        }
                                    }
                                }));
                    }
                });
            } else {
                badRequest(request);
            }
        }
    });
}

From source file:org.entcore.directory.services.impl.DefaultTimetableService.java

License:Open Source License

@Override
public void updateClassesMapping(final String structureId, final JsonObject mapping,
        final Handler<Either<String, JsonObject>> handler) {

    classesMapping(structureId, new Handler<Either<String, JsonObject>>() {
        @Override//from   ww  w  .  ja  v  a2  s  .  com
        public void handle(Either<String, JsonObject> event) {
            if (event.isRight()) {
                final JsonObject cm = event.right().getValue();
                if (cm == null || cm.getJsonArray("unknownClasses") == null) {
                    handler.handle(new Either.Left<String, JsonObject>("missing.classes.mapping"));
                    return;
                }
                final JsonArray uc = cm.getJsonArray("unknownClasses");
                final JsonObject m = mapping.getJsonObject("mapping");
                for (String attr : m.copy().fieldNames()) {
                    if (!uc.contains(attr)) {
                        m.remove(attr);
                    }
                }
                mapping.put("mapping", m.encode());
                final String query = "MATCH (:Structure {id:{id}})<-[:MAPPING]-(cm:ClassesMapping) "
                        + "SET cm.mapping = {mapping} ";
                neo4j.execute(query, mapping.put("id", structureId), validEmptyHandler(handler));
            } else {
                handler.handle(event);
            }
        }
    });
}

From source file:org.entcore.feeder.csv.CsvImportsLauncher.java

License:Open Source License

public CsvImportsLauncher(Vertx vertx, String path, JsonObject config, PostImport postImport) {
    this.vertx = vertx;
    this.path = path;
    this.profiles = config.getJsonObject("profiles");
    this.namePattern = Pattern.compile(config.getString("namePattern"));
    this.postImport = postImport;
    this.preDelete = config.getBoolean("preDelete", false);
}

From source file:org.entcore.feeder.dictionary.structures.DuplicateUsers.java

License:Open Source License

public void autoMergeDuplicatesInStructure(final Handler<AsyncResult<JsonArray>> handler) {
    final Handler<JsonObject> duplicatesHandler = new Handler<JsonObject>() {
        @Override/* w  w  w .  j a  v  a  2  s.c  om*/
        public void handle(JsonObject duplicatesRes) {
            JsonArray res = duplicatesRes.getJsonArray("result");
            if ("ok".equals(duplicatesRes.getString("status")) && res != null && res.size() > 0) {
                try {
                    final TransactionHelper tx = TransactionManager.getTransaction();
                    final AtomicInteger count = new AtomicInteger(res.size());
                    final Handler<JsonObject> mergeHandler = new Handler<JsonObject>() {
                        @Override
                        public void handle(JsonObject event) {
                            decrementCount(count, tx);
                        }
                    };
                    for (Object o : res) {
                        if (!(o instanceof JsonObject)) {
                            decrementCount(count, tx);
                            continue;
                        }
                        JsonObject j = (JsonObject) o;
                        JsonObject u1 = j.getJsonObject("user1");
                        JsonObject u2 = j.getJsonObject("user2");
                        if (u1 != null && u2 != null) {
                            mergeDuplicate(new ResultMessage(mergeHandler).put("userId1", u1.getString("id"))
                                    .put("userId2", u2.getString("id")), tx);
                            log.info("AutoMerge duplicates - u1 : " + u1.encode() + ", u2 : " + u2.encode());
                        } else {
                            decrementCount(count, tx);
                        }
                    }
                } catch (TransactionException e) {
                    log.error("Error in automerge transaction", e);
                    handler.handle(new DefaultAsyncResult<JsonArray>(e));
                }
            } else {
                log.info("No duplicates automatically mergeable.");
                handler.handle(new DefaultAsyncResult<>(new fr.wseduc.webutils.collections.JsonArray()));
            }
        }

        private void decrementCount(AtomicInteger count, TransactionHelper tx) {
            if (count.decrementAndGet() == 0) {
                tx.commit(new Handler<Message<JsonObject>>() {
                    @Override
                    public void handle(Message<JsonObject> event) {
                        if ("ok".equals(event.body().getString("status"))) {
                            if (updateCourses) {
                                AbstractTimetableImporter
                                        .updateMergedUsers(event.body().getJsonArray("results"));
                            }
                            handler.handle(new DefaultAsyncResult<>(event.body().getJsonArray("results")));
                        } else {
                            log.error("Error in automerge duplicates transaction : "
                                    + event.body().getString("message"));
                            handler.handle(new DefaultAsyncResult<JsonArray>(
                                    new TransactionException(event.body().getString("message"))));
                        }
                    }
                });
            }
        }
    };
    listDuplicates(new ResultMessage(duplicatesHandler).put("minScore", 5)
            .put("inSameStructure", autoMergeOnlyInSameStructure).put("inherit", false));
}

From source file:org.entcore.feeder.dictionary.structures.GraphData.java

License:Open Source License

static void loadData(final Neo4j neo4j, final Handler<Message<JsonObject>> handler) {
    String query = "MATCH (s:Structure) " + "OPTIONAL MATCH s<-[:DEPENDS]-(g:Group) "
            + "OPTIONAL MATCH s<-[:BELONGS]-(c:Class) "
            + "return s, collect(distinct g.externalId) as groups, collect(distinct c.externalId) as classes ";
    neo4j.execute(query, new JsonObject(), new Handler<Message<JsonObject>>() {
        @Override//w  ww .ja v  a  2  s.c o  m
        public void handle(Message<JsonObject> message) {
            String query = "MATCH (p:Profile) " + "OPTIONAL MATCH p<-[:COMPOSE]-(f:Function) "
                    + "return p, collect(distinct f.externalId) as functions ";
            final AtomicInteger count = new AtomicInteger(2);
            neo4j.execute(query, new JsonObject(), new Handler<Message<JsonObject>>() {
                @Override
                public void handle(Message<JsonObject> message) {
                    JsonArray res = message.body().getJsonArray("result");
                    if ("ok".equals(message.body().getString("status")) && res != null) {
                        for (Object o : res) {
                            if (!(o instanceof JsonObject))
                                continue;
                            JsonObject r = (JsonObject) o;
                            JsonObject p = r.getJsonObject("p", new JsonObject()).getJsonObject("data");
                            profiles.putIfAbsent(p.getString("externalId"),
                                    new Profile(p, r.getJsonArray("functions")));
                        }
                    }
                    if (handler != null && count.decrementAndGet() == 0) {
                        handler.handle(message);
                    }
                }
            });
            JsonArray res = message.body().getJsonArray("result");
            if ("ok".equals(message.body().getString("status")) && res != null) {
                for (Object o : res) {
                    if (!(o instanceof JsonObject))
                        continue;
                    JsonObject r = (JsonObject) o;
                    JsonObject s = r.getJsonObject("s", new JsonObject()).getJsonObject("data");
                    Structure structure = new Structure(s, r.getJsonArray("groups"), r.getJsonArray("classes"));
                    String externalId = s.getString("externalId");
                    structures.putIfAbsent(externalId, structure);
                    String UAI = s.getString("UAI");
                    if (UAI != null && !UAI.trim().isEmpty()) {
                        structuresByUAI.putIfAbsent(UAI, structure);
                    }
                    JsonArray joinKeys = s.getJsonArray("joinKey");
                    if (joinKeys != null && joinKeys.size() > 0) {
                        for (Object key : joinKeys) {
                            externalIdMapping.putIfAbsent(key.toString(), externalId);
                        }
                    }
                }
            }
            if (handler != null && count.decrementAndGet() == 0) {
                handler.handle(message);
            }
        }
    });
}

From source file:org.entcore.feeder.dictionary.structures.PostImport.java

License:Open Source License

private void wsCall(JsonObject object) {
    for (String url : object.fieldNames()) {
        final JsonArray endpoints = object.getJsonArray(url);
        if (endpoints == null || endpoints.size() < 1)
            continue;
        try {/*from www.j av a2  s .c om*/
            final URI uri = new URI(url);
            HttpClientOptions options = new HttpClientOptions().setDefaultHost(uri.getHost())
                    .setDefaultPort(uri.getPort()).setMaxPoolSize(16).setSsl("https".equals(uri.getScheme()))
                    .setConnectTimeout(10000).setKeepAlive(false);
            final HttpClient client = vertx.createHttpClient(options);

            final Handler[] handlers = new Handler[endpoints.size() + 1];
            handlers[handlers.length - 1] = new Handler<Void>() {
                @Override
                public void handle(Void v) {
                    client.close();
                }
            };
            for (int i = endpoints.size() - 1; i >= 0; i--) {
                final int ji = i;
                handlers[i] = new Handler<Void>() {
                    @Override
                    public void handle(Void v) {
                        final JsonObject j = endpoints.getJsonObject(ji);
                        logger.info("endpoint : " + j.encode());
                        final HttpClientRequest req = client.request(HttpMethod.valueOf(j.getString("method")),
                                j.getString("uri"), new Handler<HttpClientResponse>() {
                                    @Override
                                    public void handle(HttpClientResponse resp) {
                                        if (resp.statusCode() >= 300) {
                                            logger.warn("Endpoint " + j.encode() + " error : "
                                                    + resp.statusCode() + " " + resp.statusMessage());
                                        }
                                        handlers[ji + 1].handle(null);
                                    }
                                });
                        JsonObject headers = j.getJsonObject("headers");
                        if (headers != null && headers.size() > 0) {
                            for (String h : headers.fieldNames()) {
                                req.putHeader(h, headers.getString(h));
                            }
                        }
                        req.exceptionHandler(
                                e -> logger.error("Error in ws call post import : " + j.encode(), e));
                        if (j.getString("body") != null) {
                            req.end(j.getString("body"));
                        } else {
                            req.end();
                        }
                    }
                };
            }
            handlers[0].handle(null);
        } catch (URISyntaxException e) {
            logger.error("Invalid uri in ws call after import : " + url, e);
        }
    }
}

From source file:org.entcore.feeder.Feeder.java

License:Open Source License

@Override
public void start() {
    super.start();
    String node = (String) vertx.sharedData().getLocalMap("server").get("node");
    if (node == null) {
        node = "";
    }//ww w. j  a va  2  s  .c o m
    String neo4jConfig = (String) vertx.sharedData().getLocalMap("server").get("neo4jConfig");
    if (neo4jConfig != null) {
        neo4j = Neo4j.getInstance();
        neo4j.init(vertx, new JsonObject(neo4jConfig));
    }
    MongoDb.getInstance().init(vertx.eventBus(), node + "wse.mongodb.persistor");
    TransactionManager.getInstance().setNeo4j(neo4j);
    EventStoreFactory.getFactory().setVertx(vertx);
    defaultFeed = config.getString("feeder", "AAF");
    feeds.put("AAF", new AafFeeder(vertx, getFilesDirectory("AAF")));
    feeds.put("AAF1D", new Aaf1dFeeder(vertx, getFilesDirectory("AAF1D")));
    feeds.put("CSV", new CsvFeeder(vertx, config.getJsonObject("csvMappings", new JsonObject())));
    final long deleteUserDelay = config.getLong("delete-user-delay", 90 * 24 * 3600 * 1000l);
    final long preDeleteUserDelay = config.getLong("pre-delete-user-delay", 90 * 24 * 3600 * 1000l);
    final String deleteCron = config.getString("delete-cron", "0 0 2 * * ? *");
    final String preDeleteCron = config.getString("pre-delete-cron", "0 0 3 * * ? *");
    final String importCron = config.getString("import-cron");
    final JsonObject imports = config.getJsonObject("imports");
    final JsonObject preDelete = config.getJsonObject("pre-delete");
    final TimelineHelper timeline = new TimelineHelper(vertx, eb, config);
    try {
        new CronTrigger(vertx, deleteCron).schedule(new User.DeleteTask(deleteUserDelay, eb, vertx));
        if (preDelete != null) {
            if (preDelete.size() == ManualFeeder.profiles.size()
                    && ManualFeeder.profiles.keySet().containsAll(preDelete.fieldNames())) {
                for (String profile : preDelete.fieldNames()) {
                    final JsonObject profilePreDelete = preDelete.getJsonObject(profile);
                    if (profilePreDelete == null || profilePreDelete.getString("cron") == null
                            || profilePreDelete.getLong("delay") == null)
                        continue;
                    new CronTrigger(vertx, profilePreDelete.getString("cron")).schedule(
                            new User.PreDeleteTask(profilePreDelete.getLong("delay"), profile, timeline));
                }
            }
        } else {
            new CronTrigger(vertx, preDeleteCron)
                    .schedule(new User.PreDeleteTask(preDeleteUserDelay, timeline));
        }
        if (imports != null) {
            if (feeds.keySet().containsAll(imports.fieldNames())) {
                for (String f : imports.fieldNames()) {
                    final JsonObject i = imports.getJsonObject(f);
                    if (i != null && i.getString("cron") != null) {
                        new CronTrigger(vertx, i.getString("cron"))
                                .schedule(new ImporterTask(vertx, f, i.getBoolean("auto-export", false),
                                        config.getLong("auto-export-delay", 1800000l)));
                    }
                }
            } else {
                logger.error("Invalid imports configuration.");
            }
        } else if (importCron != null && !importCron.trim().isEmpty()) {
            new CronTrigger(vertx, importCron).schedule(new ImporterTask(vertx, defaultFeed,
                    config.getBoolean("auto-export", false), config.getLong("auto-export-delay", 1800000l)));
        }
    } catch (ParseException e) {
        logger.fatal(e.getMessage(), e);
        vertx.close();
        return;
    }
    Validator.initLogin(neo4j, vertx);
    manual = new ManualFeeder(neo4j);
    duplicateUsers = new DuplicateUsers(config.getBoolean("timetable", true),
            config.getBoolean("autoMergeOnlyInSameStructure", true), vertx.eventBus());
    postImport = new PostImport(vertx, duplicateUsers, config);
    vertx.eventBus().localConsumer(config.getString("address", FEEDER_ADDRESS), this);
    switch (config.getString("exporter", "")) {
    case "ELIOT":
        exporter = new EliotExporter(config.getString("export-path", "/tmp"),
                config.getString("export-destination"), config.getBoolean("concat-export", false),
                config.getBoolean("delete-export", true), vertx);
        break;
    }
    final JsonObject edt = config.getJsonObject("edt");
    if (edt != null) {
        final String pronotePrivateKey = edt.getString("pronote-private-key");
        if (isNotEmpty(pronotePrivateKey)) {
            edtUtils = new EDTUtils(vertx, pronotePrivateKey,
                    config.getString("pronote-partner-name", "NEO-Open"));
            final String edtPath = edt.getString("path");
            final String edtCron = edt.getString("cron");
            if (isNotEmpty(edtPath) && isNotEmpty(edtCron)) {
                try {
                    new CronTrigger(vertx, edtCron).schedule(new ImportsLauncher(vertx, edtPath, postImport,
                            edtUtils, config.getBoolean("udt-user-creation", true)));
                } catch (ParseException e) {
                    logger.error("Error in cron edt", e);
                }
            }
        }
    }
    final JsonObject udt = config.getJsonObject("udt");
    if (udt != null) {
        final String udtPath = udt.getString("path");
        final String udtCron = udt.getString("cron");
        if (isNotEmpty(udtPath) && isNotEmpty(udtCron)) {
            try {
                new CronTrigger(vertx, udtCron).schedule(new ImportsLauncher(vertx, udtPath, postImport,
                        edtUtils, config.getBoolean("udt-user-creation", true)));
            } catch (ParseException e) {
                logger.error("Error in cron udt", e);
            }
        }
    }
    final JsonObject csv = config.getJsonObject("csv");
    if (csv != null) {
        final String csvPath = csv.getString("path");
        final String csvCron = csv.getString("cron");
        final JsonObject csvConfig = csv.getJsonObject("config");
        if (isNotEmpty(csvPath) && isNotEmpty(csvCron) && csvConfig != null) {
            try {
                new CronTrigger(vertx, csvCron)
                        .schedule(new CsvImportsLauncher(vertx, csvPath, csvConfig, postImport));
            } catch (ParseException e) {
                logger.error("Error in cron csv", e);
            }
        }
    }
    I18n.getInstance().init(vertx);
}

From source file:org.entcore.feeder.Feeder.java

License:Open Source License

private String getFilesDirectory(String feeder) {
    JsonObject imports = config.getJsonObject("imports");
    if (imports != null && imports.getJsonObject(feeder) != null
            && imports.getJsonObject(feeder).getString("files") != null) {
        return imports.getJsonObject(feeder).getString("files");
    }/*from w  w  w. jav a2  s  . c o  m*/
    return config.getString("import-files");
}

From source file:org.entcore.feeder.utils.Report.java

License:Open Source License

private JsonObject cloneAndFilterResults(Optional<String> prefixAcademy) {
    JsonObject results = this.result.copy();
    if (prefixAcademy.isPresent()) {
        // filter each ignored object by externalId starting with academy name
        String prefix = prefixAcademy.get();
        JsonObject ignored = results.getJsonObject("ignored");
        Set<String> domains = ignored.fieldNames();
        for (String domain : domains) {
            JsonArray filtered = ignored.getJsonArray(domain, new JsonArray()).stream().filter(ig -> {
                if (ig instanceof JsonObject && ((JsonObject) ig).containsKey("object")) {
                    JsonObject object = ((JsonObject) ig).getJsonObject("object");
                    String externalId = object.getString("externalId");
                    return StringUtils.startsWithIgnoreCase(externalId, prefix);
                } else {
                    // keep in list because it is not a concerned object
                    return true;
                }//  w w w .jav  a2s.co m
            }).collect(JsonArray::new, JsonArray::add, JsonArray::addAll);//
            ignored.put(domain, filtered);
        }
        // userExternalIds FIltered
        JsonArray usersExternalIdsFiltered = results.getJsonArray("usersExternalIds", new JsonArray()).stream()
                .filter(value -> {
                    return (value instanceof String
                            && StringUtils.startsWithIgnoreCase((String) value, prefix));
                }).collect(JsonArray::new, JsonArray::add, JsonArray::addAll);//
        results.put("usersExternalIds", usersExternalIdsFiltered);
    }
    return results;
}