Example usage for io.vertx.core.json JsonArray size

List of usage examples for io.vertx.core.json JsonArray size

Introduction

In this page you can find the example usage for io.vertx.core.json JsonArray size.

Prototype

public int size() 

Source Link

Document

Get the number of values in this JSON array

Usage

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   ww  w. j  a va 2  s.  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 w ww .ja v a2 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.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   w  w w .  ja  v  a 2 s  .  c om
                    };

                    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.timeline.services.impl.DefaultTimelineMailerService.java

License:Open Source License

@Override
public void sendDailyMails(int dayDelta, final Handler<Either<String, JsonObject>> handler) {

    final HttpServerRequest request = new JsonHttpServerRequest(new JsonObject());
    final AtomicInteger userPagination = new AtomicInteger(0);
    final AtomicInteger endPage = new AtomicInteger(0);
    final Calendar dayDate = Calendar.getInstance();
    dayDate.add(Calendar.DAY_OF_MONTH, dayDelta);
    dayDate.set(Calendar.HOUR_OF_DAY, 0);
    dayDate.set(Calendar.MINUTE, 0);
    dayDate.set(Calendar.SECOND, 0);
    dayDate.set(Calendar.MILLISECOND, 0);

    final JsonObject results = new JsonObject().put("mails.sent", 0).put("users.ko", 0);
    final JsonObject notificationsDefaults = new JsonObject();
    final List<String> notifiedUsers = new ArrayList<>();

    final Handler<Boolean> userContinuationHandler = new Handler<Boolean>() {

        private final Handler<Boolean> continuation = this;
        private final Handler<JsonArray> usersHandler = new Handler<JsonArray>() {
            public void handle(final JsonArray users) {
                final int nbUsers = users.size();
                if (nbUsers == 0) {
                    log.info("[DailyMails] Page0 : " + userPagination.get() + "/" + endPage.get());
                    continuation.handle(userPagination.get() != endPage.get());
                    return;
                }/*from w  w  w . j  a  v a 2s . com*/
                final AtomicInteger usersCountdown = new AtomicInteger(nbUsers);

                final Handler<Void> usersEndHandler = new Handler<Void>() {
                    public void handle(Void v) {
                        if (usersCountdown.decrementAndGet() <= 0) {
                            log.info("[DailyMails] Page : " + userPagination.get() + "/" + endPage.get());
                            continuation.handle(userPagination.get() != endPage.get());
                        }
                    }
                };

                final JsonArray userIds = new fr.wseduc.webutils.collections.JsonArray();
                for (Object userObj : users)
                    userIds.add(((JsonObject) userObj).getString("id", ""));
                NotificationUtils.getUsersPreferences(eb, userIds, "language: uac.language",
                        new Handler<JsonArray>() {
                            public void handle(JsonArray preferences) {
                                for (Object userObj : preferences) {
                                    final JsonObject userPrefs = (JsonObject) userObj;
                                    final String userDomain = userPrefs.getString("lastDomain",
                                            I18n.DEFAULT_DOMAIN);
                                    final String userScheme = userPrefs.getString("lastScheme", "http");
                                    String mutableUserLanguage = "fr";
                                    try {
                                        mutableUserLanguage = getOrElse(new JsonObject(
                                                getOrElse(userPrefs.getString("language"), "{}", false))
                                                        .getString("default-domain"),
                                                "fr", false);
                                    } catch (Exception e) {
                                        log.error("UserId [" + userPrefs.getString("userId", "")
                                                + "] - Bad language preferences format");
                                    }
                                    final String userLanguage = mutableUserLanguage;

                                    getUserNotifications(userPrefs.getString("userId", ""), dayDate.getTime(),
                                            new Handler<JsonArray>() {
                                                public void handle(JsonArray notifications) {
                                                    if (notifications.size() == 0) {
                                                        usersEndHandler.handle(null);
                                                        return;
                                                    }

                                                    SimpleDateFormat formatter = new SimpleDateFormat(
                                                            "EEE, d MMM yyyy HH:mm:ss",
                                                            Locale.forLanguageTag(userLanguage));
                                                    final JsonArray dates = new fr.wseduc.webutils.collections.JsonArray();
                                                    final JsonArray templates = new fr.wseduc.webutils.collections.JsonArray();

                                                    for (Object notificationObj : notifications) {
                                                        JsonObject notification = (JsonObject) notificationObj;
                                                        final String notificationName = notification
                                                                .getString("type", "").toLowerCase() + "."
                                                                + notification.getString("event-type", "")
                                                                        .toLowerCase();
                                                        if (notificationsDefaults
                                                                .getJsonObject(notificationName) == null)
                                                            continue;

                                                        JsonObject notificationPreference = userPrefs
                                                                .getJsonObject("preferences", new JsonObject())
                                                                .getJsonObject("config", new JsonObject())
                                                                .getJsonObject(notificationName,
                                                                        new JsonObject());
                                                        if (TimelineNotificationsLoader.Frequencies.DAILY.name()
                                                                .equals(notificationPrefsMixin(
                                                                        "defaultFrequency",
                                                                        notificationPreference,
                                                                        notificationsDefaults.getJsonObject(
                                                                                notificationName)))
                                                                && !TimelineNotificationsLoader.Restrictions.INTERNAL
                                                                        .name()
                                                                        .equals(notificationPrefsMixin(
                                                                                "restriction",
                                                                                notificationPreference,
                                                                                notificationsDefaults
                                                                                        .getJsonObject(
                                                                                                notificationName)))
                                                                && !TimelineNotificationsLoader.Restrictions.HIDDEN
                                                                        .name()
                                                                        .equals(notificationPrefsMixin(
                                                                                "restriction",
                                                                                notificationPreference,
                                                                                notificationsDefaults
                                                                                        .getJsonObject(
                                                                                                notificationName)))) {
                                                            templates.add(new JsonObject()
                                                                    .put("template", notificationsDefaults
                                                                            .getJsonObject(notificationName,
                                                                                    new JsonObject())
                                                                            .getString("template", ""))
                                                                    .put("params", notification.getJsonObject(
                                                                            "params", new JsonObject())));
                                                            dates.add(formatter.format(MongoDb.parseIsoDate(
                                                                    notification.getJsonObject("date"))));
                                                        }
                                                    }
                                                    if (templates.size() > 0) {
                                                        JsonObject templateParams = new JsonObject()
                                                                .put("nestedTemplatesArray", templates)
                                                                .put("notificationDates", dates);
                                                        processTimelineTemplate(templateParams, "",
                                                                "notifications/daily-mail.html", userDomain,
                                                                userScheme, userLanguage, false,
                                                                new Handler<String>() {
                                                                    public void handle(
                                                                            final String processedTemplate) {
                                                                        //On completion : log
                                                                        final Handler<AsyncResult<Message<JsonObject>>> completionHandler = event -> {
                                                                            if (event.failed()
                                                                                    || "error".equals(event
                                                                                            .result().body()
                                                                                            .getString("status",
                                                                                                    "error"))) {
                                                                                log.error(
                                                                                        "[Timeline daily emails] Error while sending mail : ",
                                                                                        event.cause());
                                                                                results.put("users.ko",
                                                                                        results.getInteger(
                                                                                                "users.ko")
                                                                                                + 1);
                                                                            } else {
                                                                                results.put("mails.sent",
                                                                                        results.getInteger(
                                                                                                "mails.sent")
                                                                                                + 1);
                                                                            }
                                                                            usersEndHandler.handle(null);
                                                                        };

                                                                        //Translate mail title
                                                                        JsonArray keys = new fr.wseduc.webutils.collections.JsonArray()
                                                                                .add("timeline.daily.mail.subject.header");
                                                                        translateTimeline(keys, userDomain,
                                                                                userLanguage,
                                                                                new Handler<JsonArray>() {
                                                                                    public void handle(
                                                                                            JsonArray translations) {
                                                                                        //Send mail containing the "daily" notifications
                                                                                        emailSender.sendEmail(
                                                                                                request,
                                                                                                userPrefs
                                                                                                        .getString(
                                                                                                                "userMail",
                                                                                                                ""),
                                                                                                null, null,
                                                                                                translations
                                                                                                        .getString(
                                                                                                                0),
                                                                                                processedTemplate,
                                                                                                null, false,
                                                                                                completionHandler);
                                                                                    }
                                                                                });
                                                                    }
                                                                });
                                                    } else {
                                                        usersEndHandler.handle(null);
                                                    }

                                                }
                                            });
                                }
                            }
                        });
            }
        };

        public void handle(Boolean continuation) {
            if (continuation) {
                getImpactedUsers(notifiedUsers, userPagination.getAndIncrement(),
                        new Handler<Either<String, JsonArray>>() {
                            public void handle(Either<String, JsonArray> event) {
                                if (event.isLeft()) {
                                    log.error("[sendDailyMails] Error while retrieving impacted users : "
                                            + event.left().getValue());
                                    handler.handle(
                                            new Either.Left<String, JsonObject>(event.left().getValue()));
                                } else {
                                    JsonArray users = event.right().getValue();
                                    usersHandler.handle(users);
                                }
                            }
                        });
            } else {
                handler.handle(new Either.Right<String, JsonObject>(results));
            }
        }
    };

    getRecipientsUsers(dayDate.getTime(), new Handler<JsonArray>() {
        @Override
        public void handle(JsonArray event) {
            if (event != null && event.size() > 0) {
                notifiedUsers.addAll(event.getList());
                endPage.set((event.size() / USERS_LIMIT) + (event.size() % USERS_LIMIT != 0 ? 1 : 0));
            } else {
                handler.handle(new Either.Right<String, JsonObject>(results));
                return;
            }
            getNotificationsDefaults(new Handler<JsonArray>() {
                public void handle(final JsonArray notifications) {
                    if (notifications == null) {
                        log.error("[sendDailyMails] Error while retrieving notifications defaults.");
                    } else {
                        for (Object notifObj : notifications) {
                            final JsonObject notif = (JsonObject) notifObj;
                            notificationsDefaults.put(notif.getString("key", ""), notif);
                        }
                        userContinuationHandler.handle(true);
                    }
                }
            });
        }
    });
}

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

License:Open Source License

public void sendWeeklyMails(int dayDelta, final Handler<Either<String, JsonObject>> handler) {

    final HttpServerRequest request = new JsonHttpServerRequest(new JsonObject());
    final AtomicInteger userPagination = new AtomicInteger(0);
    final AtomicInteger endPage = new AtomicInteger(0);
    final Calendar weekDate = Calendar.getInstance();
    weekDate.add(Calendar.DAY_OF_MONTH, dayDelta - 6);
    weekDate.set(Calendar.HOUR_OF_DAY, 0);
    weekDate.set(Calendar.MINUTE, 0);
    weekDate.set(Calendar.SECOND, 0);
    weekDate.set(Calendar.MILLISECOND, 0);

    final JsonObject results = new JsonObject().put("mails.sent", 0).put("users.ko", 0);
    final JsonObject notificationsDefaults = new JsonObject();
    final List<String> notifiedUsers = new ArrayList<>();

    final Handler<Boolean> userContinuationHandler = new Handler<Boolean>() {

        private final Handler<Boolean> continuation = this;
        private final Handler<JsonArray> usersHandler = new Handler<JsonArray>() {
            public void handle(final JsonArray users) {
                final int nbUsers = users.size();
                if (nbUsers == 0) {
                    log.info("[WeeklyMails] Page0 : " + userPagination.get() + "/" + endPage.get());
                    continuation.handle(userPagination.get() != endPage.get());
                    return;
                }/*from   w  ww . j  a va  2s  .com*/
                final AtomicInteger usersCountdown = new AtomicInteger(nbUsers);

                final Handler<Void> usersEndHandler = new Handler<Void>() {
                    public void handle(Void v) {
                        if (usersCountdown.decrementAndGet() <= 0) {
                            log.info("[WeeklyMails] Page : " + userPagination.get() + "/" + endPage.get());
                            continuation.handle(userPagination.get() != endPage.get());
                        }
                    }
                };

                final JsonArray userIds = new fr.wseduc.webutils.collections.JsonArray();
                for (Object userObj : users)
                    userIds.add(((JsonObject) userObj).getString("id", ""));
                NotificationUtils.getUsersPreferences(eb, userIds, "language: uac.language",
                        new Handler<JsonArray>() {
                            public void handle(JsonArray preferences) {
                                for (Object userObj : preferences) {
                                    final JsonObject userPrefs = (JsonObject) userObj;
                                    final String userDomain = userPrefs.getString("lastDomain",
                                            I18n.DEFAULT_DOMAIN);
                                    final String userScheme = userPrefs.getString("lastScheme", "http");
                                    String mutableUserLanguage = "fr";
                                    try {
                                        mutableUserLanguage = getOrElse(new JsonObject(
                                                getOrElse(userPrefs.getString("language"), "{}", false))
                                                        .getString("default-domain"),
                                                "fr", false);
                                    } catch (Exception e) {
                                        log.error("UserId [" + userPrefs.getString("userId", "")
                                                + "] - Bad language preferences format");
                                    }
                                    final String userLanguage = mutableUserLanguage;

                                    getAggregatedUserNotifications(userPrefs.getString("userId", ""),
                                            weekDate.getTime(), new Handler<JsonArray>() {
                                                public void handle(JsonArray notifications) {
                                                    if (notifications.size() == 0) {
                                                        usersEndHandler.handle(null);
                                                        return;
                                                    }

                                                    final JsonArray weeklyNotifications = new fr.wseduc.webutils.collections.JsonArray();

                                                    for (Object notificationObj : notifications) {
                                                        JsonObject notification = (JsonObject) notificationObj;
                                                        final String notificationName = notification
                                                                .getString("type", "").toLowerCase() + "."
                                                                + notification.getString("event-type", "")
                                                                        .toLowerCase();
                                                        if (notificationsDefaults
                                                                .getJsonObject(notificationName) == null)
                                                            continue;

                                                        JsonObject notificationPreference = userPrefs
                                                                .getJsonObject("preferences", new JsonObject())
                                                                .getJsonObject("config", new JsonObject())
                                                                .getJsonObject(notificationName,
                                                                        new JsonObject());
                                                        if (TimelineNotificationsLoader.Frequencies.WEEKLY
                                                                .name()
                                                                .equals(notificationPrefsMixin(
                                                                        "defaultFrequency",
                                                                        notificationPreference,
                                                                        notificationsDefaults.getJsonObject(
                                                                                notificationName)))
                                                                && !TimelineNotificationsLoader.Restrictions.INTERNAL
                                                                        .name()
                                                                        .equals(notificationPrefsMixin(
                                                                                "restriction",
                                                                                notificationPreference,
                                                                                notificationsDefaults
                                                                                        .getJsonObject(
                                                                                                notificationName)))
                                                                && !TimelineNotificationsLoader.Restrictions.HIDDEN
                                                                        .name()
                                                                        .equals(notificationPrefsMixin(
                                                                                "restriction",
                                                                                notificationPreference,
                                                                                notificationsDefaults
                                                                                        .getJsonObject(
                                                                                                notificationName)))) {
                                                            notification.put("notificationName",
                                                                    notificationName);
                                                            weeklyNotifications.add(notification);
                                                        }
                                                    }

                                                    final JsonObject weeklyNotificationsObj = new JsonObject();
                                                    final JsonArray weeklyNotificationsGroupedArray = new fr.wseduc.webutils.collections.JsonArray();
                                                    for (Object notif : weeklyNotifications) {
                                                        JsonObject notification = (JsonObject) notif;
                                                        if (!weeklyNotificationsObj.containsKey(
                                                                notification.getString("type").toLowerCase()))
                                                            weeklyNotificationsObj.put(
                                                                    notification.getString("type")
                                                                            .toLowerCase(),
                                                                    new JsonObject().put("link",
                                                                            notificationsDefaults.getJsonObject(
                                                                                    notification.getString(
                                                                                            "notificationName"))
                                                                                    .getString("app-address",
                                                                                            ""))
                                                                            .put("event-types",
                                                                                    new fr.wseduc.webutils.collections.JsonArray()));
                                                        weeklyNotificationsObj
                                                                .getJsonObject(notification.getString("type")
                                                                        .toLowerCase())
                                                                .getJsonArray(("event-types"),
                                                                        new fr.wseduc.webutils.collections.JsonArray())
                                                                .add(notification);
                                                    }

                                                    for (String key : weeklyNotificationsObj.getMap()
                                                            .keySet()) {
                                                        weeklyNotificationsGroupedArray.add(new JsonObject()
                                                                .put("type", key)
                                                                .put("link",
                                                                        weeklyNotificationsObj
                                                                                .getJsonObject(key)
                                                                                .getString("link", ""))
                                                                .put("event-types",
                                                                        weeklyNotificationsObj
                                                                                .getJsonObject(key)
                                                                                .getJsonArray("event-types")));
                                                    }

                                                    if (weeklyNotifications.size() > 0) {
                                                        JsonObject templateParams = new JsonObject().put(
                                                                "notifications",
                                                                weeklyNotificationsGroupedArray);
                                                        processTimelineTemplate(templateParams, "",
                                                                "notifications/weekly-mail.html", userDomain,
                                                                userScheme, userLanguage, false,
                                                                new Handler<String>() {
                                                                    public void handle(
                                                                            final String processedTemplate) {
                                                                        //On completion : log
                                                                        final Handler<AsyncResult<Message<JsonObject>>> completionHandler = event -> {
                                                                            if (event.failed()
                                                                                    || "error".equals(event
                                                                                            .result().body()
                                                                                            .getString("status",
                                                                                                    "error"))) {
                                                                                log.error(
                                                                                        "[Timeline weekly emails] Error while sending mail : ",
                                                                                        event.cause());
                                                                                results.put("users.ko",
                                                                                        results.getInteger(
                                                                                                "users.ko")
                                                                                                + 1);
                                                                            } else {
                                                                                results.put("mails.sent",
                                                                                        results.getInteger(
                                                                                                "mails.sent")
                                                                                                + 1);
                                                                            }
                                                                            usersEndHandler.handle(null);
                                                                        };

                                                                        //Translate mail title
                                                                        JsonArray keys = new fr.wseduc.webutils.collections.JsonArray()
                                                                                .add("timeline.weekly.mail.subject.header");
                                                                        translateTimeline(keys, userDomain,
                                                                                userLanguage,
                                                                                new Handler<JsonArray>() {
                                                                                    public void handle(
                                                                                            JsonArray translations) {
                                                                                        //Send mail containing the "weekly" notifications
                                                                                        emailSender.sendEmail(
                                                                                                request,
                                                                                                userPrefs
                                                                                                        .getString(
                                                                                                                "userMail",
                                                                                                                ""),
                                                                                                null, null,
                                                                                                translations
                                                                                                        .getString(
                                                                                                                0),
                                                                                                processedTemplate,
                                                                                                null, false,
                                                                                                completionHandler);
                                                                                    }
                                                                                });
                                                                    }
                                                                });
                                                    } else {
                                                        usersEndHandler.handle(null);
                                                    }

                                                }
                                            });
                                }
                            }
                        });
            }
        };

        public void handle(Boolean continuation) {
            if (continuation) {
                getImpactedUsers(notifiedUsers, userPagination.getAndIncrement(),
                        new Handler<Either<String, JsonArray>>() {
                            public void handle(Either<String, JsonArray> event) {
                                if (event.isLeft()) {
                                    log.error("[sendWeeklyMails] Error while retrieving impacted users : "
                                            + event.left().getValue());
                                    handler.handle(
                                            new Either.Left<String, JsonObject>(event.left().getValue()));
                                } else {
                                    JsonArray users = event.right().getValue();
                                    usersHandler.handle(users);
                                }
                            }
                        });
            } else {
                handler.handle(new Either.Right<String, JsonObject>(results));
            }
        }
    };
    getRecipientsUsers(weekDate.getTime(), new Handler<JsonArray>() {
        @Override
        public void handle(JsonArray event) {
            if (event != null && event.size() > 0) {
                notifiedUsers.addAll(event.getList());
                endPage.set((event.size() / USERS_LIMIT) + (event.size() % USERS_LIMIT != 0 ? 1 : 0));
            } else {
                handler.handle(new Either.Right<String, JsonObject>(results));
                return;
            }
            getNotificationsDefaults(new Handler<JsonArray>() {
                public void handle(final JsonArray notifications) {
                    if (notifications == null) {
                        log.error("[sendWeeklyMails] Error while retrieving notifications defaults.");
                    } else {
                        for (Object notifObj : notifications) {
                            final JsonObject notif = (JsonObject) notifObj;
                            notificationsDefaults.put(notif.getString("key", ""), notif);
                        }
                        userContinuationHandler.handle(true);
                    }
                }
            });

        }
    });
}

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

License:Open Source License

private void getRecipientsUsers(Date from, final Handler<JsonArray> handler) {
    final JsonObject aggregation = new JsonObject();
    JsonArray pipeline = new fr.wseduc.webutils.collections.JsonArray();
    aggregation.put("aggregate", "timeline").put("allowDiskUse", true).put("pipeline", pipeline);

    JsonObject matcher = MongoQueryBuilder.build(QueryBuilder.start("date").greaterThanEquals(from));
    JsonObject grouper = new JsonObject(
            "{ \"_id\" : \"notifiedUsers\", \"recipients\" : {\"$addToSet\" : \"$recipients.userId\"}}");

    pipeline.add(new JsonObject().put("$match", matcher));
    pipeline.add(new JsonObject().put("$unwind", "$recipients"));
    pipeline.add(new JsonObject().put("$group", grouper));

    mongo.command(aggregation.toString(), new Handler<Message<JsonObject>>() {
        @Override/*from   w w w .  j a  va 2  s.  c  om*/
        public void handle(Message<JsonObject> event) {
            if ("error".equals(event.body().getString("status", "error"))) {
                handler.handle(new fr.wseduc.webutils.collections.JsonArray());
            } else {
                JsonArray r = event.body().getJsonObject("result", new JsonObject()).getJsonArray("result");
                if (r != null && r.size() > 0) {
                    handler.handle(r.getJsonObject(0).getJsonArray("recipients",
                            new fr.wseduc.webutils.collections.JsonArray()));
                } else {
                    handler.handle(new fr.wseduc.webutils.collections.JsonArray());
                }
            }
        }

    });
}

From source file:org.entcore.workspace.security.WorkspaceResourcesProvider.java

License:Open Source License

private void isUserOrAdmin(HttpServerRequest request, UserInfos user, final Handler<Boolean> handler) {
    final String userId = request.params().get("userId");
    if (user.getUserId().equals(userId)) {
        handler.handle(true);/*from w  ww .j  av  a2s.c om*/
        return;
    }
    final UserInfos.Function adminLocal = getFunction(user, handler);
    if (adminLocal == null)
        return;
    String query = "MATCH (s:Structure)<-[:DEPENDS]-(:ProfileGroup)<-[:IN]-(u:User {id : {userId}}) "
            + "WHERE s.id IN {structures} " + "RETURN count(*) > 0 as exists ";
    JsonObject params = new JsonObject()
            .put("structures", new fr.wseduc.webutils.collections.JsonArray(adminLocal.getScope()))
            .put("userId", userId);
    Neo4j.getInstance().execute(query, params, new Handler<Message<JsonObject>>() {
        @Override
        public void handle(Message<JsonObject> message) {
            JsonArray res = message.body().getJsonArray("result");
            handler.handle("ok".equals(message.body().getString("status")) && res != null && res.size() == 1
                    && res.getJsonObject(0).getBoolean("exists", false));
        }
    });
}

From source file:org.entcore.workspace.security.WorkspaceResourcesProvider.java

License:Open Source License

private void isAdminFromUsers(HttpServerRequest request, UserInfos user, final Handler<Boolean> handler) {
    final UserInfos.Function adminLocal = getFunction(user, handler);
    if (adminLocal == null)
        return;/*w w w . ja  v  a  2s .  c o m*/
    RequestUtils.bodyToJson(request, new Handler<JsonObject>() {
        @Override
        public void handle(JsonObject object) {
            String query = "MATCH (s:Structure)<-[:DEPENDS]-(:ProfileGroup)<-[:IN]-(u:User) "
                    + "WHERE s.id IN {structures} AND u.id IN {users} " + "RETURN count(distinct u) as nb ";
            final JsonArray users = object.getJsonArray("users",
                    new fr.wseduc.webutils.collections.JsonArray());
            JsonObject params = new JsonObject()
                    .put("structures", new fr.wseduc.webutils.collections.JsonArray(adminLocal.getScope()))
                    .put("users", users);
            Neo4j.getInstance().execute(query, params, new Handler<Message<JsonObject>>() {
                @Override
                public void handle(Message<JsonObject> message) {
                    JsonArray res = message.body().getJsonArray("result");
                    handler.handle(
                            "ok".equals(message.body().getString("status")) && res != null && res.size() == 1
                                    && res.getJsonObject(0).getInteger("nb", -1).equals(users.size()));
                }
            });
        }
    });
}

From source file:org.entcore.workspace.security.WorkspaceResourcesProvider.java

License:Open Source License

private void authorizeDocuments(HttpServerRequest request, UserInfos user, String serviceMethod,
        Handler<Boolean> handler) {
    String ids = request.params().get("ids");
    if (ids != null && !ids.trim().isEmpty()) {
        JsonArray idsArray = new fr.wseduc.webutils.collections.JsonArray(Arrays.asList(ids.split(",")));
        String query = "{ \"_id\": { \"$in\" : " + idsArray.encode() + "}, " + "\"$or\" : [{ \"owner\": \""
                + user.getUserId() + "\"}, {\"shared\" : { \"$elemMatch\" : "
                + orSharedElementMatch(user, serviceMethod) + "}}]}";
        executeCountQuery(request, DocumentDao.DOCUMENTS_COLLECTION, new JsonObject(query), idsArray.size(),
                handler);//from www  . j a  v a 2 s. c  om
    } else {
        handler.handle(false);
    }
}

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

License:Open Source License

private void recursiveMove(final String folder, final String name, final String owner, final String path,
        final Handler<Either<String, JsonObject>> result) {
    final String folderAttr = "Trash".equals(path) ? "old-folder" : "folder";
    final QueryBuilder q = QueryBuilder.start("owner").is(owner).put(folderAttr)
            .regex(Pattern.compile("^" + Pattern.quote(folder) + "($|_)"));

    //If the folder has a parent folder, replicate sharing rights
    String[] splittedPath = path.split("_");
    String parentName = splittedPath[splittedPath.length - 1];
    String parentFolder = path;//from w w w  .  j  av a 2s . co  m

    getParentRights(parentName, parentFolder, owner, new Handler<Either<String, JsonArray>>() {
        public void handle(Either<String, JsonArray> event) {
            final JsonArray parentSharedRights = event.right() == null || event.isLeft() ? null
                    : event.right().getValue();

            mongo.distinct(DOCUMENTS_COLLECTION, folderAttr, MongoQueryBuilder.build(q),
                    new Handler<Message<JsonObject>>() {
                        @Override
                        public void handle(Message<JsonObject> d) {
                            JsonArray directories = d.body().getJsonArray("values",
                                    new fr.wseduc.webutils.collections.JsonArray());
                            if ("ok".equals(d.body().getString("status")) && directories.size() > 0) {
                                final AtomicInteger remaining = new AtomicInteger(directories.size());
                                final AtomicInteger count = new AtomicInteger(0);
                                String dest;
                                if (path != null && !path.trim().isEmpty()) {
                                    dest = path + "_" + name;
                                } else {
                                    dest = name;
                                }
                                for (Object o : directories) {
                                    if (!(o instanceof String))
                                        continue;
                                    String dir = (String) o;
                                    QueryBuilder qf = QueryBuilder.start("owner").is(owner).put(folderAttr)
                                            .is(dir);
                                    MongoUpdateBuilder modifier = new MongoUpdateBuilder();
                                    modifier.set("folder", dir.replaceFirst("^" + Pattern.quote(folder),
                                            Matcher.quoteReplacement(dest)));

                                    if ("Trash".equals(path) || parentSharedRights == null)
                                        modifier.unset("shared");
                                    else
                                        modifier.set("shared", parentSharedRights);

                                    mongo.update(DOCUMENTS_COLLECTION, MongoQueryBuilder.build(qf),
                                            modifier.build(), false, true, new Handler<Message<JsonObject>>() {
                                                @Override
                                                public void handle(Message<JsonObject> res) {
                                                    count.getAndAdd(res.body().getInteger("number", 0));
                                                    if (remaining.decrementAndGet() == 0) {
                                                        res.body().put("number", count.get());
                                                        result.handle(Utils.validResult(res));
                                                    }
                                                }
                                            });
                                }
                            } else {
                                result.handle(
                                        new Either.Left<String, JsonObject>("workspace.folder.not.found"));
                            }
                        }
                    });
        }

    });

}