Example usage for com.mongodb QueryBuilder get

List of usage examples for com.mongodb QueryBuilder get

Introduction

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

Prototype

public DBObject get() 

Source Link

Document

Creates a DBObject query to be used for the driver's find operations

Usage

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());
        }/* ww 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.graylog2.alerts.AlertServiceImpl.java

License:Open Source License

@Override
public List<Alert> loadRecentOfStream(String streamId, DateTime since) {
    QueryBuilder qb = QueryBuilder.start("stream_id").is(streamId);

    if (since != null) {
        qb.and("triggered_at").greaterThanEquals(since.toDate());
    }//  w  w  w  . j a  va2  s.  co  m

    BasicDBObject sort = new BasicDBObject("triggered_at", -1);

    final List<DBObject> alertObjects = query(AlertImpl.class, qb.get(), sort, AlertImpl.MAX_LIST_COUNT, 0);

    List<Alert> alerts = Lists.newArrayList();

    for (DBObject alertObj : alertObjects) {
        alerts.add(new AlertImpl(new ObjectId(alertObj.get("_id").toString()), alertObj.toMap()));
    }

    return alerts;
}

From source file:org.keycloak.authorization.mongo.store.MongoPolicyStore.java

License:Open Source License

@Override
public List<Policy> findByResourceServer(Map<String, String[]> attributes, String resourceServerId,
        int firstResult, int maxResult) {
    QueryBuilder queryBuilder = new QueryBuilder().and("resourceServerId").is(resourceServerId);

    attributes.forEach((name, value) -> {
        if ("permission".equals(name)) {
            if (Boolean.valueOf(value[0])) {
                queryBuilder.and("type").in(new String[] { "resource", "scope" });
            } else {
                queryBuilder.and("type").notIn(new String[] { "resource", "scope" });
            }/*from  ww w .j av  a  2  s  .c  o m*/
        } else if ("id".equals(name)) {
            queryBuilder.and("_id").in(value);
        } else {
            queryBuilder.and(name).regex(Pattern.compile(".*" + value[0] + ".*", Pattern.CASE_INSENSITIVE));
        }
    });

    DBObject sort = new BasicDBObject("name", 1);

    return getMongoStore().loadEntities(PolicyEntity.class, queryBuilder.get(), sort, firstResult, maxResult,
            invocationContext).stream().map(policy -> findById(policy.getId())).collect(toList());
}

From source file:org.keycloak.authorization.mongo.store.MongoResourceStore.java

License:Open Source License

@Override
public List<Resource> findByResourceServer(Map<String, String[]> attributes, String resourceServerId,
        int firstResult, int maxResult) {
    QueryBuilder queryBuilder = new QueryBuilder().and("resourceServerId").is(resourceServerId);

    attributes.forEach((name, value) -> {
        if ("scope".equals(name)) {
            queryBuilder.and("scopes").in(value);
        } else {//from  ww  w  .j  a v  a2 s .  c  om
            queryBuilder.and(name).regex(Pattern.compile(".*" + value[0] + ".*", Pattern.CASE_INSENSITIVE));
        }
    });

    DBObject sort = new BasicDBObject("name", 1);

    return getMongoStore().loadEntities(ResourceEntity.class, queryBuilder.get(), sort, firstResult, maxResult,
            invocationContext).stream().map(scope -> findById(scope.getId())).collect(toList());
}

From source file:org.keycloak.authorization.mongo.store.MongoScopeStore.java

License:Open Source License

@Override
public List<Scope> findByResourceServer(Map<String, String[]> attributes, String resourceServerId,
        int firstResult, int maxResult) {
    QueryBuilder queryBuilder = new QueryBuilder().and("resourceServerId").is(resourceServerId);

    attributes.forEach((name, value) -> {
        queryBuilder.and(name).regex(Pattern.compile(".*" + value[0] + ".*", Pattern.CASE_INSENSITIVE));
    });/*  ww  w .  jav a  2 s  . c  o  m*/

    DBObject sort = new BasicDBObject("name", 1);

    return getMongoStore().loadEntities(ScopeEntity.class, queryBuilder.get(), sort, firstResult, maxResult,
            invocationContext).stream().map(scope -> findById(scope.getId())).collect(toList());
}

From source file:org.keycloak.storage.mongo.MongoUserFederatedStorageProvider.java

License:Apache License

@Override
public List<String> getStoredUsers(RealmModel realm, int first, int max) {
    QueryBuilder queryBuilder = new QueryBuilder().and("realmId").is(realm.getId());

    DBObject query = queryBuilder.get();
    List<FederatedUser> users = getMongoStore().loadEntities(FederatedUser.class, query, null, first, max,
            invocationContext);/*from   ww w  . j a va 2  s.  c om*/
    List<String> ids = new LinkedList<>();
    for (FederatedUser user : users)
        ids.add(user.getId());
    return ids;
}

From source file:org.keycloak.storage.mongo.MongoUserFederatedStorageProvider.java

License:Apache License

@Override
public List<String> getUsersByUserAttribute(RealmModel realm, String name, String value) {
    QueryBuilder queryBuilder = new QueryBuilder().and("realmId").is(realm.getId());
    queryBuilder.and("attributes." + name).is(value);

    List<FederatedUser> users = getMongoStore().loadEntities(FederatedUser.class, queryBuilder.get(),
            invocationContext);/*w w w. j  ava  2 s.c om*/
    List<String> ids = new LinkedList<>();
    for (FederatedUser user : users)
        ids.add(user.getId());
    return ids;
}

From source file:org.keycloak.storage.mongo.MongoUserFederatedStorageProvider.java

License:Apache License

@Override
public List<String> getMembership(RealmModel realm, GroupModel group, int firstResult, int max) {
    QueryBuilder queryBuilder = new QueryBuilder().and("realmId").is(realm.getId());
    queryBuilder.and("groupIds").is(group.getId());

    List<FederatedUser> users = getMongoStore().loadEntities(FederatedUser.class, queryBuilder.get(), null,
            firstResult, max, invocationContext);
    List<String> ids = new LinkedList<>();
    for (FederatedUser user : users)
        ids.add(user.getId());//from ww  w  . j  a v a  2  s . c  om
    return ids;
}

From source file:org.mule.modules.morphia.MorphiaConnector.java

License:Open Source License

/**
 * Find a single instance of type using the specified query criteria
 * <p/>/*from  w ww . j av  a  2s.co m*/
 * {@sample.xml ../../../doc/mule-module-morphia.xml.sample morphia:find-single}
 *
 * @param className            Type class name
 * @param filters              Filter criteria. Criteria is a composite of the field name and the operator ("field >", or "field in"). All criteria are implicitly combined with a logical "and".
 * @param fields               Limit the returned fields to the ones specified.
 * @param disableCursorTimeout Disables cursor timeout on server
 * @param disableSnapshotMode  Disable snapshotted mode (default mode). This will be faster but changes made
 *                             during the cursor may cause duplicates.
 * @param disableValidation    Turns off validation
 * @param exception The exception that needs to be thrown if the criteria does not match any result. The exception must be a RuntimeException
 * @param username the username to use in case authentication is required
 * @param password the password to use in case authentication is required, null
 *                 if no authentication is desired
 * @param host     The host of the Mongo server. If the host is part of a replica set then you can specify all the hosts
 *                 separated by comma.
 * @param port     The port of the Mongo server
 * @param database The database name of the Mongo server
 * @throws ExecutionException if there is a connection exception
 * @return An object collection
 * @throws Exception if there is an exception
 */
@Processor
public Object findSingle(String className, @Optional Map<String, Object> filters, @Optional List<String> fields,
        @Optional Boolean disableCursorTimeout, @Optional Boolean disableSnapshotMode,
        @Optional Boolean disableValidation, @Optional String exception, @Optional String username,
        @Optional @Password String password, @Optional String host, @Optional Integer port,
        @Optional String database) throws Exception {

    Datastore datastore = getDatastore(username, password, database, host, port);

    QueryBuilder queryBuilder = QueryBuilder.newBuilder(datastore, className)
            .setDisableCursorTimeout(disableCursorTimeout).setDisableValidation(disableValidation)
            .setDisableSnapshotMode(disableSnapshotMode).setFilters(filters).setFields(fields);

    Object findResult = queryBuilder.getQuery().get();

    if (exception != null && findResult == null) {
        throw getExceptionFromClassName(exception);
    }

    return findResult;
}

From source file:org.opencb.cellbase.lib.db.core.ConservationMongoDBAdaptor.java

License:Apache License

@Deprecated
@Override/* www  . j a va2  s  .com*/
public List<QueryResult> getAllByRegionList(List<Region> regions, QueryOptions options) {
    //TODO not finished yet
    List<Document> queries = new ArrayList<>();
    List<String> ids = new ArrayList<>(regions.size());
    List<String> integerChunkIds;
    for (Region region : regions) {
        integerChunkIds = new ArrayList<>();
        // positions below 1 are not allowed
        if (region.getStart() < 1) {
            region.setStart(1);
        }
        if (region.getEnd() < 1) {
            region.setEnd(1);
        }

        // Max region size is 10000bp
        if (region.getEnd() - region.getStart() > 10000) {
            region.setEnd(region.getStart() + 10000);
        }

        QueryBuilder builder;
        int regionChunkStart = getChunkId(region.getStart(), this.chunkSize);
        int regionChunkEnd = getChunkId(region.getEnd(), this.chunkSize);
        if (regionChunkStart == regionChunkEnd) {
            builder = QueryBuilder.start("_chunkIds")
                    .is(getChunkIdPrefix(region.getChromosome(), region.getStart(), this.chunkSize));
        } else {
            //                for (int chunkId = regionChunkStart; chunkId <= regionChunkEnd; chunkId++) {
            ////                    integerChunkIds.add(chunkId);
            //                    integerChunkIds.add(region.getChromosomeInfo() + "_" + chunkId + "_" + this.chunkSize/1000 + "k");
            //                }
            //                builder = QueryBuilder.start("chromosome").is(region.getChromosomeInfo()).and("chunkId").in(integerChunkIds);
            builder = QueryBuilder.start("chromosome").is(region.getChromosome()).and("end")
                    .greaterThanEquals(region.getStart()).and("start").lessThanEquals(region.getEnd());
        }
        //            QueryBuilder builder = QueryBuilder.start("chromosome").is(region.getChromosomeInfo()).and("chunkId").in(hunkIds);
        /****/

        queries.add(new Document(builder.get().toMap()));
        ids.add(region.toString());

        //            logger.debug(builder.get().toString());
    }

    List<QueryResult> queryResults = executeQueryList2(ids, queries, options);
    for (int i = 0; i < regions.size(); i++) {
        Region region = regions.get(i);
        QueryResult queryResult = queryResults.get(i);
        //            BasicDBList list = (BasicDBList) queryResult.getResult();
        List list = queryResult.getResult();

        Map<String, List<Float>> typeMap = new HashMap();

        //            int start = region.getStart();

        for (int j = 0; j < list.size(); j++) {
            Document chunk = (Document) list.get(j);
            String source = chunk.getString("source");
            List<Float> valuesList;
            if (!typeMap.containsKey(source)) {
                valuesList = new ArrayList<>(region.getEnd() - region.getStart() + 1);
                for (int val = 0; val < region.getEnd() - region.getStart() + 1; val++) {
                    valuesList.add(null);
                }
                typeMap.put(source, valuesList);
            } else {
                valuesList = typeMap.get(source);
            }

            BasicDBList valuesChunk = (BasicDBList) chunk.get("values");

            int pos = 0;
            if (region.getStart() > chunk.getInteger("start")) {
                pos = region.getStart() - chunk.getInteger("start");
            }

            for (; pos < valuesChunk.size() && (pos + chunk.getInteger("start") <= region.getEnd()); pos++) {
                //                    System.out.println("valuesList SIZE = " + valuesList.size());
                //                    System.out.println("pos = " + pos);
                //                    System.out.println("DIV " + (chunk.getInt("start") - region.getStart()));
                //                    System.out.println("valuesChunk = " + valuesChunk.get(pos));
                //                    System.out.println("indexFinal = " + (pos + chunk.getInt("start") - region.getStart()));
                valuesList.set(pos + chunk.getInteger("start") - region.getStart(),
                        new Float((Double) valuesChunk.get(pos)));
            }
        }
        //
        BasicDBList resultList = new BasicDBList();
        //            ConservationScoreRegion conservedRegionChunk;
        GenomicScoreRegion<Float> conservedRegionChunk;
        for (Map.Entry<String, List<Float>> elem : typeMap.entrySet()) {
            //                conservedRegionChunk = new ConservationScoreRegion(region.getChromosome(), region.getStart(),
            //                        region.getEnd(), elem.getKey(), elem.getValue());
            conservedRegionChunk = new GenomicScoreRegion<>(region.getChromosome(), region.getStart(),
                    region.getEnd(), elem.getKey(), elem.getValue());
            resultList.add(conservedRegionChunk);
        }
        queryResult.setResult(resultList);
    }

    return queryResults;
}