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.feeder.timetable.edt.EDTImporter.java

License:Open Source License

void addCourse(JsonObject currentEntity) {
    final List<Long> weeks = new ArrayList<>();
    final List<JsonObject> items = new ArrayList<>();

    for (String attr : currentEntity.fieldNames()) {
        if (!ignoreAttributes.contains(attr) && currentEntity.getValue(attr) instanceof JsonArray) {
            for (Object o : currentEntity.getJsonArray(attr)) {
                if (!(o instanceof JsonObject))
                    continue;
                final JsonObject j = (JsonObject) o;
                j.put("itemType", attr);
                final String week = j.getString("Semaines");
                if (week != null) {
                    weeks.add(Long.valueOf(week));
                    items.add(j);/*ww  w  .j  a v a  2 s  .com*/
                }
            }
        }
    }

    if (log.isDebugEnabled() && currentEntity.containsKey("SemainesAnnulation")) {
        log.debug(currentEntity.encode());
    }
    final Long cancelWeek = (currentEntity.getString("SemainesAnnulation") != null)
            ? Long.valueOf(currentEntity.getString("SemainesAnnulation"))
            : null;
    BitSet lastWeek = new BitSet(weeks.size());
    int startCourseWeek = 0;
    for (int i = 1; i < 53; i++) {
        final BitSet currentWeek = new BitSet(weeks.size());
        boolean enabledCurrentWeek = false;
        for (int j = 0; j < weeks.size(); j++) {
            if (cancelWeek != null && ((1L << i) & cancelWeek) != 0) {
                currentWeek.set(j, false);
            } else {
                final Long week = weeks.get(j);
                currentWeek.set(j, ((1L << i) & week) != 0);
            }
            enabledCurrentWeek = enabledCurrentWeek | currentWeek.get(j);
        }
        if (!currentWeek.equals(lastWeek)) {
            if (startCourseWeek > 0) {
                persistCourse(generateCourse(startCourseWeek, i - 1, lastWeek, items, currentEntity));
            }
            startCourseWeek = enabledCurrentWeek ? i : 0;
            lastWeek = currentWeek;
        }
    }
}

From source file:org.entcore.feeder.timetable.udt.UDTImporter.java

License:Open Source License

void addEleve(JsonObject currentEntity) {
    if ("0".equals(currentEntity.getString("theorique"))) {
        return;//from w w w . j av a  2  s .c om
    }
    final String ele = currentEntity.getString("ele");
    if (isEmpty(ele)) {
        report.addErrorWithParams("invalid.epj", currentEntity.encode());
        return;
    }
    JsonObject eleve = eleves.get(ele);
    if (eleve == null) {
        report.addErrorWithParams("missing.student", currentEntity.encode());
        return;
    }
    final String codeGroup = currentEntity.getString("gpe");
    final String codeDiv = currentEntity.getString("code_div");
    JsonArray groups;
    if (isNotEmpty(codeGroup)) {
        JsonObject group = this.groups.get(codeDiv + codeGroup);
        if (group == null) {
            log.warn("addEleve : unknown.group.mapping");
            return;
        }
        final String name = group.getString("code_div") + " Gr " + group.getString(CODE);
        txXDT.add(STUDENTS_TO_GROUPS,
                new JsonObject().put("firstName", eleve.getString("prenom", "").toLowerCase())
                        .put("lastName", eleve.getString("nom", "").toLowerCase())
                        .put("birthDate", StringValidation.convertDate(eleve.getString("naissance", "")))
                        .put("externalId", structureExternalId + "$" + name)
                        .put("structureExternalId", structureExternalId).put("source", UDT)
                        .put("inDate", importTimestamp).put("outDate", endStudents)
                        .put("now", importTimestamp));
        groups = group.getJsonArray("groups");

    } else {
        JsonObject classe = classes.get(codeDiv);
        if (classe == null) {
            log.warn("addEleve : unknown.class.mapping");
            return;
        }
        groups = classe.getJsonArray("groups");
    }
    if (groups != null) {
        for (Object o2 : groups) {
            txXDT.add(STUDENTS_TO_GROUPS,
                    new JsonObject().put("firstName", eleve.getString("prenom", "").toLowerCase())
                            .put("lastName", eleve.getString("nom", "").toLowerCase())
                            .put("birthDate", StringValidation.convertDate(eleve.getString("naissance", "")))
                            .put("externalId", structureExternalId + "$" + o2.toString())
                            .put("structureExternalId", structureExternalId).put("source", UDT)
                            .put("inDate", importTimestamp).put("outDate", endStudents)
                            .put("now", importTimestamp));
        }
    }
}

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

License:Open Source License

public static String checksum(JsonObject object, HashAlgorithm hashAlgorithm) throws NoSuchAlgorithmException {
    if (object == null) {
        return null;
    }//from  www  . j  a va2 s . c om
    final TreeSet<String> sorted = new TreeSet<>(object.fieldNames());
    final JsonObject j = new JsonObject();
    for (String attr : sorted) {
        j.put(attr, object.getValue(attr));
    }
    switch (hashAlgorithm) {
    case MD5:
        return Md5.hash(j.encode());
    default:
        return Sha256.hash(j.encode());
    }
}

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

License:Open Source License

public void add(String query, JsonObject params) {
    if (autoSend && !waitingQuery && transactionId != null && remainingStatementNumber.getAndDecrement() == 0) {
        final JsonArray s = statements;
        statements = new fr.wseduc.webutils.collections.JsonArray();
        send(s);//from  www . j ava 2 s .com
        remainingStatementNumber = new AtomicInteger(statementNumber);
    }
    if (query != null && !query.trim().isEmpty()) {
        if (log.isDebugEnabled()) {
            log.debug("query : " + query + " - params : " + (params != null ? params.encode() : "{}"));
        }
        JsonObject statement = new JsonObject().put("statement", query);
        if (params != null) {
            statement.put("parameters", params);
        }
        statements.add(statement);
    }
}

From source file:org.entcore.infra.services.impl.AbstractAntivirusService.java

License:Open Source License

private void removeInfectedFile(final InfectedFile i, final Message<JsonObject> message) {
    ObjectMapper mapper = new ObjectMapper();
    try {/*from  www.  j a  v a  2s .  co m*/
        final JsonObject params = new JsonObject(mapper.writeValueAsString(i));
        log.info("Remove infected file : " + params.encode());
        final HttpServerRequest request = new JsonHttpServerRequest(new JsonObject());
        render.processTemplate(request, "text/infectedFile.txt", params, new Handler<String>() {
            @Override
            public void handle(String content) {
                storage.writeBuffer(i.getPath(), i.getId(), Buffer.buffer(content), "text/plain",
                        i.getName() + ".txt", new Handler<JsonObject>() {
                            @Override
                            public void handle(JsonObject event) {
                                if (timeline != null && i.getOwner() != null) {
                                    final List<String> recipients = new ArrayList<>();
                                    recipients.add(i.getOwner());
                                    timeline.notifyTimeline(request, "workspace.delete-virus", null, recipients,
                                            null, params);
                                }
                                if (message != null) {
                                    JsonObject m = new JsonObject().put("id", i.getId())
                                            .put("name", i.getName() + ".txt").put("contentType", "text/plain")
                                            .put("action", "updateInfos");
                                    message.reply(m, handlerToAsyncHandler(new Handler<Message<JsonObject>>() {
                                        @Override
                                        public void handle(Message<JsonObject> r) {
                                            if ("ok".equals(r.body().getString("status"))
                                                    && r.body().getInteger("count", -1) > 0) {
                                                log.info("File info " + i.getId() + " updated.");
                                            } else {
                                                log.error("Error updating file info " + i.getId());
                                            }
                                        }
                                    }));
                                }
                            }
                        });
            }
        });
    } catch (IOException | DecodeException e) {
        log.error("Error serializing infected file : " + i.getId(), e);
    }
}

From source file:org.entcore.infra.Starter.java

License:Open Source License

@Override
public void start() {
    try {//from   w  ww. ja va2 s. com
        super.start();
        final LocalMap<Object, Object> serverMap = vertx.sharedData().getLocalMap("server");

        serverMap.put("signKey", config.getString("key", "zbxgKWuzfxaYzbXcHnK3WnWK" + Math.random()));
        CookieHelper.getInstance().init((String) vertx.sharedData().getLocalMap("server").get("signKey"), log);

        JsonObject swift = config.getJsonObject("swift");
        if (swift != null) {
            serverMap.put("swift", swift.encode());
        }
        JsonObject emailConfig = config.getJsonObject("emailConfig");
        if (emailConfig != null) {
            serverMap.put("emailConfig", emailConfig.encode());
        }
        JsonObject filesystem = config.getJsonObject("file-system");
        if (filesystem != null) {
            serverMap.put("file-system", filesystem.encode());
        }
        JsonObject neo4jConfig = config.getJsonObject("neo4jConfig");
        if (neo4jConfig != null) {
            serverMap.put("neo4jConfig", neo4jConfig.encode());
        }
        final String csp = config.getString("content-security-policy");
        if (isNotEmpty(csp)) {
            serverMap.put("contentSecurityPolicy", csp);
        }
        serverMap.put("gridfsAddress", config.getString("gridfs-address", "wse.gridfs.persistor"));
        //initModulesHelpers(node);

        /* sharedConf sub-object */
        JsonObject sharedConf = config.getJsonObject("sharedConf", new JsonObject());
        for (String field : sharedConf.fieldNames()) {
            serverMap.put(field, sharedConf.getValue(field));
        }

        vertx.sharedData().getLocalMap("skins")
                .putAll(config.getJsonObject("skins", new JsonObject()).getMap());

        final MessageConsumer<JsonObject> messageConsumer = vertx.eventBus()
                .localConsumer("app-registry.loaded");
        messageConsumer.handler(message -> {
            //            JsonSchemaValidator validator = JsonSchemaValidator.getInstance();
            //            validator.setEventBus(getEventBus(vertx));
            //            validator.setAddress(node + "json.schema.validator");
            //            validator.loadJsonSchema(getPathPrefix(config), vertx);
            registerGlobalWidgets(
                    config.getString("widgets-path", config.getString("assets-path", ".") + "/assets/widgets"));
            loadInvalidEmails();
            messageConsumer.unregister();
        });
    } catch (Exception ex) {
        log.error(ex.getMessage());
    }
    JsonObject eventConfig = config.getJsonObject("eventConfig", new JsonObject());
    EventStoreService eventStoreService = new MongoDbEventStore();
    EventStoreController eventStoreController = new EventStoreController(eventConfig);
    eventStoreController.setEventStoreService(eventStoreService);
    addController(eventStoreController);
    addController(new MonitoringController());
    addController(new EmbedController());
    if (config.getBoolean("antivirus", false)) {
        ClamAvService antivirusService = new ClamAvService();
        antivirusService.setVertx(vertx);
        antivirusService.setTimeline(new TimelineHelper(vertx, getEventBus(vertx), config));
        antivirusService.setRender(new Renders(vertx, config));
        antivirusService.init();
        AntiVirusController antiVirusController = new AntiVirusController();
        antiVirusController.setAntivirusService(antivirusService);
        addController(antiVirusController);
        vertx.deployVerticle(ExecCommandWorker.class.getName(), new DeploymentOptions().setWorker(true));
    }
}

From source file:org.entcore.portal.controllers.PortalController.java

License:Open Source License

@Get("/theme")
@SecuredAction(value = "portal", type = ActionType.AUTHENTICATED)
public void getTheme(final HttpServerRequest request) {
    final String theme_attr = THEME_ATTRIBUTE + getHost(request);
    UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() {
        @Override//from  www .jav  a2s . c  om
        public void handle(final UserInfos user) {
            if (user != null) {
                Object t = user.getAttribute(theme_attr);
                if (t != null) {
                    renderJson(request, new JsonObject(t.toString()));
                    return;
                }
                JsonObject urls = config.getJsonObject("urls", new JsonObject());
                final JsonObject theme = new JsonObject().put("template", "/public/template/portal.html")
                        .put("logoutCallback", getLogoutCallback(request, urls));
                String query = "MATCH (n:User)-[:USERBOOK]->u " + "WHERE n.id = {id} " + "RETURN u.theme"
                        + getSkinFromConditions(request).replaceAll("\\W+", "") + " as theme";
                Map<String, Object> params = new HashMap<>();
                params.put("id", user.getUserId());
                Neo4j.getInstance().execute(query, params, new Handler<Message<JsonObject>>() {
                    @Override
                    public void handle(Message<JsonObject> event) {
                        if ("ok".equals(event.body().getString("status"))) {
                            JsonArray result = event.body().getJsonArray("result");
                            String userTheme = (result != null && result.size() == 1)
                                    ? result.getJsonObject(0).getString("theme")
                                    : null;
                            List<String> t = themes.get(getSkinFromConditions(request));
                            if (userTheme != null && t != null && t.contains(userTheme)) {
                                theme.put("skin", getThemePrefix(request) + "/skins/" + userTheme + "/");
                            } else {
                                theme.put("skin", getThemePrefix(request) + "/skins/default/");
                            }
                        } else {
                            theme.put("skin", getThemePrefix(request) + "/skins/default/");
                        }
                        renderJson(request, theme);
                        UserUtils.addSessionAttribute(eb, user.getUserId(), theme_attr, theme.encode(), null);
                    }
                });
            } else {
                unauthorized(request);
            }
        }
    });
}

From source file:org.entcore.session.AuthManager.java

License:Open Source License

private void createSession(final String userId, final String sId, final String sessionIndex,
        final String nameId, final Handler<String> handler) {
    final String sessionId = (sId != null) ? sId : UUID.randomUUID().toString();
    generateSessionInfos(userId, new Handler<JsonObject>() {

        @Override/*  ww  w  . j a  v a  2  s  .c  o  m*/
        public void handle(JsonObject infos) {
            if (infos != null) {
                long timerId = setTimer(userId, sessionId);

                try {
                    sessions.put(sessionId, infos.encode());
                    addLoginInfo(userId, timerId, sessionId);
                } catch (Exception e) {
                    logger.error("Error putting session in hazelcast map");
                    //                  try {
                    //                     if (sessions instanceof IMap) {
                    //                        ((IMap) sessions).putAsync(sessionId, infos.encode());
                    //                     }
                    //                     addLoginInfo(userId, timerId, sessionId);
                    //                  } catch (Exception e1) {
                    //                     logger.error("Error putting async session in hazelcast map", e1);
                    //                  }
                }
                final JsonObject now = MongoDb.now();
                if (sId == null) {
                    JsonObject json = new JsonObject().put("_id", sessionId).put("userId", userId)
                            .put("created", now).put("lastUsed", now);
                    if (sessionIndex != null && nameId != null) {
                        json.put("SessionIndex", sessionIndex).put("NameID", nameId);
                    }
                    mongo.save(SESSIONS_COLLECTION, json);
                } else {
                    mongo.update(SESSIONS_COLLECTION, new JsonObject().put("_id", sessionId),
                            new JsonObject().put("$set", new JsonObject().put("lastUsed", now)));
                }
                handler.handle(sessionId);
            } else {
                handler.handle(null);
            }
        }
    });
}

From source file:org.entcore.session.AuthManager.java

License:Open Source License

private void updateSessionByUserId(Message<JsonObject> message, JsonObject session) {
    final String userId = message.body().getString("userId");
    if (userId == null || userId.trim().isEmpty()) {
        sendError(message, "[updateSessionByUserId] Invalid userId : " + message.body().encode());
        return;/*from w  w  w  .  j ava2 s .co  m*/
    }

    List<LoginInfo> infos = logins.get(userId);
    if (infos == null || infos.isEmpty()) {
        sendError(message,
                "[updateSessionByUserId] info is null - Invalid userId : " + message.body().encode());
        return;
    }
    for (LoginInfo info : infos) {
        try {
            sessions.put(info.sessionId, session.encode());
        } catch (Exception e) {
            logger.error("Error putting session in hazelcast map : " + info.sessionId, e);
        }
    }
}

From source file:org.entcore.workspace.service.impl.DefaultQuotaService.java

License:Open Source License

@Override
public void incrementStorage(String userId, Long size, int threshold,
        final Handler<Either<String, JsonObject>> handler) {
    JsonObject params = new JsonObject().put("size", size).put("threshold", threshold);
    if (!neo4jPlugin) {
        String query = "MATCH (u:UserBook { userid : {userId}}) " + "SET u.storage = u.storage + {size} "
                + "WITH u, u.alertSize as oldAlert "
                + "SET u.alertSize = ((100.0 * u.storage / u.quota) > {threshold}) "
                + "RETURN u.storage as storage, (u.alertSize = true AND oldAlert <> u.alertSize) as notify ";
        params.put("userId", userId);
        neo4j.execute(query, params, validUniqueResultHandler(handler));
    } else {//  ww  w  .j  av a 2  s. c om
        neo4j.unmanagedExtension("put", "/entcore/quota/storage/" + userId, params.encode(),
                new Handler<Message<JsonObject>>() {
                    @Override
                    public void handle(Message<JsonObject> event) {
                        if ("ok".equals(event.body().getString("status"))) {
                            handler.handle(new Either.Right<String, JsonObject>(
                                    new JsonObject(event.body().getString("result"))));
                        } else {
                            handler.handle(
                                    new Either.Left<String, JsonObject>(event.body().getString("message")));
                        }
                    }
                });
    }
}