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

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

Introduction

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

Prototype

public String encode() 

Source Link

Document

Encode this JSON object as a string.

Usage

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

License:Open Source License

@Override
public void sendUserCreatedEmail(final HttpServerRequest request, String userId,
        final Handler<Either<String, Boolean>> result) {
    String query = "MATCH (u:`User` { id : {id}}) WHERE NOT(u.email IS NULL) AND NOT(u.activationCode IS NULL) "
            + "RETURN u.login as login, u.email as email, u.activationCode as activationCode ";
    JsonObject params = new JsonObject().put("id", userId);
    neo.execute(query, params, new Handler<Message<JsonObject>>() {
        @Override/*w w  w. j  a  v  a  2  s  .  com*/
        public void handle(Message<JsonObject> m) {
            Either<String, JsonObject> r = validUniqueResult(m);
            if (r.isRight()) {
                JsonObject j = r.right().getValue();
                String email = j.getString("email");
                String login = j.getString("login");
                String activationCode = j.getString("activationCode");
                if (email == null || login == null || activationCode == null || email.trim().isEmpty()
                        || login.trim().isEmpty() || activationCode.trim().isEmpty()) {
                    result.handle(new Either.Left<String, Boolean>("user.invalid.values"));
                    return;
                }
                JsonObject json = new JsonObject()
                        .put("activationUri",
                                notification.getHost(request) + "/auth/activation?login=" + login
                                        + "&activationCode=" + activationCode)
                        .put("host", notification.getHost(request)).put("login", login);
                logger.debug(json.encode());
                notification.sendEmail(request, email, null, null, "email.user.created.info",
                        "email/userCreated.html", json, true, new Handler<AsyncResult<Message<JsonObject>>>() {

                            @Override
                            public void handle(AsyncResult<Message<JsonObject>> ar) {
                                if (ar.succeeded()) {
                                    result.handle(new Either.Right<String, Boolean>(true));
                                } else {
                                    result.handle(new Either.Left<String, Boolean>(ar.cause().getMessage()));
                                }
                            }
                        });
            } else {
                result.handle(new Either.Left<String, Boolean>(r.left().getValue()));
            }
        }
    });
}

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

License:Open Source License

private void findUsers(final String path, final String profile, List<String> columns, int eii,
        final String charset, final Handler<JsonObject> handler) {
    mappingFinder.findExternalIds(structureId, path, profile, columns, eii, charset, new Handler<JsonArray>() {
        @Override//from  w w w. j a v  a 2 s  . com
        public void handle(JsonArray errors) {
            if (errors.size() > 0) {
                for (Object o : errors) {
                    if (!(o instanceof JsonObject))
                        continue;
                    JsonObject j = (JsonObject) o;
                    JsonArray p = j.getJsonArray("params");
                    log.info(j.encode());
                    if (p != null && p.size() > 0) {
                        addErrorByFile(profile, j.getString("key"), p.encode()
                                .substring(1, p.encode().length() - 1).replaceAll("\"", "").split(","));
                    } else if (j.getString("key") != null) {
                        addError(profile, j.getString("key"));
                    } else {
                        addError(profile, "mapping.unknown.error");
                    }
                }
                handler.handle(result);
            } else {
                //validateFile(path, profile, columns, null, handler);
                checkFile(path, profile, charset, handler);
            }
        }
    });
}

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

License:Open Source License

private void mergeDuplicate(final JsonObject r, final Message<JsonObject> message, final TransactionHelper tx) {
    final String source1 = r.getString("source1");
    final String source2 = r.getString("source2");
    final boolean activatedU1 = r.getBoolean("activatedU1", false);
    final boolean activatedU2 = r.getBoolean("activatedU2", false);
    final String userId1 = r.getString("userId1");
    final String userId2 = r.getString("userId2");
    final boolean missing1 = r.getLong("disappearanceDate1") != null || r.getLong("deleteDate1") != null;
    final boolean missing2 = r.getLong("disappearanceDate2") != null || r.getLong("deleteDate2") != null;
    final JsonObject error = new JsonObject().put("status", "error");
    if (source1 != null && source1.equals(source2) && notDeduplicateSource.contains(source1) && !missing1
            && !missing2) {/*  w ww . j a va2  s.com*/
        message.reply(error.put("message", "two.users.in.same.source"));
        return;
    }
    String query;
    JsonObject params = new JsonObject();
    if ((activatedU1 && prioritySource(source1) >= prioritySource(source2))
            || (activatedU2 && prioritySource(source1) <= prioritySource(source2))
            || (!activatedU1 && !activatedU2)) {
        query = SIMPLE_MERGE_QUERY;
        if (prioritySource(source1) == prioritySource(source2) && notDeduplicateSource.contains(source1)) {
            if (!missing1 && activatedU1) {
                params.put("userId1", userId1).put("userId2", userId2);
            } else if (!missing2 && activatedU2) {
                params.put("userId1", userId2).put("userId2", userId1);
            } else {
                query = SWITCH_MERGE_QUERY;
                if (activatedU1) {
                    params.put("userId1", userId1).put("userId2", userId2);
                } else {
                    params.put("userId1", userId2).put("userId2", userId1);
                }
            }
        } else {
            if (activatedU1) {
                params.put("userId1", userId1).put("userId2", userId2);
            } else if (activatedU2) {
                params.put("userId1", userId2).put("userId2", userId1);
            } else {
                if (prioritySource(source1) > prioritySource(source2)) {
                    params.put("userId1", userId1).put("userId2", userId2);
                } else {
                    params.put("userId1", userId2).put("userId2", userId1);
                }
            }
        }
    } else if ((activatedU1 && prioritySource(source1) < prioritySource(source2))
            || (activatedU2 && prioritySource(source1) > prioritySource(source2))) {
        query = SWITCH_MERGE_QUERY;
        if (activatedU1) {
            params.put("userId1", userId1).put("userId2", userId2);
        } else {
            params.put("userId1", userId2).put("userId2", userId1);
        }
    } else {
        message.reply(error.put("message", "invalid.merge.case"));
        return;
    }
    if (tx != null) {
        tx.add(INCREMENT_RELATIVE_SCORE, params);
        tx.add(query, params);
        sendMergedEvent(params.getString("userId1"), params.getString("userId2"));
        message.reply(new JsonObject().put("status", "ok"));
    } else {
        try {
            TransactionHelper txl = TransactionManager.getTransaction();
            txl.add(INCREMENT_RELATIVE_SCORE, params);
            txl.add(query, params);
            txl.commit(new Handler<Message<JsonObject>>() {
                @Override
                public void handle(Message<JsonObject> event) {
                    if ("ok".equals(event.body().getString("status"))) {
                        log.info("Merge duplicates : " + r.encode());
                        if (updateCourses) {
                            AbstractTimetableImporter.updateMergedUsers(event.body().getJsonArray("results"));
                        }
                        sendMergedEvent(params.getString("userId1"), params.getString("userId2"));
                    }
                    message.reply(event.body());
                }
            });
        } catch (TransactionException e) {
            message.reply(error.put("message", "invalid.transaction"));
        }
    }
}

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/*from  w  ww. j a  v  a  2  s  .co m*/
        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.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 {//w  ww.j  a v  a 2s  .com
            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.dictionary.structures.Transition.java

License:Open Source License

private void publishTransition(JsonObject struct, JsonArray classes) {
    if (struct == null)
        return;/*  www .j ava 2 s  .co m*/
    final JsonObject structure = struct.copy();
    structure.put("classes", classes);
    structure.remove("created");
    structure.remove("modified");
    structure.remove("checksum");
    log.info("Publish transition : " + structure.encode());
    vertx.eventBus().publish(Feeder.USER_REPOSITORY,
            new JsonObject().put("action", "transition").put("structure", structure));
}

From source file:org.entcore.feeder.timetable.AbstractTimetableImporter.java

License:Open Source License

protected void init(final Handler<AsyncResult<Void>> handler) throws TransactionException {
    importTimestamp = System.currentTimeMillis();
    final String externalIdFromUAI = "MATCH (s:Structure {UAI : {UAI}}) "
            + "return s.externalId as externalId, s.id as id, s.timetable as timetable ";
    final String tma = getTeacherMappingAttribute();
    final String getUsersByProfile = "MATCH (:Structure {UAI : {UAI}})<-[:DEPENDS]-(:ProfileGroup)<-[:IN]-(u:User) "
            + "WHERE head(u.profiles) = {profile} AND NOT(u." + tma + " IS NULL) "
            + "RETURN DISTINCT u.id as id, u." + tma
            + " as tma, head(u.profiles) as profile, u.source as source, "
            + "u.lastName as lastName, u.firstName as firstName";
    final String classesMappingQuery = "MATCH (s:Structure {UAI : {UAI}})<-[:MAPPING]-(cm:ClassesMapping) "
            + "return cm.mapping as mapping ";
    final String subjectsMappingQuery = "MATCH (s:Structure {UAI : {UAI}})<-[:SUBJECT]-(sub:Subject) return sub.code as code, sub.id as id";
    final TransactionHelper tx = TransactionManager.getTransaction();
    tx.add(getUsersByProfile, new JsonObject().put("UAI", UAI).put("profile", "Teacher"));
    tx.add(externalIdFromUAI, new JsonObject().put("UAI", UAI));
    tx.add(classesMappingQuery, new JsonObject().put("UAI", UAI));
    tx.add(subjectsMappingQuery, new JsonObject().put("UAI", UAI));
    tx.commit(new Handler<Message<JsonObject>>() {
        @Override/*from   w  w  w .  j  a  v a 2  s.c  o  m*/
        public void handle(Message<JsonObject> event) {
            final JsonArray res = event.body().getJsonArray("results");
            if ("ok".equals(event.body().getString("status")) && res != null && res.size() == 4) {
                try {
                    for (Object o : res.getJsonArray(0)) {
                        if (o instanceof JsonObject) {
                            final JsonObject j = (JsonObject) o;
                            teachersMapping.put(j.getString("tma"),
                                    new String[] { j.getString("id"), j.getString("source") });
                            teachersCleanNameMapping.put(
                                    Validator.sanitize(j.getString("firstName") + j.getString("lastName")),
                                    new String[] { j.getString("id"), j.getString("source") });
                        }
                    }
                    JsonArray a = res.getJsonArray(1);
                    if (a != null && a.size() == 1) {
                        structureExternalId = a.getJsonObject(0).getString("externalId");
                        structure.add(structureExternalId);
                        structureId = a.getJsonObject(0).getString("id");
                        if (!getSource().equals(a.getJsonObject(0).getString("timetable"))) {
                            handler.handle(new DefaultAsyncResult<Void>(
                                    new TransactionException("different.timetable.type")));
                            return;
                        }
                    } else {
                        handler.handle(new DefaultAsyncResult<Void>(new ValidationException("invalid.uai")));
                        return;
                    }
                    JsonArray cm = res.getJsonArray(2);
                    if (cm != null && cm.size() == 1) {
                        try {
                            final JsonObject cmn = cm.getJsonObject(0);
                            log.info(cmn.encode());
                            if (isNotEmpty(cmn.getString("mapping"))) {
                                classesMapping = new JsonObject(cmn.getString("mapping"));
                                log.info("classMapping : " + classesMapping.encodePrettily());
                            } else {
                                classesMapping = new JsonObject();
                            }
                        } catch (Exception ecm) {
                            classesMapping = new JsonObject();
                            log.error(ecm.getMessage(), ecm);
                        }
                    }
                    JsonArray subjects = res.getJsonArray(3);
                    if (subjects != null && subjects.size() > 0) {
                        for (Object o : subjects) {
                            if (o instanceof JsonObject) {
                                final JsonObject s = (JsonObject) o;
                                subjectsMapping.put(s.getString("code"), s.getString("id"));
                            }
                        }
                    }
                    txXDT = TransactionManager.getTransaction();
                    persEducNat = new PersEducNat(txXDT, report, getSource());
                    persEducNat.setMapping(
                            "dictionary/mapping/" + getSource().toLowerCase() + "/PersEducNat.json");
                    handler.handle(new DefaultAsyncResult<>((Void) null));
                } catch (Exception e) {
                    handler.handle(new DefaultAsyncResult<Void>(e));
                }
            } else {
                handler.handle(new DefaultAsyncResult<Void>(
                        new TransactionException(event.body().getString("message"))));
            }
        }
    });
}

From source file:org.entcore.feeder.timetable.AbstractTimetableImporter.java

License:Open Source License

private static void transitionDeleteCourses(final JsonObject query) {
    MongoDb.getInstance().delete(COURSES, query, new Handler<Message<JsonObject>>() {
        @Override/*from  w ww . ja  v  a 2  s. co  m*/
        public void handle(Message<JsonObject> event) {
            if (!"ok".equals(event.body().getString("status"))) {
                log.error("Courses timetable transition error on structure " + query.encode() + " - message : "
                        + event.body().getString("message"));
            }
        }
    });
}

From source file:org.entcore.feeder.timetable.AbstractTimetableImporter.java

License:Open Source License

private static void transitionDeleteSubjectsAndMapping(final String structureExternalId) {
    final JsonObject params = new JsonObject();
    String filter = "";
    if (isNotEmpty(structureExternalId)) {
        filter = " {externalId : {structureExternalId}}";
        params.put("structureExternalId", structureExternalId);
    }/*from   w w  w .ja  v  a2s. co  m*/
    try {
        final TransactionHelper tx = TransactionManager.getTransaction();
        tx.add("MATCH (s:Structure" + filter + ") SET s.timetable = 'NOP'", params);
        tx.add("MATCH (:Structure" + filter + ")<-[:SUBJECT]-(sub:Subject) DETACH DELETE sub", params);
        tx.add("MATCH (:Structure" + filter + ")<-[:MAPPING]-(cm:ClassesMapping) DETACH DELETE cm", params);
        tx.commit(new Handler<Message<JsonObject>>() {
            @Override
            public void handle(Message<JsonObject> event) {
                if (!"ok".equals(event.body().getString("status"))) {
                    log.error("Subjects timetable transition error on structure " + params.encode()
                            + " - message : " + event.body().getString("message"));
                }
            }
        });
    } catch (TransactionException e) {
        log.error("Unable to acquire transaction for timetable transition", e);
    }
}

From source file:org.entcore.feeder.timetable.edt.EDTImporter.java

License:Open Source License

private void findPersEducNat(JsonObject currentEntity, String idPronote, String profile) {
    log.debug(currentEntity);/*  www.j a  v a 2  s.c om*/
    try {
        JsonObject p = persEducNat.applyMapping(currentEntity);
        p.put("profiles", new fr.wseduc.webutils.collections.JsonArray().add(profile));
        p.put("externalId", idPronote);
        p.put(IDPN, idPronote);
        if (isNotEmpty(p.getString("lastName")) && isNotEmpty(p.getString("firstName"))) {
            notFoundPersEducNat.put(idPronote, p);
            txXDT.add(MATCH_PERSEDUCNAT_QUERY,
                    new JsonObject().put("UAI", UAI).put(IDPN, idPronote).put("profile", profile)
                            .put("lastName", p.getString("lastName").toLowerCase())
                            .put("firstName", p.getString("firstName").toLowerCase()));
        } else {
            report.addErrorWithParams("empty.required.user.attribute", p.encode().replaceAll("\\$", ""));
        }
    } catch (Exception e) {
        report.addError(e.getMessage());
    }
}