Example usage for com.mongodb QueryBuilder and

List of usage examples for com.mongodb QueryBuilder and

Introduction

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

Prototype

@SuppressWarnings("unchecked")
public QueryBuilder and(final DBObject... ands) 

Source Link

Document

Equivalent to an $and operand

Usage

From source file:org.opencb.opencga.storage.mongodb.variant.VariantMongoDBAdaptor.java

License:Apache License

private QueryBuilder addFrequencyFilter(String key, String alleleFrequencyField, List<String> list,
        QueryBuilder builder) {/*from  w ww  .  ja v a2 s .  c  om*/
    List<DBObject> ands = new ArrayList<>();
    for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
        String elem = iterator.next();
        String[] split = elem.split(":");
        if (split.length == 2) {
            String study = split[0];
            String population = split[1];
            //                String frequency = split[2];
            String[] populationFrequency = splitKeyValue(population);
            QueryBuilder frequencyBuilder = new QueryBuilder();
            frequencyBuilder.and(DBObjectToVariantAnnotationConverter.POPULATION_FREQUENCY_STUDY_FIELD)
                    .is(study);
            //                frequencyBuilder.and(DBObjectToVariantAnnotationConverter.POPULATION_FREQUENCY_POP_FIELD).is(population);
            frequencyBuilder.and(DBObjectToVariantAnnotationConverter.POPULATION_FREQUENCY_POP_FIELD)
                    .is(populationFrequency[0]);
            //                addCompQueryFilter(alleleFrequencyField, frequency, frequencyBuilder);
            System.out.println("populationFrequency = " + Arrays.toString(populationFrequency));
            addCompQueryFilter(alleleFrequencyField, populationFrequency[1], frequencyBuilder);
            ands.add(new BasicDBObject(key, new BasicDBObject("$elemMatch", frequencyBuilder.get())));
        } else {
            logger.error("Bad score filter: " + elem);
            iterator.remove(); //Remove the malformed query params.
        }
    }
    if (!ands.isEmpty()) {
        builder.and(ands.toArray(new DBObject[ands.size()]));
    }
    return builder;
}

From source file:org.opencb.opencga.storage.mongodb.variant.VariantMongoDBAdaptor.java

License:Apache License

private QueryBuilder getRegionFilter(Region region, QueryBuilder builder) {
    List<String> chunkIds = getChunkIds(region);
    builder.and("_at.chunkIds").in(chunkIds);
    builder.and(DBObjectToVariantConverter.END_FIELD).greaterThanEquals(region.getStart());
    builder.and(DBObjectToVariantConverter.START_FIELD).lessThanEquals(region.getEnd());
    return builder;
}

From source file:org.opencb.opencga.storage.mongodb.variant.VariantMongoDBAdaptor.java

License:Apache License

@Deprecated
private QueryBuilder parseQueryOptions(QueryOptions options, QueryBuilder builder) {
    if (options != null) {

        if (options.containsKey("sort")) {
            if (options.getBoolean("sort")) {
                options.put("sort", new BasicDBObject(DBObjectToVariantConverter.CHROMOSOME_FIELD, 1)
                        .append(DBObjectToVariantConverter.START_FIELD, 1));
            } else {
                options.remove("sort");
            }//from  ww  w.  ja  v a  2 s  .c o  m
        }

        /** GENOMIC REGION **/

        if (options.containsKey(VariantQueryParams.REGION.key())
                && !options.getString(VariantQueryParams.REGION.key()).isEmpty()) {
            List<String> stringList = options.getAsStringList(VariantQueryParams.REGION.key());
            List<Region> regions = new ArrayList<>(stringList.size());
            for (String reg : stringList) {
                Region region = Region.parseRegion(reg);
                regions.add(region);
            }
            getRegionFilter(regions, builder);
        }

        //            if (options.containsKey(VariantQueryParams.CHROMOSOME.key())) {
        //                List<String> chromosome = options.getAsStringList(VariantQueryParams.CHROMOSOME.key());
        //                addQueryListFilter(DBObjectToVariantConverter.CHROMOSOME_FIELD, chromosome, builder, QueryOperation.OR);
        //            }

        if (options.containsKey(VariantQueryParams.GENE.key())) {
            List<String> xrefs = options.getAsStringList(VariantQueryParams.GENE.key());
            addQueryListFilter(
                    DBObjectToVariantConverter.ANNOTATION_FIELD + "."
                            + DBObjectToVariantAnnotationConverter.XREFS_FIELD + "."
                            + DBObjectToVariantAnnotationConverter.XREF_ID_FIELD,
                    xrefs, builder, QueryOperation.OR);
        }

        if (options.getString(VariantQueryParams.ID.key()) != null
                && !options.getString(VariantQueryParams.ID.key()).isEmpty()) { //) && !options.getString("id").isEmpty()) {
            List<String> ids = options.getAsStringList(VariantQueryParams.ID.key());
            addQueryListFilter(
                    DBObjectToVariantConverter.ANNOTATION_FIELD + "."
                            + DBObjectToVariantAnnotationConverter.XREFS_FIELD + "."
                            + DBObjectToVariantAnnotationConverter.XREF_ID_FIELD,
                    ids, builder, QueryOperation.OR);
            addQueryListFilter(DBObjectToVariantConverter.IDS_FIELD, ids, builder, QueryOperation.OR);
        }

        /** VARIANT **/

        if (options.containsKey(VariantQueryParams.TYPE.key())) { // && !options.getString("type").isEmpty()) {
            addQueryStringFilter(DBObjectToVariantConverter.TYPE_FIELD,
                    options.getString(VariantQueryParams.TYPE.key()), builder);
        }

        if (options.containsKey(VariantQueryParams.REFERENCE.key())
                && options.getString(VariantQueryParams.REFERENCE.key()) != null) {
            addQueryStringFilter(DBObjectToVariantConverter.REFERENCE_FIELD,
                    options.getString(VariantQueryParams.REFERENCE.key()), builder);
        }

        if (options.containsKey(VariantQueryParams.ALTERNATE.key())
                && options.getString(VariantQueryParams.ALTERNATE.key()) != null) {
            addQueryStringFilter(DBObjectToVariantConverter.ALTERNATE_FIELD,
                    options.getString(VariantQueryParams.ALTERNATE.key()), builder);
        }

        /** ANNOTATION **/

        if (options.containsKey(VariantQueryParams.ANNOTATION_EXISTS.key())) {
            builder.and(DBObjectToVariantConverter.ANNOTATION_FIELD)
                    .exists(options.getBoolean(VariantQueryParams.ANNOTATION_EXISTS.key()));
        }

        if (options.containsKey(VariantQueryParams.ANNOT_XREF.key())) {
            List<String> xrefs = options.getAsStringList(VariantQueryParams.ANNOT_XREF.key());
            addQueryListFilter(
                    DBObjectToVariantConverter.ANNOTATION_FIELD + "."
                            + DBObjectToVariantAnnotationConverter.XREFS_FIELD + "."
                            + DBObjectToVariantAnnotationConverter.XREF_ID_FIELD,
                    xrefs, builder, QueryOperation.AND);
        }

        if (options.containsKey(VariantQueryParams.ANNOT_CONSEQUENCE_TYPE.key())) {
            List<String> cts = new ArrayList<>(
                    options.getAsStringList(VariantQueryParams.ANNOT_CONSEQUENCE_TYPE.key()));
            List<Integer> ctsInteger = new ArrayList<>(cts.size());
            for (Iterator<String> iterator = cts.iterator(); iterator.hasNext();) {
                String ct = iterator.next();
                if (ct.startsWith("SO:")) {
                    ct = ct.substring(3);
                }
                try {
                    ctsInteger.add(Integer.parseInt(ct));
                } catch (NumberFormatException e) {
                    logger.error("Error parsing integer ", e);
                    iterator.remove(); //Remove the malformed query params.
                }
            }
            options.put(VariantQueryParams.ANNOT_CONSEQUENCE_TYPE.key(), cts); //Replace the QueryOption without the malformed query params
            addQueryListFilter(
                    DBObjectToVariantConverter.ANNOTATION_FIELD + "."
                            + DBObjectToVariantAnnotationConverter.CONSEQUENCE_TYPE_FIELD + "."
                            + DBObjectToVariantAnnotationConverter.SO_ACCESSION_FIELD,
                    ctsInteger, builder, QueryOperation.AND);
        }

        if (options.containsKey(VariantQueryParams.ANNOT_BIOTYPE.key())) {
            List<String> biotypes = options.getAsStringList(VariantQueryParams.ANNOT_BIOTYPE.key());
            addQueryListFilter(
                    DBObjectToVariantConverter.ANNOTATION_FIELD + "."
                            + DBObjectToVariantAnnotationConverter.CONSEQUENCE_TYPE_FIELD + "."
                            + DBObjectToVariantAnnotationConverter.BIOTYPE_FIELD,
                    biotypes, builder, QueryOperation.AND);
        }

        if (options.containsKey(VariantQueryParams.POLYPHEN.key())) {
            addCompQueryFilter(
                    DBObjectToVariantConverter.ANNOTATION_FIELD + "."
                            + DBObjectToVariantAnnotationConverter.CONSEQUENCE_TYPE_FIELD + "."
                            + DBObjectToVariantAnnotationConverter.POLYPHEN_FIELD + "."
                            + DBObjectToVariantAnnotationConverter.SCORE_SCORE_FIELD,
                    options.getString(VariantQueryParams.POLYPHEN.key()), builder);
        }

        if (options.containsKey(VariantQueryParams.SIFT.key())) {
            addCompQueryFilter(
                    DBObjectToVariantConverter.ANNOTATION_FIELD + "."
                            + DBObjectToVariantAnnotationConverter.CONSEQUENCE_TYPE_FIELD + "."
                            + DBObjectToVariantAnnotationConverter.SIFT_FIELD + "."
                            + DBObjectToVariantAnnotationConverter.SCORE_SCORE_FIELD,
                    options.getString(VariantQueryParams.SIFT.key()), builder);
        }

        if (options.containsKey(VariantQueryParams.PROTEIN_SUBSTITUTION.key())) {
            List<String> list = new ArrayList<>(
                    options.getAsStringList(VariantQueryParams.PROTEIN_SUBSTITUTION.key()));
            addScoreFilter(
                    DBObjectToVariantConverter.ANNOTATION_FIELD + "."
                            + DBObjectToVariantAnnotationConverter.CONSEQUENCE_TYPE_FIELD + "."
                            + DBObjectToVariantAnnotationConverter.PROTEIN_SUBSTITUTION_SCORE_FIELD,
                    list, builder);
            options.put(VariantQueryParams.PROTEIN_SUBSTITUTION.key(), list); //Replace the QueryOption without the malformed query params
        }

        if (options.containsKey(VariantQueryParams.CONSERVATION.key())) {
            List<String> list = new ArrayList<>(options.getAsStringList(VariantQueryParams.CONSERVATION.key()));
            addScoreFilter(DBObjectToVariantConverter.ANNOTATION_FIELD + "."
                    + DBObjectToVariantAnnotationConverter.CONSERVED_REGION_SCORE_FIELD, list, builder);
            options.put(VariantQueryParams.CONSERVATION.key(), list); //Replace the QueryOption without the malformed query params
        }

        if (options.containsKey(VariantQueryParams.ALTERNATE_FREQUENCY.key())) {
            List<String> list = new ArrayList<>(
                    options.getAsStringList(VariantQueryParams.ALTERNATE_FREQUENCY.key()));
            addFrequencyFilter(
                    DBObjectToVariantConverter.ANNOTATION_FIELD + "."
                            + DBObjectToVariantAnnotationConverter.POPULATION_FREQUENCIES_FIELD,
                    DBObjectToVariantAnnotationConverter.POPULATION_FREQUENCY_ALTERNATE_FREQUENCY_FIELD, list,
                    builder); // Same method addFrequencyFilter is used for reference and allele frequencies. Need to provide the field (reference/alternate) where to check the frequency
        }

        if (options.containsKey(VariantQueryParams.REFERENCE_FREQUENCY.key())) {
            List<String> list = new ArrayList<>(
                    options.getAsStringList(VariantQueryParams.REFERENCE_FREQUENCY.key()));
            addFrequencyFilter(
                    DBObjectToVariantConverter.ANNOTATION_FIELD + "."
                            + DBObjectToVariantAnnotationConverter.POPULATION_FREQUENCIES_FIELD,
                    DBObjectToVariantAnnotationConverter.POPULATION_FREQUENCY_REFERENCE_FREQUENCY_FIELD, list,
                    builder); // Same method addFrequencyFilter is used for reference and allele frequencies. Need to provide the field (reference/alternate) where to check the frequency
        }

        /** STATS **/

        if (options.get(VariantQueryParams.STATS_MAF.key()) != null
                && !options.getString(VariantQueryParams.STATS_MAF.key()).isEmpty()) {
            addCompQueryFilter(
                    DBObjectToVariantConverter.STATS_FIELD + "." + DBObjectToVariantStatsConverter.MAF_FIELD,
                    options.getString(VariantQueryParams.STATS_MAF.key()), builder);
        }

        if (options.get(VariantQueryParams.STATS_MGF.key()) != null
                && !options.getString(VariantQueryParams.STATS_MGF.key()).isEmpty()) {
            addCompQueryFilter(
                    DBObjectToVariantConverter.STATS_FIELD + "." + DBObjectToVariantStatsConverter.MGF_FIELD,
                    options.getString(VariantQueryParams.STATS_MGF.key()), builder);
        }

        if (options.get(VariantQueryParams.MISSING_ALLELES.key()) != null
                && !options.getString(VariantQueryParams.MISSING_ALLELES.key()).isEmpty()) {
            addCompQueryFilter(
                    DBObjectToVariantConverter.STATS_FIELD + "."
                            + DBObjectToVariantStatsConverter.MISSALLELE_FIELD,
                    options.getString(VariantQueryParams.MISSING_ALLELES.key()), builder);
        }

        if (options.get(VariantQueryParams.MISSING_GENOTYPES.key()) != null
                && !options.getString(VariantQueryParams.MISSING_GENOTYPES.key()).isEmpty()) {
            addCompQueryFilter(
                    DBObjectToVariantConverter.STATS_FIELD + "."
                            + DBObjectToVariantStatsConverter.MISSGENOTYPE_FIELD,
                    options.getString(VariantQueryParams.MISSING_GENOTYPES.key()), builder);
        }

        if (options.get("numgt") != null && !options.getString("numgt").isEmpty()) {
            for (String numgt : options.getAsStringList("numgt")) {
                String[] split = numgt.split(":");
                addCompQueryFilter(
                        DBObjectToVariantConverter.STATS_FIELD + "."
                                + DBObjectToVariantStatsConverter.NUMGT_FIELD + "." + split[0],
                        split[1], builder);
            }
        }

        //            if (options.get("freqgt") != null && !options.getString("freqgt").isEmpty()) {
        //                for (String freqgt : getStringList(options.get("freqgt"))) {
        //                    String[] split = freqgt.split(":");
        //                    addCompQueryFilter(
        //                            DBObjectToVariantSourceEntryConverter.STATS_FIELD + "." + DBObjectToVariantStatsConverter.FREQGT_FIELD + "." + split[0],
        //                            split[1], builder);
        //                }
        //            }

        /** FILES **/
        QueryBuilder fileBuilder = QueryBuilder.start();

        if (options.containsKey(VariantQueryParams.STUDIES.key())) { // && !options.getList("studies").isEmpty() && !options.getListAs("studies", String.class).get(0).isEmpty()) {
            addQueryListFilter(DBObjectToVariantSourceEntryConverter.STUDYID_FIELD,
                    options.getAsIntegerList(VariantQueryParams.STUDIES.key()), fileBuilder,
                    QueryOperation.AND);
        }

        if (options.containsKey(VariantQueryParams.FILES.key())) { // && !options.getList("files").isEmpty() && !options.getListAs("files", String.class).get(0).isEmpty()) {
            addQueryListFilter(
                    DBObjectToVariantSourceEntryConverter.FILES_FIELD + "."
                            + DBObjectToVariantSourceEntryConverter.FILEID_FIELD,
                    options.getAsIntegerList(VariantQueryParams.FILES.key()), fileBuilder, QueryOperation.AND);
        }

        if (options.containsKey(VariantQueryParams.GENOTYPE.key())) {
            String sampleGenotypesCSV = options.getString(VariantQueryParams.GENOTYPE.key());

            //                String AND = ",";
            //                String OR = ";";
            //                String IS = ":";

            //                String AND = "AND";
            //                String OR = "OR";
            //                String IS = ":";

            String AND = ";";
            String OR = ",";
            String IS = ":";

            String[] sampleGenotypesArray = sampleGenotypesCSV.split(AND);
            for (String sampleGenotypes : sampleGenotypesArray) {
                String[] sampleGenotype = sampleGenotypes.split(IS);
                if (sampleGenotype.length != 2) {
                    continue;
                }
                int sample = Integer.parseInt(sampleGenotype[0]);
                String[] genotypes = sampleGenotype[1].split(OR);
                QueryBuilder genotypesBuilder = QueryBuilder.start();
                for (String genotype : genotypes) {
                    String s = DBObjectToVariantSourceEntryConverter.GENOTYPES_FIELD + "."
                            + DBObjectToSamplesConverter.genotypeToStorageType(genotype);
                    //or [ {"samp.0|0" : { $elemMatch : { $eq : <sampleId> } } } ]
                    genotypesBuilder.or(new BasicDBObject(s,
                            new BasicDBObject("$elemMatch", new BasicDBObject("$eq", sample))));
                }
                fileBuilder.and(genotypesBuilder.get());
            }
        }

        DBObject fileQuery = fileBuilder.get();
        if (fileQuery.keySet().size() != 0) {
            builder.and(DBObjectToVariantConverter.STUDIES_FIELD).elemMatch(fileQuery);
        }
    }

    logger.debug("Find = " + builder.get());
    return builder;
}

From source file:org.opencb.opencga.storage.mongodb.variant.VariantSourceMongoDBAdaptor.java

License:Apache License

private QueryBuilder andIs(String fieldName, Object object, QueryBuilder builder) {
    if (object == null) {
        return builder;
    } else if (object instanceof Collection) {
        return builder.and(fieldName).in(object);
    } else {/*  w  ww.  j ava 2  s.  co m*/
        return builder.and(fieldName).is(object);
    }
}

From source file:org.openmhealth.reference.data.mongodb.MongoAuthenticationTokenBin.java

License:Apache License

@Override
public AuthenticationToken getToken(final String token) throws OmhException {

    // Get the connection to the authentication token bin with the Jackson
    // wrapper.//from  www  . j  a v a 2s.c  o m
    JacksonDBCollection<MongoAuthenticationToken, Object> collection = JacksonDBCollection
            .wrap(MongoDao.getInstance().getDb().getCollection(DB_NAME), MongoAuthenticationToken.class);

    // Build the query.
    QueryBuilder queryBuilder = QueryBuilder.start();

    // Add the authentication token to the query.
    queryBuilder.and(AuthenticationToken.JSON_KEY_TOKEN).is(token);

    // Add the expiration timer to ensure that this token has not expired.
    queryBuilder.and(MongoAuthenticationToken.JSON_KEY_EXPIRES).greaterThan(System.currentTimeMillis());

    // Execute query.
    DBCursor<MongoAuthenticationToken> result = collection.find(queryBuilder.get());

    // If multiple authentication tokens were returned, that is a violation
    // of the system.
    if (result.count() > 1) {
        throw new OmhException("Multiple copies of the same authentication token " + "exist: " + token);
    }

    // If no tokens were returned, then return null.
    if (result.count() == 0) {
        return null;
    } else {
        return result.next();
    }
}

From source file:org.openmhealth.reference.data.mongodb.MongoDataSet.java

License:Apache License

@Override
public MultiValueResult<Data> getData(final String owner, final String schemaId, final long version,
        final ColumnList columnList, final long numToSkip, final long numToReturn) {

    // Get the connection to the database.
    DB db = MongoDao.getInstance().getDb();

    // Get the connection to the data with the Jackson wrapper.
    JacksonDBCollection<MongoData, Object> collection = JacksonDBCollection.wrap(db.getCollection(DB_NAME),
            MongoData.class);

    // Build the query.
    QueryBuilder queryBuilder = QueryBuilder.start();

    // Only select data for a single user.
    queryBuilder.and(Data.JSON_KEY_OWNER).is(owner);

    // Only select data for a given schema.
    queryBuilder.and(Schema.JSON_KEY_ID).is(schemaId);

    // Only select data for a given version of the the given schema.
    queryBuilder.and(Schema.JSON_KEY_VERSION).is(version);

    // Create the projection.
    DBObject projection = new BasicDBObject();
    // Add the owner field.
    projection.put(Data.JSON_KEY_OWNER, 1);
    // Add the schema ID field.
    projection.put(Schema.JSON_KEY_ID, 1);
    // Add the schema version.
    projection.put(Schema.JSON_KEY_VERSION, 1);
    // Add the meta-data field.
    projection.put(Data.JSON_KEY_METADATA, 1);
    // Add all of the data or add only the specified columns if given.
    if (columnList.size() == 0) {
        projection.put(Data.JSON_KEY_DATA, 1);
    } else {// w w  w. j a v a2s  .co m
        if ((columnList != null) && (columnList.size() > 0)) {
            for (String column : columnList.toList()) {
                projection.put(Data.JSON_KEY_DATA + ColumnList.COLUMN_SEPARATOR + column, 1);
            }
        }
    }

    // Build the query.
    DBCursor<MongoData> dbResult = collection.find(queryBuilder.get(), projection);

    // Build the sort field by sorting in reverse chronological order.
    DBObject sort = new BasicDBObject();
    sort.put(Data.JSON_KEY_METADATA + ColumnList.COLUMN_SEPARATOR + MetaData.JSON_KEY_TIMESTAMP, -1);
    dbResult.sort(sort);

    // Page the results and return the multi-value result.
    return new MongoMultiValueResultCursor<Data>(
            dbResult.skip((new Long(numToSkip)).intValue()).limit((new Long(numToReturn)).intValue()));
}

From source file:org.openmhealth.reference.data.mongodb.MongoRegistry.java

License:Apache License

public Schema getSchema(final String schemaId, final long schemaVersion) {
    // Get the connection to the database.
    DB db = MongoDao.getInstance().getDb();

    // Get the connection to the registry with the Jackson wrapper.
    JacksonDBCollection<MongoSchema, Object> collection = JacksonDBCollection.wrap(db.getCollection(DB_NAME),
            MongoSchema.class, Object.class, JSON_MAPPER);

    // Build the query
    QueryBuilder queryBuilder = QueryBuilder.start();

    // Add the schema ID.
    queryBuilder.and(MongoSchema.JSON_KEY_ID).is(schemaId);

    // Add the schema version.
    queryBuilder.and(MongoSchema.JSON_KEY_VERSION).is(schemaVersion);

    // Execute query.
    DBCursor<MongoSchema> result = collection.find(queryBuilder.get());

    // Return null or the schema based on what the query returned.
    if (result.count() == 0) {
        return null;
    } else {//  w w  w. j  a va2s .  c  om
        return result.next();
    }
}

From source file:org.openmhealth.reference.data.mongodb.MongoUserBin.java

License:Apache License

@Override
public User getUser(final String username) throws OmhException {
    // Validate the parameter.
    if (username == null) {
        throw new OmhException("The username is null.");
    }//  www .j a v a 2 s .  co m

    // Get the authentication token collection.
    JacksonDBCollection<MongoUser, Object> collection = JacksonDBCollection.wrap(
            MongoDao.getInstance().getDb().getCollection(DB_NAME), MongoUser.class, Object.class, JSON_MAPPER);

    // Build the query.
    QueryBuilder queryBuilder = QueryBuilder.start();

    // Add the authentication token to the query
    queryBuilder.and(MongoUser.JSON_KEY_USERNAME).is(username);

    // Execute query.
    DBCursor<MongoUser> result = collection.find(queryBuilder.get());

    // If multiple authentication tokens were returned, that is a violation
    // of the system.
    if (result.count() > 1) {
        throw new OmhException("Multiple users exist with the same username: " + username);
    }

    // If no tokens were returned, then return null.
    if (result.count() == 0) {
        return null;
    } else {
        return result.next();
    }
}

From source file:org.openmhealth.reference.data.mongodb.MongoUserBin.java

License:Apache License

@Override
public User getUserFromRegistrationId(final String registrationId) throws OmhException {

    // Validate the parameter.
    if (registrationId == null) {
        throw new OmhException("The registration ID is null.");
    }//from   w w  w .  j a v a  2  s. c  om

    // Get the authentication token collection.
    JacksonDBCollection<MongoUser, Object> collection = JacksonDBCollection.wrap(
            MongoDao.getInstance().getDb().getCollection(DB_NAME), MongoUser.class, Object.class, JSON_MAPPER);

    // Build the query.
    QueryBuilder queryBuilder = QueryBuilder.start();

    // Add the authentication token to the query
    queryBuilder.and(MongoUser.JSON_KEY_REGISTRATION_KEY).is(registrationId);

    // Execute query.
    DBCursor<MongoUser> result = collection.find(queryBuilder.get());

    // If multiple authentication tokens were returned, that is a violation
    // of the system.
    if (result.count() > 1) {
        throw new OmhException("Multiple users exist with the same registration ID: " + registrationId);
    }

    // If no tokens were returned, then return null.
    if (result.count() == 0) {
        return null;
    } else {
        return result.next();
    }
}

From source file:org.ossmeter.platform.AbstractHistoricalMetricProvider.java

License:Open Source License

public List<Pongo> getHistoricalMeasurements(MetricProviderContext context, Project project, Date start,
        Date end) {/*  w w w  .j a v a  2s.  c  o m*/

    DB db = context.getProjectDB(project);
    DBCollection collection = db.getCollection(this.getCollectionName());

    QueryBuilder builder = QueryBuilder.start();
    if (start != null) {
        builder.and("__datetime").greaterThanEquals(start.toJavaDate());
    }
    if (end != null) {
        builder.and("__datetime").lessThanEquals(end.toJavaDate());
    }

    BasicDBObject query = (BasicDBObject) builder.get();

    Iterator<DBObject> it = collection.find(query).iterator();

    List<Pongo> pongoList = new ArrayList<Pongo>();

    while (it.hasNext()) {
        DBObject dbObject = it.next();
        pongoList.add(PongoFactory.getInstance().createPongo(dbObject));
    }

    return pongoList;

}