List of usage examples for io.vertx.core.json JsonArray add
public JsonArray add(Object value)
From source file:org.entcore.timeline.services.impl.DefaultTimelineMailerService.java
License:Open Source License
@Override public void translateTimeline(JsonArray i18nKeys, String domain, String language, Handler<JsonArray> handler) { String i18n = eventsI18n.get(language.split(",")[0].split("-")[0]); final JsonObject timelineI18n; if (i18n == null) { timelineI18n = new JsonObject(); } else {//from www. ja va2 s . com timelineI18n = new JsonObject("{" + i18n.substring(0, i18n.length() - 1) + "}"); } timelineI18n.mergeIn(I18n.getInstance().load(language, domain)); JsonArray translations = new fr.wseduc.webutils.collections.JsonArray(); for (Object keyObj : i18nKeys) { String key = (String) keyObj; translations.add(timelineI18n.getString(key, key)); } handler.handle(translations); }
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 ww.j a va2 s . c om 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 .j av a2s . 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("[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
@Override public void getNotificationsDefaults(final Handler<JsonArray> handler) { configService.list(new Handler<Either<String, JsonArray>>() { public void handle(Either<String, JsonArray> event) { if (event.isLeft()) { handler.handle(null);/* ww w. j a v a 2 s. c om*/ } else { JsonArray config = event.right().getValue(); JsonArray notificationsList = new fr.wseduc.webutils.collections.JsonArray(); for (String key : registeredNotifications.keySet()) { JsonObject notif = new JsonObject(registeredNotifications.get(key)); notif.put("key", key); for (Object notifConfigObj : config) { JsonObject notifConfig = (JsonObject) notifConfigObj; if (notifConfig.getString("key", "").equals(key)) { notif.put("defaultFrequency", notifConfig.getString("defaultFrequency", notif.getString("defaultFrequency"))); notif.put("restriction", notifConfig.getString("restriction", notif.getString("restriction"))); break; } } notificationsList.add(notif); } handler.handle(notificationsList); } } }); }
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/*w w w .j a v a 2s. c o m*/ 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.timeline.services.impl.DefaultTimelineMailerService.java
License:Open Source License
/** * Retrieves an aggregated list of notifications from mongodb for a single user. * * Notifications are grouped by type & event-type. * @param userId : Userid//from w w w. j a v a 2 s .c o m * @param from : Starting date in the past * @param handler: Handles the notifications */ private void getAggregatedUserNotifications(String userId, 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("recipients") .elemMatch(QueryBuilder.start("userId").is(userId).get()).and("date").greaterThanEquals(from)); JsonObject grouper = new JsonObject( "{ \"_id\" : { \"type\": \"$type\", \"event-type\": \"$event-type\"}, \"count\": { \"$sum\": 1 } }"); JsonObject transformer = new JsonObject( "{ \"type\": \"$_id.type\", \"event-type\": \"$_id.event-type\", \"count\": 1, \"_id\": 0 }"); pipeline.add(new JsonObject().put("$match", matcher)); pipeline.add(new JsonObject().put("$group", grouper)); pipeline.add(new JsonObject().put("$project", transformer)); mongo.command(aggregation.toString(), new Handler<Message<JsonObject>>() { @Override public void handle(Message<JsonObject> event) { if ("error".equals(event.body().getString("status", "error"))) { handler.handle(new fr.wseduc.webutils.collections.JsonArray()); } else { handler.handle(event.body().getJsonObject("result", new JsonObject()).getJsonArray("result", new fr.wseduc.webutils.collections.JsonArray())); } } }); }
From source file:org.entcore.timeline.services.impl.FlashMsgServiceSqlImpl.java
License:Open Source License
@Override public void update(String id, JsonObject data, Handler<Either<String, JsonObject>> handler) { StringBuilder sb = new StringBuilder(); JsonArray values = new fr.wseduc.webutils.collections.JsonArray(); for (String attr : data.fieldNames()) { if ("startDate".equals(attr) || "endDate".equals(attr)) { sb.append("\"" + attr + "\"").append(" = ?::timestamptz, "); } else if ("contents".equals(attr) || "profiles".equals(attr)) { sb.append("\"" + attr + "\"").append(" = ?::jsonb, "); } else {//from w w w . j a v a 2s . co m sb.append("\"" + attr + "\"").append(" = ?, "); } values.add(data.getValue(attr)); } String query = "UPDATE " + resourceTable + " SET " + sb.toString() + "modified = NOW() " + "WHERE id = ? "; sql.prepared(query, values.add(parseId(id)), validRowsResultHandler(handler)); }
From source file:org.entcore.timeline.services.impl.FlashMsgServiceSqlImpl.java
License:Open Source License
@Override public void deleteMultiple(List<String> ids, Handler<Either<String, JsonObject>> handler) { String query = "DELETE FROM " + resourceTable + " WHERE id IN " + Sql.listPrepared(ids.toArray()); JsonArray values = new fr.wseduc.webutils.collections.JsonArray(); for (String id : ids) { try {/*www .j av a 2s . c o m*/ long idNb = Long.parseLong(id); values.add(idNb); } catch (NumberFormatException e) { log.error("Bad id - not a number : " + id.toString()); } } sql.prepared(query, values, validUniqueResultHandler(handler)); }
From source file:org.entcore.workspace.service.impl.DefaultFolderService.java
License:Open Source License
@Override public void copy(final String id, final String n, final String p, final UserInfos owner, final long emptySize, final Handler<Either<String, JsonArray>> result) { if (owner == null) { result.handle(new Either.Left<String, JsonArray>("workspace.invalid.user")); return;//from w ww. ja va 2 s . co m } if (id == null || id.trim().isEmpty()) { result.handle(new Either.Left<String, JsonArray>("workspace.folder.not.found")); return; } final String path = getOrElse(p, ""); //If the folder has a parent folder, replicate sharing rights String[] splittedPath = path.split("_"); String parentName = splittedPath[splittedPath.length - 1]; String parentFolder = path; 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(); QueryBuilder query = QueryBuilder.start("_id").is(id).put("owner").is(owner.getUserId()); JsonObject keys = new JsonObject().put("folder", 1).put("name", 1); mongo.findOne(DOCUMENTS_COLLECTION, MongoQueryBuilder.build(query), keys, new Handler<Message<JsonObject>>() { @Override public void handle(Message<JsonObject> event) { final String folder = event.body().getJsonObject("result", new JsonObject()) .getString("folder"); final String n1 = event.body().getJsonObject("result", new JsonObject()) .getString("name"); if ("ok".equals(event.body().getString("status")) && folder != null && !folder.trim().isEmpty() && n1 != null && !n1.trim().isEmpty()) { final String folderAttr = "folder"; QueryBuilder q = QueryBuilder.start("owner").is(owner.getUserId()) .put(folderAttr) .regex(Pattern.compile("^" + Pattern.quote(folder) + "($|_)")); mongo.find(DOCUMENTS_COLLECTION, MongoQueryBuilder.build(q), new Handler<Message<JsonObject>>() { @Override public void handle(Message<JsonObject> src) { final JsonArray origs = src.body().getJsonArray("results", new fr.wseduc.webutils.collections.JsonArray()); if ("ok".equals(src.body().getString("status")) && origs.size() > 0) { 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) { result.handle(new Either.Left<String, JsonArray>( "files.too.large")); return; } final AtomicInteger number = new AtomicInteger( origs.size()); final JsonArray insert = new fr.wseduc.webutils.collections.JsonArray(); String name = (n != null && !n.trim().isEmpty()) ? n : n1; final String destFolderName = (path != null && !path.trim().isEmpty()) ? path + "_" + name : name; QueryBuilder alreadyExist = QueryBuilder.start("owner") .is(owner.getUserId()).put("folder") .is(destFolderName); mongo.count(DOCUMENTS_COLLECTION, MongoQueryBuilder.build(alreadyExist), new Handler<Message<JsonObject>>() { @Override public void handle(Message<JsonObject> event) { String destFolder; if ("ok".equals( event.body().getString("status")) && event.body() .getInteger("count") == 0) { destFolder = destFolderName; } else { destFolder = destFolderName + "-" + format.format(new Date()); } for (Object o : origs) { if (!(o instanceof JsonObject)) continue; JsonObject orig = (JsonObject) o; final JsonObject dest = orig.copy(); String now = MongoDb .formatDate(new Date()); dest.remove("_id"); dest.put("created", now); dest.put("modified", now); dest.put("folder", dest .getString("folder", "") .replaceFirst( "^" + Pattern .quote(folder), Matcher.quoteReplacement( destFolder))); dest.put("shared", parentSharedRights); insert.add(dest); String filePath = orig .getString("file"); 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 { result.handle(new Either.Left<String, JsonArray>( "workspace.folder.not.found")); } } private void persist(final JsonArray insert, int remains) { if (remains == 0) { mongo.insert(DOCUMENTS_COLLECTION, insert, new Handler<Message<JsonObject>>() { @Override public void handle( Message<JsonObject> inserted) { if ("ok".equals(inserted.body() .getString("status"))) { result.handle( new Either.Right<String, JsonArray>( insert)); } else { result.handle( new Either.Left<String, JsonArray>( inserted.body() .getString( "message"))); } } }); } } }); } else { result.handle(new Either.Left<String, JsonArray>("workspace.folder.not.found")); } } }); } }); }
From source file:org.entcore.workspace.service.impl.DefaultFolderService.java
License:Open Source License
@Override public void delete(String id, final UserInfos owner, final Handler<Either<String, JsonArray>> result) { if (owner == null) { result.handle(new Either.Left<String, JsonArray>("workspace.invalid.user")); return;//from www .j a v a 2 s. co m } if (id == null || id.trim().isEmpty()) { result.handle(new Either.Left<String, JsonArray>("workspace.folder.not.found")); return; } QueryBuilder query = QueryBuilder.start("_id").is(id).put("owner").is(owner.getUserId()); JsonObject keys = new JsonObject().put("folder", 1); mongo.findOne(DOCUMENTS_COLLECTION, MongoQueryBuilder.build(query), keys, new Handler<Message<JsonObject>>() { @Override public void handle(Message<JsonObject> event) { String folder = event.body().getJsonObject("result", new JsonObject()).getString("folder"); if ("ok".equals(event.body().getString("status")) && folder != null && !folder.trim().isEmpty()) { QueryBuilder q = QueryBuilder.start("owner").is(owner.getUserId()).put("folder") .regex(Pattern.compile("^" + Pattern.quote(folder) + "($|_)")); JsonObject keys = new JsonObject().put("metadata", 1).put("owner", 1).put("name", 1) .put("file", 1); final JsonObject query = MongoQueryBuilder.build(q); mongo.find(DOCUMENTS_COLLECTION, query, null, keys, new Handler<Message<JsonObject>>() { @Override public void handle(Message<JsonObject> message) { final JsonArray results = message.body().getJsonArray("results"); if ("ok".equals(message.body().getString("status")) && results != null) { mongo.delete(DOCUMENTS_COLLECTION, query, new Handler<Message<JsonObject>>() { @Override public void handle(Message<JsonObject> res) { if ("ok".equals(res.body().getString("status"))) { result.handle( new Either.Right<String, JsonArray>(results)); final JsonArray filesIds = new fr.wseduc.webutils.collections.JsonArray(); for (Object o : results) { if (!(o instanceof JsonObject)) continue; String file = ((JsonObject) o).getString("file"); if (file != null && !file.trim().isEmpty()) { filesIds.add(file); } } if (filesIds.size() > 0) { storage.removeFiles(filesIds, new Handler<JsonObject>() { @Override public void handle( JsonObject jsonObject) { if (!"ok".equals(jsonObject .getString("status"))) { log.error( "Error deleting gridfs files : " + filesIds .encode()); log.error(jsonObject .getString("message")); } } }); } } else { result.handle(new Either.Left<String, JsonArray>( res.body().getString("message"))); } } }); } else { result.handle(new Either.Left<String, JsonArray>( message.body().getString("message"))); } } }); } else { result.handle(new Either.Left<String, JsonArray>("workspace.folder.not.found")); } } }); }