List of usage examples for com.mongodb QueryBuilder QueryBuilder
public QueryBuilder()
From source file:org.entcore.common.service.impl.MongoDbCrudService.java
License:Open Source License
@Override public void list(VisibilityFilter filter, UserInfos user, Handler<Either<String, JsonArray>> handler) { QueryBuilder query;/* w ww.j a va 2 s .c o m*/ if (user != null) { List<DBObject> groups = new ArrayList<>(); groups.add(QueryBuilder.start("userId").is(user.getUserId()).get()); for (String gpId : user.getGroupsIds()) { groups.add(QueryBuilder.start("groupId").is(gpId).get()); } switch (filter) { case OWNER: query = QueryBuilder.start("owner.userId").is(user.getUserId()); break; case OWNER_AND_SHARED: query = new QueryBuilder().or(QueryBuilder.start("owner.userId").is(user.getUserId()).get(), QueryBuilder.start("shared") .elemMatch(new QueryBuilder().or(groups.toArray(new DBObject[groups.size()])).get()) .get()); break; case SHARED: query = QueryBuilder.start("shared") .elemMatch(new QueryBuilder().or(groups.toArray(new DBObject[groups.size()])).get()); break; case PROTECTED: query = QueryBuilder.start("visibility").is(VisibilityFilter.PROTECTED.name()); break; case PUBLIC: query = QueryBuilder.start("visibility").is(VisibilityFilter.PUBLIC.name()); break; default: query = new QueryBuilder().or( QueryBuilder.start("visibility").is(VisibilityFilter.PUBLIC.name()).get(), QueryBuilder.start("visibility").is(VisibilityFilter.PROTECTED.name()).get(), QueryBuilder.start("owner.userId").is(user.getUserId()).get(), QueryBuilder.start("shared") .elemMatch(new QueryBuilder().or(groups.toArray(new DBObject[groups.size()])).get()) .get()); break; } } else { query = QueryBuilder.start("visibility").is(VisibilityFilter.PUBLIC.name()); } JsonObject sort = new JsonObject().put("modified", -1); mongo.find(collection, MongoQueryBuilder.build(query), sort, defaultListProjection, validResultsHandler(handler)); }
From source file:org.entcore.common.service.impl.MongoDbSearchService.java
License:Open Source License
@Override public void search(String userId, List<String> groupIds, List<String> returnFields, List<String> searchWords, Integer page, Integer limit, Handler<Either<String, JsonArray>> handler) { final int skip = (0 == page) ? -1 : page * limit; final List<DBObject> groups = new ArrayList<DBObject>(); groups.add(QueryBuilder.start("userId").is(userId).get()); for (String gpId : groupIds) { groups.add(QueryBuilder.start("groupId").is(gpId).get()); }/* w w w . j a va2s . c o m*/ final QueryBuilder worldsQuery = new QueryBuilder(); //no stemming (in fact, stemming works only with words and for a given language) and no list of stop words worldsQuery.text(textSearchedComposition(searchWords)); final QueryBuilder rightsOrQuery = new QueryBuilder().or( QueryBuilder.start("visibility").is(VisibilityFilter.PUBLIC.name()).get(), QueryBuilder.start("visibility").is(VisibilityFilter.PROTECTED.name()).get(), QueryBuilder.start(this.ownerUserId).is(userId).get(), QueryBuilder.start("shared") .elemMatch(new QueryBuilder().or(groups.toArray(new DBObject[groups.size()])).get()).get()); final QueryBuilder query = new QueryBuilder().and(worldsQuery.get(), rightsOrQuery.get()); JsonObject sort = new JsonObject().put("modified", -1); final JsonObject projection = new JsonObject(); for (String field : returnFields) { projection.put(field, 1); } mongo.find(collection, MongoQueryBuilder.build(query), sort, projection, skip, limit, Integer.MAX_VALUE, validResultsHandler(handler)); }
From source file:org.entcore.sandbox.filters.PageReadFilter.java
License:Open Source License
@Override public void authorize(HttpServerRequest request, Binding binding, UserInfos user, Handler<Boolean> handler) { System.out.println(">>>>>>> filter <<<<<<<<"); String sharedMethod = binding.getServiceMethod().replaceAll("\\.", "-"); String id = request.params().get(conf.getResourceIdLabel()); if (id != null && !id.trim().isEmpty()) { List<DBObject> groups = new ArrayList<>(); groups.add(QueryBuilder.start("userId").is(user.getUserId()).put(sharedMethod).is(true).get()); for (String gpId : user.getProfilGroupsIds()) { groups.add(QueryBuilder.start("groupId").is(gpId).put(sharedMethod).is(true).get()); }/*w w w . jav a2 s . c om*/ QueryBuilder query = QueryBuilder.start("_id").is(id).or( QueryBuilder.start("owner.userId").is(user.getUserId()).get(), QueryBuilder.start("visibility").is(VisibilityFilter.PUBLIC.name()).get(), QueryBuilder.start("visibility").is(VisibilityFilter.PROTECTED.name()).get(), QueryBuilder.start("shared") .elemMatch(new QueryBuilder().or(groups.toArray(new DBObject[groups.size()])).get()) .get()); MongoAppFilter.executeCountQuery(request, conf.getCollection(), MongoQueryBuilder.build(query), 1, handler); } else { handler.handle(false); } }
From source file:org.entcore.workspace.service.impl.DefaultFolderService.java
License:Open Source License
@Override public void trash(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.ja v a 2 s . c o m } if (id == null || id.trim().isEmpty()) { result.handle(new Either.Left<String, JsonObject>("workspace.folder.not.found")); return; } final QueryBuilder resourceQuery = QueryBuilder.start("_id").is(id); final List<DBObject> groups = new ArrayList<>(); groups.add(QueryBuilder.start("userId").is(owner.getUserId()).get()); for (String gpId : owner.getGroupsIds()) { groups.add(QueryBuilder.start("groupId").is(gpId).get()); } final QueryBuilder rightQuery = new QueryBuilder() .or(QueryBuilder.start("owner").is(owner.getUserId()).get(), QueryBuilder.start("shared") .elemMatch(new QueryBuilder().or(groups.toArray(new DBObject[groups.size()])).get()).get()); final QueryBuilder query = new QueryBuilder().and(resourceQuery.get(), rightQuery.get()); JsonObject keys = new JsonObject().put("folder", 1).put("name", 1).put("owner", 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 name = event.body().getJsonObject("result", new JsonObject()) .getString("name"); final String owner = event.body().getJsonObject("result", new JsonObject()) .getString("owner"); if ("ok".equals(event.body().getString("status")) && folder != null && !folder.trim().isEmpty()) { QueryBuilder q = QueryBuilder.start("owner").is(owner).put("folder") .regex(Pattern.compile("^" + Pattern.quote(folder) + "($|_)")); MongoUpdateBuilder modifier = new MongoUpdateBuilder(); modifier.rename("folder", "old-folder"); mongo.update(DOCUMENTS_COLLECTION, MongoQueryBuilder.build(q), modifier.build(), false, true, new Handler<Message<JsonObject>>() { @Override public void handle(Message<JsonObject> e) { if ("ok".equals(e.body().getString("status"))) { recursiveMove(folder, name, owner, "Trash", result); } else { result.handle(new Either.Left<String, JsonObject>( "workspace.trash.error")); } } }); } 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
@Override public void list(String path, UserInfos owner, boolean hierarchical, String filter, final Handler<Either<String, JsonArray>> results) { if (owner == null) { results.handle(new Either.Left<String, JsonArray>("workspace.invalid.user")); return;/* w w w .ja v a2s .com*/ } QueryBuilder q = QueryBuilder.start(); if ("shared".equals(filter)) { List<DBObject> groups = new ArrayList<>(); groups.add(QueryBuilder.start("userId").is(owner.getUserId()).get()); for (String gpId : owner.getGroupsIds()) { groups.add(QueryBuilder.start("groupId").is(gpId).get()); } q.put("shared").elemMatch(new QueryBuilder().or(groups.toArray(new DBObject[groups.size()])).get()); } else { q.put("owner").is(owner.getUserId()); } q.and("file").exists(false).and("application").is(WorkspaceService.WORKSPACE_NAME); if (path != null && !path.trim().isEmpty()) { if (hierarchical) { q = q.put("folder").regex(Pattern.compile("^" + Pattern.quote(path) + "_[^_]+$")); } else { q = q.put("folder").regex(Pattern.compile("^" + Pattern.quote(path) + "_")); } } else if (hierarchical) { q = q.put("folder").regex(Pattern.compile("^[^_]+$")); } mongo.find(DOCUMENTS_COLLECTION, MongoQueryBuilder.build(q), new Handler<Message<JsonObject>>() { @Override public void handle(Message<JsonObject> res) { results.handle(Utils.validResults(res)); } }); }
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. ja v a 2s. c om*/ } 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.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()); }/* ww w .java2s .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.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 ww. j a v a 2 s. c om*/ 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.keycloak.authorization.mongo.store.MongoPolicyStore.java
License:Open Source License
@Override public Policy findByName(String name, String resourceServerId) { DBObject query = new QueryBuilder().and("resourceServerId").is(resourceServerId).and("name").is(name).get(); return getMongoStore().loadEntities(PolicyEntity.class, query, getInvocationContext()).stream() .map(policyEntity -> findById(policyEntity.getId())).findFirst().orElse(null); }
From source file:org.keycloak.authorization.mongo.store.MongoPolicyStore.java
License:Open Source License
@Override public List<Policy> findByResourceServer(String resourceServerId) { DBObject query = new QueryBuilder().and("resourceServerId").is(resourceServerId).get(); return getMongoStore().loadEntities(PolicyEntity.class, query, getInvocationContext()).stream() .map(policyEntity -> findById(policyEntity.getId())).collect(toList()); }