Example usage for com.mongodb QueryBuilder start

List of usage examples for com.mongodb QueryBuilder start

Introduction

In this page you can find the example usage for com.mongodb QueryBuilder start.

Prototype

public static QueryBuilder start(final String key) 

Source Link

Document

Creates a new query with a document key

Usage

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;//w  w w  .  ja va 2s  . c o 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"));
                    }
                }
            });
}

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

License:Open Source License

@Override
public void restore(String id, final UserInfos owner, final Handler<Either<String, JsonObject>> result) {
    if (owner == null) {
        result.handle(new Either.Left<String, JsonObject>("workspace.invalid.user"));
        return;/*from ww  w.j av a 2  s.c o  m*/
    }
    if (id == null || id.trim().isEmpty()) {
        result.handle(new Either.Left<String, JsonObject>("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) {
                    final 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) + "($|_)")).put("old-folder")
                                .exists(true);
                        MongoUpdateBuilder modifier = new MongoUpdateBuilder();
                        modifier.rename("old-folder", "folder");
                        mongo.update(DOCUMENTS_COLLECTION, MongoQueryBuilder.build(q), modifier.build(), false,
                                true, new Handler<Message<JsonObject>>() {
                                    @Override
                                    public void handle(Message<JsonObject> res) {
                                        result.handle(Utils.validResult(res));
                                    }
                                });
                    } else {
                        result.handle(new Either.Left<String, JsonObject>("workspace.folder.not.found"));
                    }
                }
            });
}

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

License:Open Source License

private void shareFolderAction(final String id, final UserInfos owner, final List<String> actions,
        final String groupId, final String userId, final ShareService shareService, final boolean remove,
        final JsonObject share, final Handler<Either<String, JsonObject>> result) {

    if (owner == null) {
        result.handle(new Either.Left<String, JsonObject>("workspace.invalid.user"));
        return;/*  w  w w.j av a  2 s .c  o  m*/
    }
    if (id == null || id.trim().isEmpty()) {
        result.handle(new Either.Left<String, JsonObject>("workspace.folder.not.found"));
        return;
    }

    String sharedMethod = "org-entcore-workspace-service-WorkspaceService|shareJsonSubmit";

    List<DBObject> groups = new ArrayList<>();
    groups.add(QueryBuilder.start("userId").is(owner.getUserId()).put(sharedMethod).is(true).get());
    for (String gpId : owner.getGroupsIds()) {
        groups.add(QueryBuilder.start("groupId").is(gpId).put(sharedMethod).is(true).get());
    }

    final DBObject managerCheck = QueryBuilder.start("shared")
            .elemMatch(new QueryBuilder().or(groups.toArray(new DBObject[groups.size()])).get()).get();

    QueryBuilder query = QueryBuilder.start("_id").is(id).put("file").exists(false)
            .or(QueryBuilder.start("owner").is(owner.getUserId()).get(), managerCheck);

    JsonObject keys = new JsonObject().put("folder", 1).put("name", 1);

    Handler<Message<JsonObject>> folderHandler = new Handler<Message<JsonObject>>() {
        @Override
        public void handle(Message<JsonObject> event) {
            final String folder = event.body().getJsonObject("result", new JsonObject()).getString("folder");

            QueryBuilder q = QueryBuilder.start()
                    .or(QueryBuilder.start("owner").is(owner.getUserId()).get(), managerCheck).put("folder")
                    .regex(Pattern.compile("^" + Pattern.quote(folder) + "($|_)")).put("_id").notEquals(id);

            mongo.find(DOCUMENTS_COLLECTION, MongoQueryBuilder.build(q), new Handler<Message<JsonObject>>() {

                public void handle(Message<JsonObject> d) {

                    JsonArray files = d.body().getJsonArray("results",
                            new fr.wseduc.webutils.collections.JsonArray());

                    if ("ok".equals(d.body().getString("status"))) {

                        if (files.size() == 0) {
                            result.handle(new Either.Right<String, JsonObject>(
                                    new JsonObject("{ \"number\": 0, \"number-errors\": 0 }")));
                            return;
                        }

                        final AtomicInteger remaining = new AtomicInteger(files.size());
                        final AtomicInteger count = new AtomicInteger(0);
                        final AtomicInteger errorcount = new AtomicInteger(0);

                        Handler<Either<String, JsonObject>> recursiveHandler = new Handler<Either<String, JsonObject>>() {
                            @Override
                            public void handle(Either<String, JsonObject> event) {
                                if (event.isRight())
                                    count.getAndAdd(1);
                                else
                                    errorcount.getAndAdd(1);

                                if (remaining.decrementAndGet() == 0) {
                                    JsonObject response = new JsonObject();
                                    response.put("number", count);
                                    response.put("number-errors", errorcount);
                                    result.handle(new Either.Right<String, JsonObject>(response));
                                }
                            }
                        };

                        for (Object o : files) {
                            if (!(o instanceof JsonObject))
                                continue;
                            JsonObject file = (JsonObject) o;

                            if (share != null) {
                                shareService.share(owner.getUserId(), file.getString("_id"), share,
                                        recursiveHandler);
                            } else {
                                if (groupId != null) {
                                    if (remove)
                                        shareService.removeGroupShare(groupId, file.getString("_id"), actions,
                                                recursiveHandler);
                                    else
                                        shareService.groupShare(owner.getUserId(), groupId,
                                                file.getString("_id"), actions, recursiveHandler);
                                } else if (userId != null) {
                                    if (remove)
                                        shareService.removeUserShare(userId, file.getString("_id"), actions,
                                                recursiveHandler);
                                    else
                                        shareService.userShare(owner.getUserId(), userId, file.getString("_id"),
                                                actions, recursiveHandler);
                                }
                            }
                        }

                    } else {
                        result.handle(new Either.Left<String, JsonObject>("workspace.folder.not.found"));
                    }
                }
            });

        }
    };

    mongo.findOne(DOCUMENTS_COLLECTION, MongoQueryBuilder.build(query), keys, folderHandler);
}

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

License:Open Source License

public void rename(String id, final String newName, final UserInfos owner,
        final Handler<Either<String, JsonObject>> result) {
    if (owner == null) {
        result.handle(new Either.Left<String, JsonObject>("workspace.invalid.user"));
        return;//w ww  .j a  v  a2 s  . co m
    }
    if (id == null || id.trim().isEmpty()) {
        result.handle(new Either.Left<String, JsonObject>("workspace.folder.not.found"));
        return;
    }

    final QueryBuilder query = QueryBuilder.start("_id").is(id).put("owner").is(owner.getUserId()).and("file")
            .exists(false);
    final JsonObject keys = new JsonObject().put("folder", 1).put("name", 1);

    Handler<Message<JsonObject>> folderHandler = new Handler<Message<JsonObject>>() {
        @Override
        public void handle(Message<JsonObject> event) {
            final String folder = event.body().getJsonObject("result", new JsonObject()).getString("folder");
            final String newFolderPath = folder.lastIndexOf("_") < 0 ? newName
                    : folder.substring(0, folder.lastIndexOf("_") + 1) + newName;

            //3 - Find & rename children
            final Handler<Message<JsonObject>> renameChildren = new Handler<Message<JsonObject>>() {
                public void handle(Message<JsonObject> event) {

                    if (!"ok".equals(event.body().getString("status"))) {
                        result.handle(Utils.validResult(event));
                        return;
                    }

                    QueryBuilder targetQuery = QueryBuilder.start("owner").is(owner.getUserId());
                    targetQuery.or(
                            QueryBuilder.start("folder")
                                    .regex(Pattern.compile("^" + Pattern.quote(folder) + "($|_)")).get(),
                            QueryBuilder.start("old-folder")
                                    .regex(Pattern.compile("^" + Pattern.quote(folder) + "($|_)")).get());

                    mongo.find(DOCUMENTS_COLLECTION, MongoQueryBuilder.build(targetQuery),
                            new Handler<Message<JsonObject>>() {
                                @Override
                                public void handle(Message<JsonObject> d) {
                                    JsonArray children = d.body().getJsonArray("results",
                                            new fr.wseduc.webutils.collections.JsonArray());
                                    if ("ok".equals(d.body().getString("status")) && children.size() > 0) {
                                        final AtomicInteger remaining = new AtomicInteger(children.size());
                                        final AtomicInteger count = new AtomicInteger(0);

                                        Handler<Message<JsonObject>> recursiveHandler = new Handler<Message<JsonObject>>() {
                                            @Override
                                            public void handle(Message<JsonObject> res) {
                                                count.getAndAdd(res.body().getInteger("number", 0));
                                                if (remaining.decrementAndGet() == 0) {
                                                    res.body().put("number", count.get());
                                                    result.handle(Utils.validResult(res));
                                                }
                                            }
                                        };

                                        for (Object o : children) {
                                            if (!(o instanceof JsonObject)) {
                                                remaining.decrementAndGet();
                                                continue;
                                            }
                                            JsonObject child = (JsonObject) o;

                                            String childFolder = child.getString("folder");
                                            String childOldFolder = child.getString("old-folder");
                                            String id = child.getString("_id");

                                            JsonObject updateMatcher = MongoQueryBuilder
                                                    .build(QueryBuilder.start("_id").is(id));
                                            MongoUpdateBuilder updateModifier = new MongoUpdateBuilder();
                                            if (childOldFolder != null || childFolder.equals("Trash")) {
                                                String newPath = childOldFolder.lastIndexOf("_") < 0 ? newName
                                                        : childOldFolder.replaceFirst(Pattern.quote(folder),
                                                                Matcher.quoteReplacement(newFolderPath));
                                                updateModifier.set("old-folder", newPath);
                                            } else {
                                                String newPath = childFolder.lastIndexOf("_") < 0 ? newName
                                                        : childFolder.replaceFirst(Pattern.quote(folder),
                                                                Matcher.quoteReplacement(newFolderPath));
                                                updateModifier.set("folder", newPath);
                                            }

                                            mongo.update(DOCUMENTS_COLLECTION, updateMatcher,
                                                    updateModifier.build(), recursiveHandler);
                                        }

                                    } else {
                                        result.handle(Utils.validResult(d));
                                    }
                                }
                            });
                }
            };

            //2 - Rename target folder
            mongo.update(DOCUMENTS_COLLECTION, MongoQueryBuilder.build(query), new JsonObject(
                    "{ \"$set\": { \"folder\": \"" + newFolderPath + "\", \"name\": \"" + newName + "\" }}"),
                    renameChildren);
        }
    };

    //1 - Find the folder
    mongo.findOne(DOCUMENTS_COLLECTION, MongoQueryBuilder.build(query), keys, folderHandler);
}

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

License:Open Source License

@Override
public void exportResources(final String exportId, final String userId, JsonArray g, final String exportPath,
        final String locale, String host, final Handler<Boolean> handler) {
    log.debug("Workspace export resources.");
    List<DBObject> groups = new ArrayList<>();
    groups.add(QueryBuilder.start("userId").is(userId).get());
    for (Object o : g) {
        if (!(o instanceof String))
            continue;
        String gpId = (String) o;
        groups.add(QueryBuilder.start("groupId").is(gpId).get());
    }//from www  .  ja va 2s . c  o m
    QueryBuilder b = new QueryBuilder().or(QueryBuilder.start("owner").is(userId).get(),
            QueryBuilder.start("shared")
                    .elemMatch(new QueryBuilder().or(groups.toArray(new DBObject[groups.size()])).get()).get(),
            QueryBuilder.start("old_shared")
                    .elemMatch(new QueryBuilder().or(groups.toArray(new DBObject[groups.size()])).get()).get())
            .put("file").exists(true);
    final JsonObject keys = new JsonObject().put("file", 1).put("name", 1);
    final JsonObject query = MongoQueryBuilder.build(b);
    mongo.find(DocumentDao.DOCUMENTS_COLLECTION, query, null, keys, new Handler<Message<JsonObject>>() {
        @Override
        public void handle(Message<JsonObject> event) {
            final AtomicBoolean exported = new AtomicBoolean(false);
            final JsonArray documents = event.body().getJsonArray("results");
            if ("ok".equals(event.body().getString("status")) && documents != null) {
                QueryBuilder b = QueryBuilder.start("to").is(userId).put("file").exists(true);
                final JsonObject q = MongoQueryBuilder.build(b);
                mongo.find(RackDao.RACKS_COLLECTION, q, null, keys, new Handler<Message<JsonObject>>() {
                    @Override
                    public void handle(Message<JsonObject> event) {
                        JsonArray racks = event.body().getJsonArray("results");
                        if ("ok".equals(event.body().getString("status")) && racks != null) {
                            final Set<String> usedFileName = new HashSet<>();
                            final JsonObject alias = new JsonObject();
                            final String[] ids = new String[racks.size() + documents.size()];
                            for (int i = 0; i < documents.size(); i++) {
                                JsonObject j = documents.getJsonObject(i);
                                ids[i] = j.getString("file");
                                String fileName = j.getString("name");
                                if (fileName != null && fileName.contains("/")) {
                                    fileName = fileName.replaceAll("/", "-");
                                }
                                if (usedFileName.add(fileName)) {
                                    alias.put(ids[i], fileName);
                                } else {
                                    alias.put(ids[i], ids[i] + "_" + fileName);
                                }
                            }
                            for (int i = 0; i < racks.size(); i++) {
                                JsonObject j = racks.getJsonObject(i);
                                ids[i] = j.getString("file");
                                String fileName = j.getString("name");
                                if (fileName != null && fileName.contains("/")) {
                                    fileName = fileName.replaceAll("/", "-");
                                }
                                if (usedFileName.add(fileName)) {
                                    alias.put(ids[i], fileName);
                                } else {
                                    alias.put(ids[i], ids[i] + "_" + fileName);
                                }
                            }
                            exportFiles(alias, ids, exportPath, locale, exported, handler);
                        } else {
                            log.error("Rack " + q.encode() + " - " + event.body().getString("message"));
                            handler.handle(exported.get());
                        }
                    }
                });
            } else {
                log.error("Documents " + query.encode() + " - " + event.body().getString("message"));
                handler.handle(exported.get());
            }
        }
    });
}

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

License:Open Source License

@Override
public void deleteGroups(JsonArray groups) {
    for (Object o : groups) {
        if (!(o instanceof JsonObject))
            continue;
        final JsonObject j = (JsonObject) o;
        final JsonObject query = MongoQueryBuilder
                .build(QueryBuilder.start("shared.groupId").is(j.getString("group")));
        final Handler<Message<JsonObject>> handler = new Handler<Message<JsonObject>>() {
            @Override//  ww  w .j  a va2 s.  c o  m
            public void handle(Message<JsonObject> event) {
                if (!"ok".equals(event.body().getString("status"))) {
                    log.error("Error updating documents with group " + j.getString("group") + " : "
                            + event.body().encode());
                } else {
                    log.info("Documents with group " + j.getString("group") + " updated : "
                            + event.body().getInteger("number"));
                }
            }
        };
        if (shareOldGroupsToUsers) {
            JsonArray userShare = new fr.wseduc.webutils.collections.JsonArray();
            for (Object u : j.getJsonArray("users")) {
                JsonObject share = new JsonObject().put("userId", u.toString())
                        .put("org-entcore-workspace-service-WorkspaceService|copyDocuments", true)
                        .put("org-entcore-workspace-service-WorkspaceService|getDocument", true);
                userShare.add(share);
            }
            JsonObject update = new JsonObject().put("$addToSet",
                    new JsonObject().put("shared", new JsonObject().put("$each", userShare)));
            mongo.update(DocumentDao.DOCUMENTS_COLLECTION, query, update, false, true, handler);
        } else {
            final MongoUpdateBuilder update = new MongoUpdateBuilder()
                    .pull("shared", new JsonObject().put("groupId", j.getString("group")))
                    .addToSet("old_shared", new JsonObject().put("groupId", j.getString("group")));
            mongo.update(DocumentDao.DOCUMENTS_COLLECTION, query, update.build(), false, true, handler);
        }
    }
}

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

License:Open Source License

@Override
public void deleteUsers(JsonArray users) {
    String[] userIds = new String[users.size()];
    for (int i = 0; i < users.size(); i++) {
        JsonObject j = users.getJsonObject(i);
        String id = j.getString("id");
        userIds[i] = id;//from w  w  w.j a  v a  2s.  c o m
    }
    final JsonObject queryDocuments = MongoQueryBuilder.build(QueryBuilder.start("owner").in(userIds));
    deleteFiles(queryDocuments, DocumentDao.DOCUMENTS_COLLECTION);
    final JsonObject queryRacks = MongoQueryBuilder.build(QueryBuilder.start("to").in(userIds));
    deleteFiles(queryRacks, RackDao.RACKS_COLLECTION);
    deleteFiles(queryDocuments, Workspace.REVISIONS_COLLECTION);

    final JsonObject query = MongoQueryBuilder.build(QueryBuilder.start("shared.userId").in(userIds));
    JsonObject update = new JsonObject().put("$pull",
            new JsonObject().put("shared", MongoQueryBuilder.build(QueryBuilder.start("userId").in(userIds))));
    mongo.update(DocumentDao.DOCUMENTS_COLLECTION, query, update, false, true,
            new Handler<Message<JsonObject>>() {
                @Override
                public void handle(Message<JsonObject> event) {
                    if (!"ok".equals(event.body().getString("status"))) {
                        log.error(event.body().getString("message"));
                    }
                }
            });
}

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

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public void searchResource(List<String> appFilters, final String userId, JsonArray groupIds,
        JsonArray searchWords, Integer page, Integer limit, final JsonArray columnsHeader, final String locale,
        final Handler<Either<String, JsonArray>> handler) {
    if (appFilters.contains(WorkspaceSearchingEvents.class.getSimpleName())) {

        final List<String> searchWordsLst = searchWords.getList();

        final List<String> groupIdsLst = groupIds.getList();
        final List<DBObject> groups = new ArrayList<>();
        groups.add(QueryBuilder.start("userId").is(userId).get());
        for (String gpId : groupIdsLst) {
            groups.add(QueryBuilder.start("groupId").is(gpId).get());
        }// w  w  w . j  a  v a 2 s. c  o m

        final QueryBuilder rightsQuery = new QueryBuilder().or(
                QueryBuilder.start("visibility").is(VisibilityFilter.PUBLIC.name()).get(),
                QueryBuilder.start("visibility").is(VisibilityFilter.PROTECTED.name()).get(),
                QueryBuilder.start("visibility").is(VisibilityFilter.PROTECTED.name()).get(),
                QueryBuilder.start("owner").is(userId).get(),
                QueryBuilder.start("shared")
                        .elemMatch(new QueryBuilder().or(groups.toArray(new DBObject[groups.size()])).get())
                        .get());

        final QueryBuilder worldsQuery = new QueryBuilder();
        worldsQuery.text(MongoDbSearchService.textSearchedComposition(searchWordsLst));

        //searching only the file entry (not folder), if folder match and is returned, the paginate system is impacted
        final QueryBuilder fileQuery = QueryBuilder.start("file").exists(true);

        final QueryBuilder query = new QueryBuilder().and(fileQuery.get(), rightsQuery.get(),
                worldsQuery.get());

        JsonObject sort = new JsonObject().put("modified", -1);
        final JsonObject projection = new JsonObject();
        projection.put("name", 1);
        projection.put("modified", 1);
        projection.put("folder", 1);
        projection.put("owner", 1);
        projection.put("ownerName", 1);
        projection.put("comments", 1);

        final int skip = (0 == page) ? -1 : page * limit;

        //main search on file
        mongo.find(this.collection, MongoQueryBuilder.build(query), sort, projection, skip, limit,
                Integer.MAX_VALUE, validResultsHandler(new Handler<Either<String, JsonArray>>() {
                    @Override
                    public void handle(Either<String, JsonArray> event) {

                        if (event.isRight()) {
                            final JsonArray globalJa = event.right().getValue();
                            //different owner can have the same folder name
                            //if the folder exists, we must find id of folder according to the directory name and the owner,
                            //it's necessary to use the front route for the resource link
                            final QueryBuilder foldersOwnersOrQuery = new QueryBuilder();
                            Boolean isFolderProcessing = false;

                            for (int i = 0; i < globalJa.size(); i++) {
                                final JsonObject j = globalJa.getJsonObject(i);

                                // processing only files that have a folder
                                if (j != null && !StringUtils.isEmpty(j.getString("folder"))) {
                                    isFolderProcessing = true;
                                    final QueryBuilder folderOwnerQuery = new QueryBuilder();
                                    folderOwnerQuery.and(
                                            QueryBuilder.start("folder").is(j.getString("folder")).get(),
                                            QueryBuilder.start("owner").is(j.getString("owner")).get());
                                    foldersOwnersOrQuery.or(folderOwnerQuery.get());
                                }
                            }

                            final Map<String, Map<String, String>> mapOwnerMapNameFolderId = new HashMap<>();
                            //finding ids of folder found.
                            if (isFolderProcessing) {
                                //find only authorized folder entry and not file
                                final QueryBuilder queryFindFolderIds = new QueryBuilder().and(
                                        QueryBuilder.start("file").exists(false).get(), rightsQuery.get(),
                                        foldersOwnersOrQuery.get());
                                //search all folder of main result set and format the search result
                                findFoldersIdAndFormatResult(globalJa, queryFindFolderIds, columnsHeader,
                                        searchWordsLst, locale, userId, handler);
                            } else {
                                //all files without folder
                                final JsonArray res = formatSearchResult(globalJa, columnsHeader,
                                        searchWordsLst, locale, userId, mapOwnerMapNameFolderId);
                                handler.handle(new Either.Right<String, JsonArray>(res));
                            }
                        } else {
                            handler.handle(new Either.Left<String, JsonArray>(event.left().getValue()));
                        }
                        if (log.isDebugEnabled()) {
                            log.debug(
                                    "[WorkspaceSearchingEvents][searchResource] The resources searched by user are finded");
                        }
                    }
                }));
    } else {
        handler.handle(new Either.Right<String, JsonArray>(new fr.wseduc.webutils.collections.JsonArray()));
    }
}

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

License:Open Source License

private void notifyComment(final HttpServerRequest request, final String id, final UserInfos user,
        final boolean isFolder) {
    final JsonObject params = new JsonObject()
            .put("userUri", "/userbook/annuaire#" + user.getUserId() + "#" + user.getType())
            .put("userName", user.getUsername()).put("appPrefix", pathPrefix + "/workspace");

    final String notifyName = WORKSPACE_NAME.toLowerCase() + "." + (isFolder ? "comment-folder" : "comment");

    //Retrieve the document from DB
    mongo.findOne(DocumentDao.DOCUMENTS_COLLECTION, new JsonObject().put("_id", id),
            new Handler<Message<JsonObject>>() {
                @Override/*from www. j  a v a2s.  c o  m*/
                public void handle(Message<JsonObject> event) {
                    if ("ok".equals(event.body().getString("status"))
                            && event.body().getJsonObject("result") != null) {
                        final JsonObject document = event.body().getJsonObject("result");
                        params.put("resourceName", document.getString("name", ""));

                        //Handle the parent folder id (null if document is at root level)
                        final Handler<String> folderIdHandler = new Handler<String>() {
                            public void handle(final String folderId) {

                                //Send the notification to the shared network
                                Handler<List<String>> shareNotificationHandler = new Handler<List<String>>() {
                                    public void handle(List<String> recipients) {
                                        JsonObject sharedNotifParams = params.copy();

                                        if (folderId != null) {
                                            sharedNotifParams.put("resourceUri",
                                                    pathPrefix + "/workspace#/shared/folder/" + folderId);
                                        } else {
                                            sharedNotifParams.put("resourceUri",
                                                    pathPrefix + "/workspace#/shared");
                                        }

                                        // don't send comment with share uri at owner
                                        final String o = document.getString("owner");
                                        if (o != null && recipients.contains(o)) {
                                            recipients.remove(o);
                                        }
                                        notification.notifyTimeline(request, notifyName, user, recipients, id,
                                                sharedNotifParams);
                                    }
                                };

                                //'Flatten' the share users & group into a user id list (excluding the current user)
                                flattenShareIds(
                                        document.getJsonArray("shared",
                                                new fr.wseduc.webutils.collections.JsonArray()),
                                        user, shareNotificationHandler);

                                //If the user commenting is not the owner, send a notification to the owner
                                if (!document.getString("owner").equals(user.getUserId())) {
                                    JsonObject ownerNotif = params.copy();
                                    ArrayList<String> ownerList = new ArrayList<>();
                                    ownerList.add(document.getString("owner"));

                                    if (folderId != null) {
                                        ownerNotif.put("resourceUri",
                                                pathPrefix + "/workspace#/folder/" + folderId);
                                    } else {
                                        ownerNotif.put("resourceUri", pathPrefix + "/workspace");
                                    }
                                    notification.notifyTimeline(request, notifyName, user, ownerList, id, null,
                                            ownerNotif, true);
                                }

                            }
                        };

                        //Handle the parent folder result from DB
                        Handler<Message<JsonObject>> folderHandler = new Handler<Message<JsonObject>>() {
                            public void handle(Message<JsonObject> event) {
                                if (!"ok".equals(event.body().getString("status"))
                                        || event.body().getJsonObject("result") == null) {
                                    log.error(
                                            "Unable to send timeline notification : invalid parent folder on resource "
                                                    + id);
                                    return;
                                }

                                final JsonObject folder = event.body().getJsonObject("result");
                                final String folderId = folder.getString("_id");

                                folderIdHandler.handle(folderId);
                            }
                        };

                        //If the document does not have a parent folder
                        if (!isFolder && !document.containsKey("folder") || isFolder
                                && document.getString("folder").equals(document.getString("name"))) {
                            folderIdHandler.handle(null);
                        } else {
                            //If the document has a parent folder
                            String parentFolderPath = document.getString("folder");
                            if (isFolder) {
                                parentFolderPath = parentFolderPath.substring(0,
                                        parentFolderPath.lastIndexOf("_"));
                            }

                            QueryBuilder query = QueryBuilder.start("folder").is(parentFolderPath).and("file")
                                    .exists(false).and("owner").is(document.getString("owner"));

                            //Retrieve the parent folder from DB
                            mongo.findOne(DocumentDao.DOCUMENTS_COLLECTION, MongoQueryBuilder.build(query),
                                    folderHandler);
                        }

                    } else {
                        log.error("Unable to send timeline notification : missing name on resource " + id);
                    }
                }
            });
}

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

License:Open Source License

@Delete("/document/:id/comment/:commentId")
@SecuredAction(value = "workspace.manager", type = ActionType.RESOURCE)
public void deleteComment(final HttpServerRequest request) {
    final String id = request.params().get("id");
    final String commentId = request.params().get("commentId");

    QueryBuilder query = QueryBuilder.start("_id").is(id);
    MongoUpdateBuilder queryUpdate = new MongoUpdateBuilder().pull("comments",
            new JsonObject().put("id", commentId));

    mongo.update(DocumentDao.DOCUMENTS_COLLECTION, MongoQueryBuilder.build(query), queryUpdate.build(),
            MongoDbResult.validActionResultHandler(defaultResponseHandler(request)));
}