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

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

Introduction

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

Prototype

public JsonObject getJsonObject(String key) 

Source Link

Document

Get the JsonObject value with the specified key

Usage

From source file:org.entcore.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  av  a2 s  . co  m*/
                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;
                }//  ww w.  ja  va 2  s . c  o m
                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.workspace.service.WorkspaceService.java

License:Open Source License

private void add(final HttpServerRequest request, final String mongoCollection, final JsonObject doc,
        long allowedSize) {
    storage.writeUploadFile(request, allowedSize, new Handler<JsonObject>() {
        @Override//w ww .j  ava  2  s  .co m
        public void handle(final JsonObject uploaded) {
            if ("ok".equals(uploaded.getString("status"))) {
                compressImage(uploaded, request.params().get("quality"), new Handler<Integer>() {
                    @Override
                    public void handle(Integer size) {
                        JsonObject meta = uploaded.getJsonObject("metadata");
                        if (size != null && meta != null) {
                            meta.put("size", size);
                        }
                        addAfterUpload(uploaded, doc, request.params().get("name"),
                                request.params().get("application"), request.params().getAll("thumbnail"),
                                mongoCollection, new Handler<Message<JsonObject>>() {
                                    @Override
                                    public void handle(Message<JsonObject> res) {
                                        if ("ok".equals(res.body().getString("status"))) {
                                            renderJson(request, res.body(), 201);
                                        } else {
                                            renderError(request, res.body());
                                        }
                                    }
                                });
                    }
                });
            } else {
                badRequest(request, uploaded.getString("message"));
            }
        }
    });
}

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

License:Open Source License

private void addAfterUpload(final JsonObject uploaded, final JsonObject doc, String name, String application,
        final List<String> thumbs, final String mongoCollection, final Handler<Message<JsonObject>> handler) {
    doc.put("name", getOrElse(name, uploaded.getJsonObject("metadata").getString("filename"), false));
    doc.put("metadata", uploaded.getJsonObject("metadata"));
    doc.put("file", uploaded.getString("_id"));
    doc.put("application", getOrElse(application, WORKSPACE_NAME)); // TODO check if application name is valid
    log.debug(doc.encodePrettily());/*from  w  w  w  .jav a 2  s .  c om*/
    mongo.save(mongoCollection, doc, new Handler<Message<JsonObject>>() {
        @Override
        public void handle(final Message<JsonObject> res) {
            if ("ok".equals(res.body().getString("status"))) {
                incrementStorage(doc);
                createRevision(res.body().getString("_id"), uploaded.getString("_id"), doc.getString("name"),
                        doc.getString("owner"), doc.getString("owner"), doc.getString("ownerName"),
                        doc.getJsonObject("metadata"));
                createThumbnailIfNeeded(mongoCollection, uploaded, res.body().getString("_id"), null, thumbs,
                        new Handler<Message<JsonObject>>() {
                            @Override
                            public void handle(Message<JsonObject> event) {
                                if (handler != null) {
                                    handler.handle(res);
                                }
                            }
                        });
            } else if (handler != null) {
                handler.handle(res);
            }
        }
    });
}

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

License:Open Source License

@Put("/document/:id")
@SecuredAction(value = "workspace.contrib", type = ActionType.RESOURCE)
public void updateDocument(final HttpServerRequest request) {
    final String documentId = request.params().get("id");

    UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() {
        @Override//from ww w.  j  av  a 2 s  . co  m
        public void handle(final UserInfos user) {
            if (user != null) {
                request.pause();
                documentDao.findById(documentId, new Handler<JsonObject>() {
                    public void handle(JsonObject event) {
                        if (!"ok".equals(event.getString("status"))) {
                            notFound(request);
                            return;
                        }

                        final String userId = event.getJsonObject("result").getString("owner");

                        emptySize(userId, new Handler<Long>() {
                            @Override
                            public void handle(Long emptySize) {
                                request.resume();
                                storage.writeUploadFile(request, emptySize, new Handler<JsonObject>() {
                                    @Override
                                    public void handle(final JsonObject uploaded) {
                                        if ("ok".equals(uploaded.getString("status"))) {
                                            compressImage(uploaded, request.params().get("quality"),
                                                    new Handler<Integer>() {
                                                        @Override
                                                        public void handle(Integer size) {
                                                            JsonObject meta = uploaded
                                                                    .getJsonObject("metadata");
                                                            if (size != null && meta != null) {
                                                                meta.put("size", size);
                                                            }
                                                            updateAfterUpload(documentId,
                                                                    request.params().get("name"), uploaded,
                                                                    request.params().getAll("thumbnail"), user,
                                                                    new Handler<Message<JsonObject>>() {
                                                                        @Override
                                                                        public void handle(
                                                                                Message<JsonObject> res) {
                                                                            if (res == null) {
                                                                                request.response()
                                                                                        .setStatusCode(404)
                                                                                        .end();
                                                                            } else if ("ok".equals(res.body()
                                                                                    .getString("status"))) {
                                                                                renderJson(request, res.body());
                                                                            } else {
                                                                                renderError(request,
                                                                                        res.body());
                                                                            }
                                                                        }
                                                                    });
                                                        }
                                                    });
                                        } else {
                                            badRequest(request, uploaded.getString("message"));
                                        }
                                    }
                                });
                            }
                        });
                    }
                });
            }
        }
    });
}

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

License:Open Source License

private void updateAfterUpload(final String id, final String name, final JsonObject uploaded,
        final List<String> t, final UserInfos user, final Handler<Message<JsonObject>> handler) {
    documentDao.findById(id, new Handler<JsonObject>() {
        @Override//from  w w  w.  ja  v a  2s.com
        public void handle(final JsonObject old) {
            if ("ok".equals(old.getString("status"))) {
                final JsonObject metadata = uploaded.getJsonObject("metadata");
                JsonObject set = new JsonObject();
                final JsonObject doc = new JsonObject();
                doc.put("name", getOrElse(name, metadata.getString("filename")));
                final String now = MongoDb.formatDate(new Date());
                doc.put("modified", now);
                doc.put("metadata", metadata);
                doc.put("file", uploaded.getString("_id"));
                final JsonObject thumbs = old.getJsonObject("result", new JsonObject())
                        .getJsonObject("thumbnails");

                String query = "{ \"_id\": \"" + id + "\"}";
                set.put("$set", doc).put("$unset", new JsonObject().put("thumbnails", ""));
                mongo.update(DocumentDao.DOCUMENTS_COLLECTION, new JsonObject(query), set,
                        new Handler<Message<JsonObject>>() {
                            @Override
                            public void handle(final Message<JsonObject> res) {
                                String status = res.body().getString("status");
                                JsonObject result = old.getJsonObject("result");
                                if ("ok".equals(status) && result != null) {
                                    String userId = user != null ? user.getUserId() : result.getString("owner");
                                    String userName = user != null ? user.getUsername()
                                            : result.getString("ownerName");
                                    doc.put("owner", result.getString("owner"));
                                    incrementStorage(doc);
                                    createRevision(id, doc.getString("file"), doc.getString("name"),
                                            result.getString("owner"), userId, userName, metadata);
                                    createThumbnailIfNeeded(DocumentDao.DOCUMENTS_COLLECTION, uploaded, id,
                                            thumbs, t, new Handler<Message<JsonObject>>() {
                                                @Override
                                                public void handle(Message<JsonObject> event) {
                                                    if (handler != null) {
                                                        handler.handle(res);
                                                    }
                                                }
                                            });

                                } else if (handler != null) {
                                    handler.handle(res);
                                }
                            }
                        });
            } else if (handler != null) {
                handler.handle(null);
            }
        }
    });
}

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

License:Open Source License

@Get("/document/properties/:id")
@SecuredAction(value = "workspace.read", type = ActionType.RESOURCE)
public void getDocumentProperties(final HttpServerRequest request) {
    documentDao.findById(request.params().get("id"), PROPERTIES_KEYS, new Handler<JsonObject>() {
        @Override/*www  .java2s . c o m*/
        public void handle(JsonObject res) {
            JsonObject result = res.getJsonObject("result");
            if ("ok".equals(res.getString("status")) && result != null) {
                renderJson(request, result);
            } else {
                notFound(request);
            }
        }
    });
}

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

License:Open Source License

private void getFile(final HttpServerRequest request, GenericDao dao, String owner, boolean publicOnly) {
    dao.findById(request.params().get("id"), owner, publicOnly, new Handler<JsonObject>() {
        @Override/* w  w  w.  j  a  v a  2  s. c o  m*/
        public void handle(JsonObject res) {
            String status = res.getString("status");
            JsonObject result = res.getJsonObject("result");
            String thumbSize = request.params().get("thumbnail");
            if ("ok".equals(status) && result != null) {
                String file;
                if (thumbSize != null && !thumbSize.trim().isEmpty()) {
                    file = result.getJsonObject("thumbnails", new JsonObject()).getString(thumbSize,
                            result.getString("file"));
                } else {
                    file = result.getString("file");
                }
                if (file != null && !file.trim().isEmpty()) {
                    boolean inline = inlineDocumentResponse(result, request.params().get("application"));
                    if (inline && ETag.check(request, file)) {
                        notModified(request, file);
                    } else {
                        storage.sendFile(file, result.getString("name"), request, inline,
                                result.getJsonObject("metadata"));
                    }
                    eventStore.createAndStoreEvent(WokspaceEvent.GET_RESOURCE.name(), request,
                            new JsonObject().put("resource", request.params().get("id")));
                } else {
                    request.response().setStatusCode(404).end();
                }
            } else {
                request.response().setStatusCode(404).end();
            }
        }
    });
}

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

License:Open Source License

private void deleteFile(final HttpServerRequest request, final GenericDao dao, String owner) {
    final String id = request.params().get("id");
    dao.findById(id, owner, new Handler<JsonObject>() {
        @Override//from   w  w w  .j a va 2s  .co  m
        public void handle(JsonObject res) {
            String status = res.getString("status");
            final JsonObject result = res.getJsonObject("result");
            if ("ok".equals(status) && result != null && result.getString("file") != null) {

                final String file = result.getString("file");
                Set<Entry<String, Object>> thumbnails = new HashSet<Entry<String, Object>>();
                if (result.containsKey("thumbnails")) {
                    thumbnails = result.getJsonObject("thumbnails").getMap().entrySet();
                }

                storage.removeFile(file, new Handler<JsonObject>() {
                    @Override
                    public void handle(JsonObject event) {
                        if (event != null && "ok".equals(event.getString("status"))) {
                            dao.delete(id, new Handler<JsonObject>() {
                                @Override
                                public void handle(final JsonObject result2) {
                                    if ("ok".equals(result2.getString("status"))) {
                                        deleteAllRevisions(id,
                                                new fr.wseduc.webutils.collections.JsonArray().add(file));
                                        decrementStorage(result, new Handler<Either<String, JsonObject>>() {
                                            @Override
                                            public void handle(Either<String, JsonObject> event) {
                                                renderJson(request, result2, 204);
                                            }
                                        });
                                    } else {
                                        renderError(request, result2);
                                    }
                                }
                            });
                        } else {
                            renderError(request, event);
                        }
                    }
                });

                //Delete thumbnails
                for (final Entry<String, Object> thumbnail : thumbnails) {
                    storage.removeFile(thumbnail.getValue().toString(), new Handler<JsonObject>() {
                        public void handle(JsonObject event) {
                            if (event == null || !"ok".equals(event.getString("status"))) {
                                log.error("Error while deleting thumbnail " + thumbnail);
                            }
                        }
                    });
                }
            } else {
                request.response().setStatusCode(404).end();
            }
        }
    });
}

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

License:Open Source License

private void copyFiles(final HttpServerRequest request, final String collection, final String owner,
        final UserInfos user) {
    String ids = request.params().get("ids"); // TODO refactor with json in request body
    String folder2 = getOrElse(request.params().get("folder"), "");
    try {/*from w w  w  .  j  a  v  a 2s . c  om*/
        folder2 = URLDecoder.decode(folder2, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        log.warn(e.getMessage(), e);
    }
    final String folder = folder2;
    if (ids != null && !ids.trim().isEmpty()) {
        JsonArray idsArray = new fr.wseduc.webutils.collections.JsonArray(Arrays.asList(ids.split(",")));
        String criteria = "{ \"_id\" : { \"$in\" : " + idsArray.encode() + "}";
        if (owner != null) {
            criteria += ", \"to\" : \"" + owner + "\"";
        }
        criteria += "}";
        mongo.find(collection, new JsonObject(criteria), new Handler<Message<JsonObject>>() {
            @Override
            public void handle(Message<JsonObject> r) {
                JsonObject src = r.body();
                if ("ok".equals(src.getString("status")) && src.getJsonArray("results") != null) {
                    final JsonArray origs = src.getJsonArray("results");
                    final JsonArray insert = new fr.wseduc.webutils.collections.JsonArray();
                    final AtomicInteger number = new AtomicInteger(origs.size());
                    emptySize(user, new Handler<Long>() {
                        @Override
                        public void handle(Long emptySize) {
                            long size = 0;
                            for (Object o : origs) {
                                if (!(o instanceof JsonObject))
                                    continue;
                                JsonObject metadata = ((JsonObject) o).getJsonObject("metadata");
                                if (metadata != null) {
                                    size += metadata.getLong("size", 0l);
                                }
                            }
                            if (size > emptySize) {
                                badRequest(request, "files.too.large");
                                return;
                            }
                            for (Object o : origs) {
                                JsonObject orig = (JsonObject) o;
                                final JsonObject dest = orig.copy();
                                String now = MongoDb.formatDate(new Date());
                                dest.remove("_id");
                                dest.remove("protected");
                                dest.remove("comments");
                                dest.put("application", WORKSPACE_NAME);
                                if (owner != null) {
                                    dest.put("owner", owner);
                                    dest.put("ownerName", dest.getString("toName"));
                                    dest.remove("to");
                                    dest.remove("from");
                                    dest.remove("toName");
                                    dest.remove("fromName");
                                } else if (user != null) {
                                    dest.put("owner", user.getUserId());
                                    dest.put("ownerName", user.getUsername());
                                    dest.put("shared", new fr.wseduc.webutils.collections.JsonArray());
                                }
                                dest.put("_id", UUID.randomUUID().toString());
                                dest.put("created", now);
                                dest.put("modified", now);
                                if (folder != null && !folder.trim().isEmpty()) {
                                    dest.put("folder", folder);
                                } else {
                                    dest.remove("folder");
                                }
                                insert.add(dest);
                                final String filePath = orig.getString("file");

                                if ((owner != null || user != null) && folder != null
                                        && !folder.trim().isEmpty()) {

                                    //If the document has a new parent folder, replicate sharing rights
                                    String parentName, parentFolder;
                                    if (folder.lastIndexOf('_') < 0) {
                                        parentName = folder;
                                        parentFolder = folder;
                                    } else if (filePath != null) {
                                        String[] splittedPath = folder.split("_");
                                        parentName = splittedPath[splittedPath.length - 1];
                                        parentFolder = folder;
                                    } else {
                                        String[] splittedPath = folder.split("_");
                                        parentName = splittedPath[splittedPath.length - 2];
                                        parentFolder = folder.substring(0, folder.lastIndexOf("_"));
                                    }

                                    folderService.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();

                                                    if (parentSharedRights != null
                                                            && parentSharedRights.size() > 0)
                                                        dest.put("shared", parentSharedRights);
                                                    if (filePath != null) {
                                                        storage.copyFile(filePath, new Handler<JsonObject>() {
                                                            @Override
                                                            public void handle(JsonObject event) {
                                                                if (event != null && "ok"
                                                                        .equals(event.getString("status"))) {
                                                                    dest.put("file", event.getString("_id"));
                                                                    persist(insert, number.decrementAndGet());
                                                                }
                                                            }
                                                        });
                                                    } else {
                                                        persist(insert, number.decrementAndGet());
                                                    }
                                                }
                                            });
                                } else if (filePath != null) {
                                    storage.copyFile(filePath, new Handler<JsonObject>() {

                                        @Override
                                        public void handle(JsonObject event) {
                                            if (event != null && "ok".equals(event.getString("status"))) {
                                                dest.put("file", event.getString("_id"));
                                                persist(insert, number.decrementAndGet());
                                            }
                                        }
                                    });
                                } else {
                                    persist(insert, number.decrementAndGet());
                                }
                            }
                        }
                    });
                } else {
                    renderJson(request, src, 404);
                }
            }

            private void persist(final JsonArray insert, int remains) {
                if (remains == 0) {
                    mongo.insert(DocumentDao.DOCUMENTS_COLLECTION, insert, new Handler<Message<JsonObject>>() {
                        @Override
                        public void handle(Message<JsonObject> inserted) {
                            if ("ok".equals(inserted.body().getString("status"))) {
                                incrementStorage(insert);
                                for (Object obj : insert) {
                                    JsonObject json = (JsonObject) obj;
                                    createRevision(json.getString("_id"), json.getString("file"),
                                            json.getString("name"), json.getString("owner"),
                                            json.getString("owner"), json.getString("ownerName"),
                                            json.getJsonObject("metadata"));
                                }
                                renderJson(request, inserted.body());
                            } else {
                                renderError(request, inserted.body());
                            }
                        }
                    });
                }
            }

        });
    } else {
        badRequest(request);
    }
}