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.common.service.impl.MongoDbRepositoryEvents.java

License:Open Source License

@Override
public void deleteUsers(JsonArray users) {
    if (users == null || users.size() == 0) {
        return;//  w  w w  .j  ava2  s  .  c o  m
    }

    final String[] userIds = new String[users.size()];
    for (int i = 0; i < users.size(); i++) {
        JsonObject j = users.getJsonObject(i);
        userIds[i] = j.getString("id");
    }

    final JsonObject criteria = MongoQueryBuilder.build(QueryBuilder.start("shared.userId").in(userIds));

    MongoUpdateBuilder modifier = new MongoUpdateBuilder();
    modifier.pull("shared", MongoQueryBuilder.build(QueryBuilder.start("userId").in(userIds)));

    final String collection = MongoDbConf.getInstance().getCollection();
    if (collection == null || collection.trim().isEmpty()) {
        log.error("Error deleting groups : invalid collection " + collection + " in class "
                + this.getClass().getName());
        return;
    }
    mongo.update(collection, criteria, modifier.build(), false, true, new Handler<Message<JsonObject>>() {
        @Override
        public void handle(Message<JsonObject> event) {
            if (!"ok".equals(event.body().getString("status"))) {
                log.error("Error deleting users shared in collection " + collection + " : "
                        + event.body().getString("message"));
            }

            final JsonObject criteria = MongoQueryBuilder.build(QueryBuilder.start("owner.userId").in(userIds));
            MongoUpdateBuilder modifier = new MongoUpdateBuilder();
            modifier.set("owner.deleted", true);
            mongo.update(collection, criteria, modifier.build(), false, true,
                    new Handler<Message<JsonObject>>() {
                        @Override
                        public void handle(Message<JsonObject> event) {
                            if (!"ok".equals(event.body().getString("status"))) {
                                log.error("Error deleting users shared in collection " + collection + " : "
                                        + event.body().getString("message"));
                            } else if (managerRight != null && !managerRight.trim().isEmpty()) {
                                removeObjects(collection);
                            }
                        }
                    });
        }
    });
}

From source file:org.entcore.common.service.impl.MongoDbRepositoryEvents.java

License:Open Source License

protected void removeObjects(final String collection) {
    JsonObject matcher = MongoQueryBuilder
            .build(QueryBuilder.start("shared." + managerRight).notEquals(true).put("owner.deleted").is(true));

    JsonObject projection = new JsonObject().put("_id", 1);

    // Get ids of objects who have no manager and no owner (owner has just been deleted, or has been deleted previously)
    mongo.find(collection, matcher, null, projection, new Handler<Message<JsonObject>>() {
        @Override//  ww w .java2s  .  co  m
        public void handle(Message<JsonObject> event) {
            JsonArray res = event.body().getJsonArray("results");
            if (!"ok".equals(event.body().getString("status"))) {
                log.error("Error when finding objects who have no manager and no owner : "
                        + event.body().getString("message"));
            } else if (res == null || res.size() == 0) {
                log.info("There are no objects without manager and without owner : no objects to delete");
            } else {
                final String[] objectIds = new String[res.size()];
                for (int i = 0; i < res.size(); i++) {
                    JsonObject j = res.getJsonObject(i);
                    objectIds[i] = j.getString("_id");
                }
                JsonObject matcher = MongoQueryBuilder.build(QueryBuilder.start("_id").in(objectIds));
                mongo.delete(collection, matcher, new Handler<Message<JsonObject>>() {
                    @Override
                    public void handle(Message<JsonObject> event) {
                        if (!"ok".equals(event.body().getString("status"))) {
                            log.error("Error deleting objects in collection " + collection + " : "
                                    + event.body().getString("message"));
                        } else if (revisionsCollection != null && !revisionsCollection.trim().isEmpty()
                                && revisionIdAttribute != null && !revisionIdAttribute.trim().isEmpty()) {
                            JsonObject criteria = MongoQueryBuilder
                                    .build(QueryBuilder.start(revisionIdAttribute).in(objectIds));
                            mongo.delete(revisionsCollection, criteria, new Handler<Message<JsonObject>>() {
                                @Override
                                public void handle(Message<JsonObject> event) {
                                    if (!"ok".equals(event.body().getString("status"))) {
                                        log.error("Error deleting revisions objects in collection "
                                                + revisionsCollection + " : "
                                                + event.body().getString("message"));
                                    }
                                }
                            });
                        }
                    }
                });
            }
        }
    });
}

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());
    }/*from  w ww .  j av a 2 s .co 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.common.share.impl.MongoDbShareService.java

License:Open Source License

@Override
public void shareInfos(final String userId, String resourceId, final String acceptLanguage, final String search,
        final Handler<Either<String, JsonObject>> handler) {
    if (userId == null || userId.trim().isEmpty()) {
        handler.handle(new Either.Left<String, JsonObject>("Invalid userId."));
        return;//from   w ww .  j  av  a 2s.  c o  m
    }
    if (resourceId == null || resourceId.trim().isEmpty()) {
        handler.handle(new Either.Left<String, JsonObject>("Invalid resourceId."));
        return;
    }
    final JsonArray actions = getResoureActions(securedActions);
    QueryBuilder query = QueryBuilder.start("_id").is(resourceId);
    JsonObject keys = new JsonObject().put("shared", 1);
    mongo.findOne(collection, MongoQueryBuilder.build(query), keys, new Handler<Message<JsonObject>>() {
        @Override
        public void handle(Message<JsonObject> event) {
            if ("ok".equals(event.body().getString("status"))) {
                JsonArray shared = event.body().getJsonObject("result", new JsonObject()).getJsonArray("shared",
                        new fr.wseduc.webutils.collections.JsonArray());
                JsonObject gs = new JsonObject();
                JsonObject us = new JsonObject();
                for (Object o : shared) {
                    if (!(o instanceof JsonObject))
                        continue;
                    JsonObject userShared = (JsonObject) o;
                    JsonArray a = new fr.wseduc.webutils.collections.JsonArray();
                    for (String attrName : userShared.fieldNames()) {
                        if ("userId".equals(attrName) || "groupId".equals(attrName)) {
                            continue;
                        }
                        if (groupedActions != null && groupedActions.containsKey(attrName)) {
                            for (String action : groupedActions.get(attrName)) {
                                a.add(action.replaceAll("\\.", "-"));
                            }
                        } else {
                            a.add(attrName);
                        }
                    }
                    final String g = userShared.getString("groupId");
                    String u;
                    if (g != null) {
                        gs.put(g, a);
                    } else if ((u = userShared.getString("userId")) != null && !u.equals(userId)) {
                        us.put(u, a);
                    }
                }
                getShareInfos(userId, actions, gs, us, acceptLanguage, search, new Handler<JsonObject>() {
                    @Override
                    public void handle(JsonObject event) {
                        if (event != null && event.size() == 3) {
                            handler.handle(new Either.Right<String, JsonObject>(event));
                        } else {
                            handler.handle(
                                    new Either.Left<String, JsonObject>("Error finding shared resource."));
                        }
                    }
                });
            } else {
                handler.handle(new Either.Left<String, JsonObject>(
                        event.body().getString("error", "Error finding shared resource.")));
            }
        }
    });
}

From source file:org.entcore.common.share.impl.MongoDbShareService.java

License:Open Source License

private void inShare(String resourceId, String shareId, boolean group, final Handler<Boolean> handler) {
    QueryBuilder query = QueryBuilder.start("_id").is(resourceId).put("shared")
            .elemMatch(QueryBuilder.start(group ? "groupId" : "userId").is(shareId).get());
    mongo.count(collection, MongoQueryBuilder.build(query), new Handler<Message<JsonObject>>() {
        @Override/*ww w.  j  a  v  a2 s.c  om*/
        public void handle(Message<JsonObject> event) {
            JsonObject res = event.body();
            handler.handle(res != null && "ok".equals(res.getString("status")) && 1 == res.getInteger("count"));
        }
    });
}

From source file:org.entcore.common.share.impl.MongoDbShareService.java

License:Open Source License

private void share(String resourceId, final String groupShareId, final List<String> actions, boolean isGroup,
        final Handler<Either<String, JsonObject>> handler) {
    final String shareIdAttr = isGroup ? "groupId" : "userId";
    QueryBuilder query = QueryBuilder.start("_id").is(resourceId);
    JsonObject keys = new JsonObject().put("shared", 1);
    final JsonObject q = MongoQueryBuilder.build(query);
    mongo.findOne(collection, q, keys, new Handler<Message<JsonObject>>() {
        @Override/*from  ww  w  .  ja  va  2  s.  c  om*/
        public void handle(Message<JsonObject> event) {
            if ("ok".equals(event.body().getString("status")) && event.body().getJsonObject("result") != null) {
                JsonArray actual = event.body().getJsonObject("result").getJsonArray("shared",
                        new fr.wseduc.webutils.collections.JsonArray());
                boolean exist = false;
                for (int i = 0; i < actual.size(); i++) {
                    JsonObject s = actual.getJsonObject(i);
                    String id = s.getString(shareIdAttr);
                    if (groupShareId.equals(id)) {
                        for (String action : actions) {
                            s.put(action, true);
                        }
                        if (groupedActions != null) {
                            for (Map.Entry<String, List<String>> ga : groupedActions.entrySet()) {
                                if (actions.containsAll(ga.getValue())) {
                                    s.put(ga.getKey(), true);
                                }
                            }
                        }
                        exist = true;
                        break;
                    }
                }
                final AtomicBoolean notifyTimeline = new AtomicBoolean(false);
                if (!exist) {
                    JsonObject t = new JsonObject().put(shareIdAttr, groupShareId);
                    actual.add(t);
                    for (String action : actions) {
                        t.put(action, true);
                    }
                    if (groupedActions != null) {
                        for (Map.Entry<String, List<String>> ga : groupedActions.entrySet()) {
                            if (actions.containsAll(ga.getValue())) {
                                t.put(ga.getKey(), true);
                            }
                        }
                    }
                    notifyTimeline.set(true);
                }
                MongoUpdateBuilder updateQuery = new MongoUpdateBuilder().set("shared", actual);
                mongo.update(collection, q, updateQuery.build(), new Handler<Message<JsonObject>>() {
                    @Override
                    public void handle(Message<JsonObject> res) {
                        if (notifyTimeline.get()) {
                            JsonObject notify = new JsonObject();
                            notify.put(shareIdAttr, groupShareId);
                            res.body().put("notify-timeline", notify);
                        }
                        handler.handle(Utils.validResult(res));
                    }
                });
            } else {
                handler.handle(new Either.Left<String, JsonObject>("Resource not found."));
            }
        }
    });
}

From source file:org.entcore.common.share.impl.MongoDbShareService.java

License:Open Source License

private void removeShare(String resourceId, final String shareId, List<String> removeActions, boolean isGroup,
        final Handler<Either<String, JsonObject>> handler) {
    final String shareIdAttr = isGroup ? "groupId" : "userId";
    final List<String> actions = findRemoveActions(removeActions);
    QueryBuilder query = QueryBuilder.start("_id").is(resourceId);
    JsonObject keys = new JsonObject().put("shared", 1);
    final JsonObject q = MongoQueryBuilder.build(query);
    mongo.findOne(collection, q, keys, new Handler<Message<JsonObject>>() {
        @Override//from  w w w  .  j ava  2 s.co m
        public void handle(Message<JsonObject> event) {
            if ("ok".equals(event.body().getString("status")) && event.body().getJsonObject("result") != null) {
                JsonArray actual = event.body().getJsonObject("result").getJsonArray("shared",
                        new fr.wseduc.webutils.collections.JsonArray());
                JsonArray shared = new fr.wseduc.webutils.collections.JsonArray();
                for (int i = 0; i < actual.size(); i++) {
                    JsonObject s = actual.getJsonObject(i);
                    String id = s.getString(shareIdAttr);
                    if (shareId.equals(id)) {
                        if (actions != null) {
                            for (String action : actions) {
                                s.remove(action);
                            }
                            if (s.size() > 1) {
                                shared.add(s);
                            }
                        }
                    } else {
                        shared.add(s);
                    }
                }
                MongoUpdateBuilder updateQuery = new MongoUpdateBuilder().set("shared", shared);
                mongo.update(collection, q, updateQuery.build(), new Handler<Message<JsonObject>>() {
                    @Override
                    public void handle(Message<JsonObject> res) {
                        handler.handle(Utils.validResult(res));
                    }
                });
            } else {
                handler.handle(new Either.Left<String, JsonObject>("Resource not found."));
            }
        }
    });
}

From source file:org.entcore.common.storage.impl.GridfsStorage.java

License:Open Source License

@Override
public void writeToFileSystem(String[] ids, String destinationPath, JsonObject alias,
        final Handler<JsonObject> handler) {
    QueryBuilder q = QueryBuilder.start("_id").in(ids);
    JsonObject e = new JsonObject().put("action", "write").put("path", destinationPath).put("alias", alias)
            .put("query", MongoQueryBuilder.build(q));
    eb.send(gridfsAddress + ".json", e, handlerToAsyncHandler(new Handler<Message<JsonObject>>() {
        @Override//from w  w w  .ja va2s.  co m
        public void handle(Message<JsonObject> event) {
            handler.handle(event.body());
        }
    }));
}

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());
        }//from w  w  w.ja v a  2  s  .  co m
        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.timeline.services.impl.DefaultTimelineMailerService.java

License:Open Source License

/**
 * Retrieves all timeline notifications from mongodb for a single user, from a specific date in the past.
 *
 * @param userId : Userid/*ww w.j  a  v a 2 s.c om*/
 * @param from : The starting date
 * @param handler : Handles the notifications
 */
private void getUserNotifications(String userId, Date from, final Handler<JsonArray> handler) {
    JsonObject matcher = MongoQueryBuilder.build(QueryBuilder.start("recipients")
            .elemMatch(QueryBuilder.start("userId").is(userId).get()).and("date").greaterThanEquals(from));

    JsonObject keys = new JsonObject().put("_id", 0).put("type", 1).put("event-type", 1).put("params", 1)
            .put("date", 1);
    mongo.find("timeline", matcher, null, keys, new Handler<Message<JsonObject>>() {
        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().getJsonArray("results"));
            }
        }
    });
}