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, JsonObject def) 

Source Link

Document

Like #getJsonObject(String) but specifying a default value to return if there is no entry.

Usage

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

License:Open Source License

@Override
public void importTimetable(String structureId, final String path, final String domain,
        final String acceptLanguage, final Handler<Either<JsonObject, JsonObject>> handler) {
    final String query = "MATCH (s:Structure {id:{id}}) RETURN s.UAI as UAI, s.timetable as timetable";
    neo4j.execute(query, new JsonObject().put("id", structureId),
            validUniqueResultHandler(new Handler<Either<String, JsonObject>>() {
                @Override/* w w  w . j a  va 2s . com*/
                public void handle(Either<String, JsonObject> event) {
                    final JsonArray errors = new fr.wseduc.webutils.collections.JsonArray();
                    final JsonObject ge = new JsonObject().put("error.global", errors);
                    if (event.isRight() && isNotEmpty(event.right().getValue().getString("UAI"))
                            && TIMETABLE_TYPES.contains(event.right().getValue().getString("timetable"))) {
                        if (!("EDT".equals(event.right().getValue().getString("timetable"))
                                && !path.endsWith("\\.xml"))
                                && !("UDT".equals(event.right().getValue().getString("timetable"))
                                        && !path.endsWith("\\.zip"))) {
                            errors.add(I18n.getInstance().translate("invalid.import.format", domain,
                                    acceptLanguage));
                            handler.handle(new Either.Left<JsonObject, JsonObject>(ge));
                            return;
                        }
                        JsonObject action = new JsonObject()
                                .put("action",
                                        "manual-"
                                                + event.right().getValue().getString("timetable").toLowerCase())
                                .put("path", path).put("UAI", event.right().getValue().getString("UAI"))
                                .put("language", acceptLanguage);
                        eb.send(Directory.FEEDER, action, new DeliveryOptions().setSendTimeout(600000l),
                                handlerToAsyncHandler(new Handler<Message<JsonObject>>() {
                                    @Override
                                    public void handle(Message<JsonObject> event) {
                                        if ("ok".equals(event.body().getString("status"))) {
                                            JsonObject r = event.body().getJsonObject("result",
                                                    new JsonObject());
                                            if (r.getJsonObject("errors", new JsonObject()).size() > 0) {
                                                handler.handle(new Either.Left<JsonObject, JsonObject>(
                                                        r.getJsonObject("errors")));
                                            } else {
                                                handler.handle(new Either.Right<JsonObject, JsonObject>(
                                                        r.getJsonObject("ignored")));
                                            }
                                        } else {
                                            errors.add(event.body().getString("message", ""));
                                            handler.handle(new Either.Left<JsonObject, JsonObject>(ge));
                                        }
                                    }
                                }));
                    } else {
                        errors.add(I18n.getInstance().translate("invalid.structure", domain, acceptLanguage));
                        handler.handle(new Either.Left<JsonObject, JsonObject>(ge));
                    }
                }
            }));
}

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

License:Open Source License

private Future<Boolean> cacheAvatarFromUserBook(String userId, Optional<String> pictureId, Boolean remove) {
    // clean avatar when changing or when removing
    Future<Boolean> futureClean = (pictureId.isPresent() || remove) ? cleanAvatarCache(userId)
            : Future.succeededFuture();
    return futureClean.compose(res -> {
        if (!pictureId.isPresent()) {
            return Future.succeededFuture();
        }//  ww w  . j  ava2  s  .  co m
        Future<Boolean> futureCopy = Future.future();
        this.wsHelper.getDocument(pictureId.get(), resDoc -> {
            if (resDoc.succeeded() && "ok".equals(resDoc.result().body().getString("status"))) {
                JsonObject document = resDoc.result().body().getJsonObject("result");
                String fileId = document.getString("file");
                // Extensions are not used by storage
                String defaultFilename = avatarFileNameFromUserId(userId, Optional.empty());
                //
                JsonObject thumbnails = document.getJsonObject("thumbnails", new JsonObject());
                Map<String, String> filenamesByIds = new HashMap<>();
                filenamesByIds.put(fileId, defaultFilename);

                for (String size : thumbnails.fieldNames()) {
                    filenamesByIds.put(thumbnails.getString(size),
                            avatarFileNameFromUserId(userId, Optional.of(size)));
                }
                // TODO avoid buffer to improve performances and avoid cache every time
                List<Future> futures = new ArrayList<>();
                for (Entry<String, String> entry : filenamesByIds.entrySet()) {
                    String cFileId = entry.getKey();
                    String cFilename = entry.getValue();
                    Future<JsonObject> future = Future.future();
                    futures.add(future);
                    this.wsHelper.readFile(cFileId, buffer -> {
                        if (buffer != null) {
                            this.avatarStorage.writeBuffer(FileUtils.stripExtension(cFilename), buffer, "",
                                    cFilename, wRes -> {
                                        future.complete(wRes);
                                    });
                        } else {
                            future.fail("Cannot read file from workspace storage. ID =: " + cFileId);
                        }
                    });
                }
                //
                CompositeFuture.all(futures)
                        .setHandler(finishRes -> futureCopy.complete(finishRes.succeeded()));
            }
        });
        return futureCopy;
    });

}

From source file:org.entcore.timeline.controllers.TimelineController.java

License:Open Source License

@Get("/lastNotifications")
@SecuredAction(value = "timeline.events", type = ActionType.AUTHENTICATED)
public void lastEvents(final HttpServerRequest request) {
    final boolean mine = request.params().contains("mine");

    UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() {

        @Override/*from w  ww.  ja  v  a  2s.  c o m*/
        public void handle(final UserInfos user) {
            if (user != null) {
                getExternalNotifications(new Handler<Either<String, JsonObject>>() {
                    public void handle(Either<String, JsonObject> notifs) {
                        if (notifs.isLeft()) {
                            badRequest(request, notifs.left().getValue());
                            return;
                        }

                        String page = request.params().get("page");
                        List<String> types = request.params().getAll("type");
                        int offset = 0;
                        try {
                            offset = 25 * Integer.parseInt(page);
                        } catch (NumberFormatException e) {
                        }

                        store.get(user, types, offset, 25, notifs.right().getValue(), mine,
                                new Handler<JsonObject>() {
                                    public void handle(final JsonObject res) {
                                        if (res != null && "ok".equals(res.getString("status"))) {
                                            JsonArray results = res.getJsonArray("results",
                                                    new fr.wseduc.webutils.collections.JsonArray());
                                            final JsonArray compiledResults = new fr.wseduc.webutils.collections.JsonArray();

                                            final AtomicInteger countdown = new AtomicInteger(results.size());
                                            final Handler<Void> endHandler = new Handler<Void>() {
                                                public void handle(Void v) {
                                                    if (countdown.decrementAndGet() <= 0) {
                                                        res.put("results", compiledResults);
                                                        renderJson(request, res);
                                                    }
                                                }
                                            };
                                            if (results.size() == 0)
                                                endHandler.handle(null);

                                            for (Object notifObj : results) {
                                                final JsonObject notif = (JsonObject) notifObj;
                                                if (!notif.getString("message", "").isEmpty()) {
                                                    compiledResults.add(notif);
                                                    endHandler.handle(null);
                                                    continue;
                                                }

                                                String key = notif.getString("type", "").toLowerCase() + "."
                                                        + notif.getString("event-type", "").toLowerCase();

                                                String stringifiedRegisteredNotif = registeredNotifications
                                                        .get(key);
                                                if (stringifiedRegisteredNotif == null) {
                                                    log.error(
                                                            "Failed to retrieve registered from the shared map notification with key : "
                                                                    + key);
                                                    endHandler.handle(null);
                                                    continue;
                                                }
                                                JsonObject registeredNotif = new JsonObject(
                                                        stringifiedRegisteredNotif);

                                                StringReader reader = new StringReader(
                                                        registeredNotif.getString("template", ""));
                                                processTemplate(request,
                                                        notif.getJsonObject("params", new JsonObject()), key,
                                                        reader, new Handler<Writer>() {
                                                            public void handle(Writer writer) {
                                                                notif.put("message", writer.toString());
                                                                compiledResults.add(notif);
                                                                endHandler.handle(null);
                                                            }
                                                        });
                                            }
                                        } else {
                                            renderError(request, res);
                                        }
                                    }
                                });
                    }
                });

            } else {
                unauthorized(request);
            }
        }
    });
}

From source file:org.entcore.timeline.controllers.TimelineController.java

License:Open Source License

@Get("/reported")
@SecuredAction(type = ActionType.RESOURCE, value = "")
@ResourceFilter(AdmlOfStructures.class)
public void listReportedNotifications(final HttpServerRequest request) {
    final String structure = request.params().get("structure");
    final boolean pending = Boolean.parseBoolean(request.params().get("pending"));
    int page = 0;
    if (request.params().contains("page")) {
        try {//from ww w .  j  a  va  2 s  .c om
            page = Integer.parseInt(request.params().get("page"));
        } catch (NumberFormatException e) {
            //silent
        }
    }
    store.listReported(structure, pending, PAGELIMIT * page, PAGELIMIT,
            new Handler<Either<String, JsonArray>>() {
                public void handle(Either<String, JsonArray> event) {
                    if (event.isLeft()) {
                        renderError(request);
                        return;
                    }

                    final JsonArray results = event.right().getValue();
                    final JsonArray compiledResults = new fr.wseduc.webutils.collections.JsonArray();

                    final AtomicInteger countdown = new AtomicInteger(results.size());
                    final Handler<Void> endHandler = new Handler<Void>() {
                        public void handle(Void v) {
                            if (countdown.decrementAndGet() <= 0) {
                                renderJson(request, compiledResults);
                            }
                        }
                    };
                    if (results.size() == 0)
                        endHandler.handle(null);

                    for (Object notifObj : results) {
                        final JsonObject notif = (JsonObject) notifObj;
                        if (!notif.getString("message", "").isEmpty()) {
                            compiledResults.add(notif);
                            endHandler.handle(null);
                            continue;
                        }

                        String key = notif.getString("type", "").toLowerCase() + "."
                                + notif.getString("event-type", "").toLowerCase();

                        String stringifiedRegisteredNotif = registeredNotifications.get(key);
                        if (stringifiedRegisteredNotif == null) {
                            log.error(
                                    "Failed to retrieve registered from the shared map notification with key : "
                                            + key);
                            endHandler.handle(null);
                            continue;
                        }
                        JsonObject registeredNotif = new JsonObject(stringifiedRegisteredNotif);

                        StringReader reader = new StringReader(registeredNotif.getString("template", ""));
                        processTemplate(request, notif.getJsonObject("params", new JsonObject()), key, reader,
                                new Handler<Writer>() {
                                    public void handle(Writer writer) {
                                        notif.put("message", writer.toString());
                                        compiledResults.add(notif);
                                        endHandler.handle(null);
                                    }
                                });
                    }
                }
            });
}

From source file:org.entcore.timeline.services.impl.DefaultPushNotifService.java

License:Open Source License

private void sendUsers(final String notificationName, final JsonObject notification, final JsonArray userList,
        final JsonObject notificationProperties, boolean typeNotification, boolean typeData) {

    for (Object userObj : userList) {
        final JsonObject userPref = ((JsonObject) userObj);

        JsonObject notificationPreference = userPref.getJsonObject("preferences", new JsonObject())
                .getJsonObject("config", new JsonObject()).getJsonObject(notificationName, new JsonObject());

        if (notificationPreference.getBoolean("push-notif", notificationProperties.getBoolean("push-notif"))
                && !TimelineNotificationsLoader.Restrictions.INTERNAL.name()
                        .equals(notificationPreference.getString("restriction",
                                notificationProperties.getString("restriction")))
                && !TimelineNotificationsLoader.Restrictions.HIDDEN.name()
                        .equals(notificationPreference.getString("restriction",
                                notificationProperties.getString("restriction")))
                && userPref.getJsonArray("tokens") != null && userPref.getJsonArray("tokens").size() > 0) {
            for (Object token : userPref.getJsonArray("tokens")) {
                processMessage(notification, "fr", typeNotification, typeData, new Handler<JsonObject>() {
                    @Override//from   ww  w  .  jav  a2  s .  c o  m
                    public void handle(final JsonObject message) {
                        try {
                            ossFcm.sendNotifications(
                                    new JsonObject().put("message", message.put("token", (String) token)));
                        } catch (Exception e) {
                            log.error("[sendNotificationToUsers] Issue while sending notification ("
                                    + notificationName + ").", e);

                        }
                    }
                });
            }

        }
    }
}

From source file:org.entcore.timeline.services.impl.DefaultTimelineMailerService.java

License:Open Source License

@Override
public void sendImmediateMails(HttpServerRequest request, String notificationName, JsonObject notification,
        JsonObject templateParameters, JsonArray userList, JsonObject notificationProperties) {

    final Map<String, Map<String, String>> processedTemplates = new HashMap<>();
    templateParameters.put("innerTemplate", notification.getString("template", ""));

    final Map<String, Map<String, List<Object>>> toByDomainLang = new HashMap<>();

    final AtomicInteger userCount = new AtomicInteger(userList.size());
    final Handler<Void> templatesHandler = new Handler<Void>() {
        public void handle(Void v) {
            if (userCount.decrementAndGet() == 0) {
                if (toByDomainLang.size() > 0) {
                    //On completion : log
                    final Handler<AsyncResult<Message<JsonObject>>> completionHandler = event -> {
                        if (event.failed()
                                || "error".equals(event.result().body().getString("status", "error"))) {
                            log.error("[Timeline immediate emails] Error while sending mails : ",
                                    event.cause());
                        } else {
                            log.debug("[Timeline immediate emails] Immediate mails sent.");
                        }/*from  ww  w  .  j  a  v a2s  . c  o m*/
                    };

                    JsonArray keys = new fr.wseduc.webutils.collections.JsonArray()
                            .add("timeline.immediate.mail.subject.header").add(notificationName.toLowerCase());

                    for (final String domain : toByDomainLang.keySet()) {
                        for (final String lang : toByDomainLang.get(domain).keySet()) {
                            translateTimeline(keys, domain, lang, new Handler<JsonArray>() {
                                public void handle(JsonArray translations) {
                                    //Send mail containing the "immediate" notification
                                    emailSender.sendEmail(request, toByDomainLang.get(domain).get(lang), null,
                                            null, translations.getString(0) + translations.getString(1),
                                            processedTemplates.get(domain).get(lang), null, false,
                                            completionHandler);
                                }
                            });
                        }
                    }
                }
            }
        }
    };

    for (Object userObj : userList) {
        final JsonObject userPref = ((JsonObject) userObj);
        final String userDomain = userPref.getString("lastDomain", I18n.DEFAULT_DOMAIN);
        final String userScheme = userPref.getString("lastScheme", "http");
        String mutableLanguage = "fr";
        try {
            mutableLanguage = getOrElse(new JsonObject(getOrElse(userPref.getString("language"), "{}", false))
                    .getString("default-domain"), "fr", false);
        } catch (Exception e) {
            log.error("UserId [" + userPref.getString("userId", "") + "] - Bad language preferences format");
        }
        final String userLanguage = mutableLanguage;

        if (!processedTemplates.containsKey(userDomain))
            processedTemplates.put(userDomain, new HashMap<String, String>());
        JsonObject notificationPreference = userPref.getJsonObject("preferences", new JsonObject())
                .getJsonObject("config", new JsonObject()).getJsonObject(notificationName, new JsonObject());
        // If the frequency is IMMEDIATE
        // and the restriction is not INTERNAL (timeline only)
        // and if the user has provided an email
        if (TimelineNotificationsLoader.Frequencies.IMMEDIATE.name()
                .equals(notificationPreference.getString("defaultFrequency",
                        notificationProperties.getString("defaultFrequency")))
                && !TimelineNotificationsLoader.Restrictions.INTERNAL.name()
                        .equals(notificationPreference.getString("restriction",
                                notificationProperties.getString("restriction")))
                && !TimelineNotificationsLoader.Restrictions.HIDDEN.name()
                        .equals(notificationPreference.getString("restriction",
                                notificationProperties.getString("restriction")))
                && userPref.getString("userMail") != null && !userPref.getString("userMail").trim().isEmpty()) {
            if (!toByDomainLang.containsKey(userDomain)) {
                toByDomainLang.put(userDomain, new HashMap<String, List<Object>>());
            }
            if (!toByDomainLang.get(userDomain).containsKey(userLanguage)) {
                toByDomainLang.get(userDomain).put(userLanguage, new ArrayList<Object>());
            }
            toByDomainLang.get(userDomain).get(userLanguage).add(userPref.getString("userMail"));
        }
        if (!processedTemplates.get(userDomain).containsKey(userLanguage)) {
            processTimelineTemplate(templateParameters, "", "notifications/immediate-mail.html", userDomain,
                    userScheme, userLanguage, false, new Handler<String>() {
                        public void handle(String processedTemplate) {
                            processedTemplates.get(userDomain).put(userLanguage, processedTemplate);
                            templatesHandler.handle(null);
                        }
                    });
        } else {
            templatesHandler.handle(null);
        }
    }
}

From source file:org.entcore.workspace.service.WorkspaceService.java

License:Open Source License

private void updateStorage(JsonArray addeds, JsonArray removeds,
        final Handler<Either<String, JsonObject>> handler) {
    Map<String, Long> sizes = new HashMap<>();
    if (addeds != null) {
        for (Object o : addeds) {
            if (!(o instanceof JsonObject))
                continue;
            JsonObject added = (JsonObject) o;
            Long size = added.getJsonObject("metadata", new JsonObject()).getLong("size", 0l);
            String userId = (added.containsKey("to")) ? added.getString("to") : added.getString("owner");
            if (userId == null) {
                log.info("UserId is null when update storage size");
                log.info(added.encode());
                continue;
            }/* w w w.ja va 2s  .  com*/
            Long old = sizes.get(userId);
            if (old != null) {
                size += old;
            }
            sizes.put(userId, size);
        }
    }

    if (removeds != null) {
        for (Object o : removeds) {
            if (!(o instanceof JsonObject))
                continue;
            JsonObject removed = (JsonObject) o;
            Long size = removed.getJsonObject("metadata", new JsonObject()).getLong("size", 0l);
            String userId = (removed.containsKey("to")) ? removed.getString("to") : removed.getString("owner");
            if (userId == null) {
                log.info("UserId is null when update storage size");
                log.info(removed.encode());
                continue;
            }
            Long old = sizes.get(userId);
            if (old != null) {
                old -= size;
            } else {
                old = -1l * size;
            }
            sizes.put(userId, old);
        }
    }

    for (final Map.Entry<String, Long> e : sizes.entrySet()) {
        quotaService.incrementStorage(e.getKey(), e.getValue(), threshold,
                new Handler<Either<String, JsonObject>>() {
                    @Override
                    public void handle(Either<String, JsonObject> r) {
                        if (r.isRight()) {
                            JsonObject j = r.right().getValue();
                            UserUtils.addSessionAttribute(eb, e.getKey(), "storage", j.getLong("storage"),
                                    null);
                            if (j.getBoolean("notify", false)) {
                                notifyEmptySpaceIsSmall(e.getKey());
                            }
                        } else {
                            log.error(r.left().getValue());
                        }
                        if (handler != null) {
                            handler.handle(r);
                        }
                    }
                });
    }
}

From source file:org.etourdot.vertx.marklogic.model.management.Host.java

License:Open Source License

public Host name(JsonObject jsonObject) {
    this.name = jsonObject
            .getJsonObject("host-default",
                    jsonObject.getJsonObject("host-config",
                            jsonObject.getJsonObject("host-counts", jsonObject.getJsonObject("host-status"))))
            .getString("name");
    return this;
}