Example usage for com.mongodb QueryBuilder QueryBuilder

List of usage examples for com.mongodb QueryBuilder QueryBuilder

Introduction

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

Prototype

public QueryBuilder() 

Source Link

Document

Creates a builder with an empty query

Usage

From source file:net.atos.entng.wiki.service.WikiServiceMongoImpl.java

License:Open Source License

@Override
public void listAllPages(UserInfos user, Handler<Either<String, JsonArray>> handler) {
    // Query : return pages visible by current user only (i.e. owner or
    // shared)//from   w ww.  j a  v  a2  s .co m
    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());
    }

    QueryBuilder 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());

    // Projection
    JsonObject projection = new JsonObject();
    projection.putNumber("pages.content", 0).putNumber("created", 0);

    JsonObject sort = new JsonObject().putNumber("pages.title", 1);

    mongo.find(collection, MongoQueryBuilder.build(query), sort, projection,
            MongoDbResult.validResultsHandler(handler));
}

From source file:net.jimj.automaton.commands.NoteCommand.java

License:Open Source License

protected void findNotes(User to) {
    QueryBuilder builder = new QueryBuilder();
    builder.or(new BasicDBObject(NOTE_TO, to.getNick().toLowerCase()),
            new BasicDBObject(NOTE_TO, to.getRealName()));
    builder.and(new BasicDBObject(NOTE_DELIVERED, false));
    DBCursor noteCursor = notes.find(builder.get());
    if (noteCursor == null) {
        return;/*from   www  . j av  a 2s.  c  o m*/
    }

    while (noteCursor.hasNext()) {
        DBObject noteObj = noteCursor.next();
        String from = (String) noteObj.get(NOTE_FROM);
        String note = (String) noteObj.get(NOTE_NOTE);
        long when = (long) noteObj.get(NOTE_WHEN);

        StringBuilder noteMessage = new StringBuilder(to.getNick()).append(" you have a note from ");
        noteMessage.append(from).append(" at ").append(WHEN_FMT.format(new Date(when)));
        addEvent(new ReplyEvent(to, noteMessage.toString()));
        addEvent(new ReplyEvent(to, note));

        notes.update(new BasicDBObject("_id", noteObj.get("_id")),
                new BasicDBObject("$set", new BasicDBObject(NOTE_DELIVERED, true)));
    }
}

From source file:org.apache.jackrabbit.oak.plugins.document.mongo.MongoBlobStore.java

License:Apache License

private static DBObject getBlobQuery(String id, long lastMod) {
    QueryBuilder queryBuilder = new QueryBuilder();
    if (id != null) {
        queryBuilder = queryBuilder.and(MongoBlob.KEY_ID).is(id);
    }/*from w  ww  .  j a  v  a 2  s  .c o m*/
    if (lastMod > 0) {
        queryBuilder = queryBuilder.and(MongoBlob.KEY_LAST_MOD).lessThan(lastMod);
    }
    return queryBuilder.get();
}

From source file:org.apache.jackrabbit.oak.plugins.document.mongo.MongoBlobStore.java

License:Apache License

@Override
public long countDeleteChunks(List<String> chunkIds, long maxLastModifiedTime) throws Exception {
    DBCollection collection = getBlobCollection();
    QueryBuilder queryBuilder = new QueryBuilder();
    if (chunkIds != null) {
        queryBuilder = queryBuilder.and(MongoBlob.KEY_ID).in(chunkIds.toArray(new String[0]));
        if (maxLastModifiedTime > 0) {
            queryBuilder = queryBuilder.and(MongoBlob.KEY_LAST_MOD).lessThan(maxLastModifiedTime);
        }/* w  w w  .  ja v a2s .com*/
    }

    WriteResult result = collection.remove(queryBuilder.get());
    return result.getN();
}

From source file:org.apache.jackrabbit.oak.plugins.document.mongo.MongoBlobStore.java

License:Apache License

@Override
public Iterator<String> getAllChunkIds(long maxLastModifiedTime) throws Exception {
    DBCollection collection = getBlobCollection();

    DBObject fields = new BasicDBObject();
    fields.put(MongoBlob.KEY_ID, 1);//from w  ww . ja v  a 2 s.co  m

    QueryBuilder builder = new QueryBuilder();
    if (maxLastModifiedTime != 0 && maxLastModifiedTime != -1) {
        builder.and(MongoBlob.KEY_LAST_MOD).lessThanEquals(maxLastModifiedTime);
    }

    final DBCursor cur = collection.find(builder.get(), fields).hint(fields)
            .addOption(Bytes.QUERYOPTION_SLAVEOK);

    //TODO The cursor needs to be closed
    return new AbstractIterator<String>() {
        @Override
        protected String computeNext() {
            if (cur.hasNext()) {
                MongoBlob blob = (MongoBlob) cur.next();
                if (blob != null) {
                    return blob.getId();
                }
            }
            return endOfData();
        }
    };
}

From source file:org.apache.jackrabbit.oak.plugins.document.mongo.MongoDocumentStore.java

License:Apache License

private <T extends Document> Map<String, T> findDocuments(Collection<T> collection, Set<String> keys) {
    Map<String, T> docs = new HashMap<String, T>();
    if (!keys.isEmpty()) {
        DBObject[] conditions = new DBObject[keys.size()];
        int i = 0;
        for (String key : keys) {
            conditions[i++] = getByKeyQuery(key).get();
        }/*from ww  w  . j a v  a  2 s  .  c om*/

        QueryBuilder builder = new QueryBuilder();
        builder.or(conditions);
        DBCursor cursor = getDBCollection(collection).find(builder.get());
        while (cursor.hasNext()) {
            T foundDoc = convertFromDBObject(collection, cursor.next());
            docs.put(foundDoc.getId(), foundDoc);
        }
    }
    return docs;
}

From source file:org.entcore.blog.events.BlogSearchingEvents.java

License:Open Source License

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

        final List<String> groupIdsLst = groupIds.getList();
        final List<DBObject> groups = new ArrayList<DBObject>();
        groups.add(QueryBuilder.start("userId").is(userId).get());
        for (String gpId : groupIdsLst) {
            groups.add(QueryBuilder.start("groupId").is(gpId).get());
        }//from  w  w  w. ja v  a  2s  .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("author.userId").is(userId).get(),
                QueryBuilder.start("shared")
                        .elemMatch(new QueryBuilder().or(groups.toArray(new DBObject[groups.size()])).get())
                        .get());

        final JsonObject projection = new JsonObject();
        projection.put("_id", 1);
        //search all blogs of user
        mongo.find(Blog.BLOGS_COLLECTION, MongoQueryBuilder.build(rightsQuery), null, projection,
                new Handler<Message<JsonObject>>() {
                    @Override
                    public void handle(Message<JsonObject> event) {
                        final Either<String, JsonArray> ei = validResults(event);
                        if (ei.isRight()) {
                            final JsonArray blogsResult = ei.right().getValue();

                            final Set<String> setIds = new HashSet<String>();
                            for (int i = 0; i < blogsResult.size(); i++) {
                                final JsonObject j = blogsResult.getJsonObject(i);
                                setIds.add(j.getString("_id"));
                            }

                            //search posts for the blogs found
                            searchPosts(page, limit, searchWords.getList(), setIds,
                                    new Handler<Either<String, JsonArray>>() {
                                        @Override
                                        public void handle(Either<String, JsonArray> event) {
                                            if (event.isRight()) {
                                                if (log.isDebugEnabled()) {
                                                    log.debug(
                                                            "[BlogSearchingEvents][searchResource] The resources searched by user are found");
                                                }
                                                final JsonArray res = formatSearchResult(
                                                        event.right().getValue(), columnsHeader,
                                                        searchWords.getList());
                                                handler.handle(new Right<String, JsonArray>(res));
                                            } else {
                                                handler.handle(new Either.Left<String, JsonArray>(
                                                        event.left().getValue()));
                                            }
                                        }
                                    });
                        } else {
                            handler.handle(new Either.Left<String, JsonArray>(ei.left().getValue()));
                        }
                    }
                });
    } else {
        handler.handle(new Right<String, JsonArray>(new JsonArray()));
    }
}

From source file:org.entcore.blog.events.BlogSearchingEvents.java

License:Open Source License

private void searchPosts(int page, int limit, List<String> searchWords, final Set<String> setIds,
        Handler<Either<String, JsonArray>> handler) {
    final int skip = (0 == page) ? -1 : page * limit;

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

    final QueryBuilder blogQuery = new QueryBuilder().start("blog.$id").in(setIds);
    final QueryBuilder publishedQuery = new QueryBuilder().start("state").is(PUBLISHED_STATE);

    final QueryBuilder query = new QueryBuilder().and(worldsQuery.get(), blogQuery.get(), publishedQuery.get());

    JsonObject sort = new JsonObject().put("modified", -1);
    final JsonObject projection = new JsonObject();
    projection.put("title", 1);
    projection.put("content", 1);
    projection.put("blog.$id", 1);
    projection.put("modified", 1);
    projection.put("author.userId", 1);
    projection.put("author.username", 1);

    mongo.find(Blog.POSTS_COLLECTION, MongoQueryBuilder.build(query), sort, projection, skip, limit,
            Integer.MAX_VALUE, validResultsHandler(handler));
}

From source file:org.entcore.common.http.filter.MongoAppFilter.java

License:Open Source License

public void sharedAndOwner(HttpServerRequest request, String sharedMethod, UserInfos user,
        Handler<Boolean> handler) {
    String id = request.params().get(resourceIdLabel);
    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.getGroupsIds()) {
            groups.add(QueryBuilder.start("groupId").is(gpId).put(sharedMethod).is(true).get());
        }//from  www.j ava2s . c o m
        QueryBuilder query = QueryBuilder.start("_id").is(id).or(
                QueryBuilder.start("owner.userId").is(user.getUserId()).get(),
                QueryBuilder.start("shared")
                        .elemMatch(new QueryBuilder().or(groups.toArray(new DBObject[groups.size()])).get())
                        .get());
        executeCountQuery(request, collection, MongoQueryBuilder.build(query), 1, handler);
    } else {
        handler.handle(false);
    }
}

From source file:org.entcore.common.http.filter.ShareAndOwner.java

License:Open Source License

@Override
public void authorize(HttpServerRequest request, Binding binding, UserInfos user, Handler<Boolean> handler) {
    String id = request.params().get(conf.getResourceIdLabel());
    if (id != null && !id.trim().isEmpty()) {
        List<DBObject> groups = new ArrayList<>();
        String sharedMethod = binding.getServiceMethod().replaceAll("\\.", "-");
        groups.add(QueryBuilder.start("userId").is(user.getUserId()).put(sharedMethod).is(true).get());
        for (String gpId : user.getGroupsIds()) {
            groups.add(QueryBuilder.start("groupId").is(gpId).put(sharedMethod).is(true).get());
        }/* w w  w .j a  va  2s . com*/
        QueryBuilder query = QueryBuilder.start("_id").is(id).or(
                QueryBuilder.start("owner.userId").is(user.getUserId()).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);
    }
}