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:com.aw.services.AncientWarServiceImpl.java

/**
 * /*from   www.  j  av a 2 s  . co m*/
 * @param userId
 * @return
 * @throws JSONException 
 */
@Override
public JSONObject browseUserVillage(Long userId) throws JSONException {
    DBCollection coll = MongoDbUtil.getCollection("ancient_war", "aw_user");
    DBObject query = QueryBuilder.start("uid").is(userId).get();
    DBCursor cursor = coll.find(query);
    JSONObject status = new JSONObject();
    while (cursor.hasNext()) {
        DBObject user = cursor.next();
        if (user != null) {
            Long uid = (Long) user.get("uid");
            JSONObject userVillage = getUserVillage(uid, "visit");
            return userVillage;
        } else {
            status.put("status", false);
            status.put("message", "No Village found");
            return status;
        }
    }
    return status;
}

From source file:com.bosscs.spark.mongodb.extractor.MongoNativeExtractor.java

License:Apache License

/**
 * Calculate splits.//from w w  w.j a v  a 2 s . c o  m
 *
 * @param collection the collection
 * @return the deep partition [ ]
 */
private HadoopPartition[] calculateSplits(DBCollection collection) {

    BasicDBList splitData = getSplitData(collection);
    List<ServerAddress> serverAddressList = collection.getDB().getMongo().getServerAddressList();

    if (splitData == null) {
        Pair<BasicDBList, List<ServerAddress>> pair = getSplitDataCollectionShardEnviroment(
                getShards(collection), collection.getDB().getName(), collection.getName());
        splitData = pair.left;
        serverAddressList = pair.right;
    }

    Object lastKey = null; // Lower boundary of the first min split

    List<String> stringHosts = new ArrayList<>();

    for (ServerAddress serverAddress : serverAddressList) {
        stringHosts.add(serverAddress.toString());
    }
    int i = 0;

    MongoPartition[] partitions = new MongoPartition[splitData.size() + 1];

    for (Object aSplitData : splitData) {

        BasicDBObject currentKey = (BasicDBObject) aSplitData;

        Object currentO = currentKey.get(MONGO_DEFAULT_ID);

        partitions[i] = new MongoPartition(mongoDeepJobConfig.getRddId(), i,
                new TokenRange(lastKey, currentO, stringHosts), MONGO_DEFAULT_ID);

        lastKey = currentO;
        i++;
    }
    QueryBuilder queryBuilder = QueryBuilder.start(MONGO_DEFAULT_ID);
    queryBuilder.greaterThanEquals(lastKey);
    partitions[i] = new MongoPartition(0, i, new TokenRange(lastKey, null, stringHosts), MONGO_DEFAULT_ID);
    return partitions;
}

From source file:com.bosscs.spark.mongodb.reader.MongoReader.java

License:Apache License

/**
 * Create query partition.//w  w w .  j av a2 s  . c o m
 *
 * @param partition the partition
 * @return the dB object
 */
private DBObject createQueryPartition(MongoPartition partition) {

    QueryBuilder queryBuilderMin = QueryBuilder.start(partition.getKey());
    DBObject bsonObjectMin = queryBuilderMin.greaterThanEquals(partition.splitWrapper().getStartToken()).get();

    QueryBuilder queryBuilderMax = QueryBuilder.start(partition.getKey());
    DBObject bsonObjectMax = queryBuilderMax.lessThan(partition.splitWrapper().getEndToken()).get();

    QueryBuilder queryBuilder = QueryBuilder.start();
    if (partition.splitWrapper().getStartToken() != null) {
        queryBuilder.and(bsonObjectMin.toString());
    }

    if (partition.splitWrapper().getEndToken() != null) {
        queryBuilder.and(bsonObjectMax.toString());
    }

    LOG.debug("mongodb query " + queryBuilder.get());

    return queryBuilder.get();
}

From source file:com.gederin.blog.dao.BlogPostDAO.java

License:Apache License

public DBObject findByPermalink(String permalink) {

    DBObject post = null;/*w w  w  .j  av  a  2 s.  c  om*/
    QueryBuilder queryBuilder = QueryBuilder.start("permalink").is(permalink);
    post = this.postsCollection.findOne(queryBuilder.get());
    // XXX HW 3.2,  Work Here

    return post;
}

From source file:com.gederin.blog.dao.UserDAO.java

License:Apache License

public DBObject validateLogin(String username, String password) {
    DBObject user = null;//from w ww  .ja  v a2 s . c  o m

    QueryBuilder queryBuilder = QueryBuilder.start("_id").is(username);
    user = this.usersCollection.findOne(queryBuilder.get());
    if (user == null) {
        System.out.println("User not in database");
        return null;
    }

    String hashedAndSalted = user.get("password").toString();

    String salt = hashedAndSalted.split(",")[1];

    if (!hashedAndSalted.equals(makePasswordHash(password, salt))) {
        System.out.println("Submitted password is not a match");
        return null;
    }

    return user;
}

From source file:com.groupon.jenkins.dynamic.build.repository.DynamicBuildRepository.java

License:Open Source License

public DbBackedBuild getPreviousFinishedBuildOfSameBranch(DbBackedBuild build, String branch) {
    BasicDBObject query = getQuery((DbBackedProject) build.getProject());
    query.append("branch", branch);
    query.append("state", "COMPLETED");
    query.putAll(QueryBuilder.start("number").lessThan(build.getNumber()).get());
    return findOne(query, null, new BasicDBObject("number", -1),
            getTransformer((DbBackedProject) build.getProject()));
}

From source file:com.ikanow.aleph2.shared.crud.mongodb.utils.MongoDbUtils.java

License:Apache License

/** Creates the MongoDB clause from the QueryComponent inner object
 * @param field - the field used in the clause
 * @param operator_args - an operator enum and a pair of objects whose context depends on the operator
 * @return the MongoDB clause/*from   w  ww .  j  av a2 s .  com*/
 */
protected static BasicDBObject operatorToMongoKey(final String field,
        final Tuple2<Operator, Tuple2<Object, Object>> operator_args) {
    return Patterns.match(operator_args).<BasicDBObject>andReturn()
            .when(op_args -> Operator.exists == op_args._1(),
                    op_args -> new BasicDBObject(field, new BasicDBObject("$exists", op_args._2()._1())))

            .when(op_args -> (Operator.any_of == op_args._1()),
                    op_args -> new BasicDBObject(field, new BasicDBObject("$in", op_args._2()._1())))
            .when(op_args -> (Operator.all_of == op_args._1()),
                    op_args -> new BasicDBObject(field, new BasicDBObject("$all", op_args._2()._1())))

            .when(op_args -> (Operator.equals == op_args._1()) && (null != op_args._2()._2()),
                    op_args -> new BasicDBObject(field, new BasicDBObject("$ne", op_args._2()._2())))
            .when(op_args -> (Operator.equals == op_args._1()),
                    op_args -> new BasicDBObject(field, op_args._2()._1()))

            .when(op_args -> Operator.range_open_open == op_args._1(), op_args -> {
                QueryBuilder qb = QueryBuilder.start(field);
                if (null != op_args._2()._1())
                    qb = qb.greaterThan(op_args._2()._1());
                if (null != op_args._2()._2())
                    qb = qb.lessThan(op_args._2()._2());
                return (BasicDBObject) qb.get();
            }).when(op_args -> Operator.range_open_closed == op_args._1(), op_args -> {
                QueryBuilder qb = QueryBuilder.start(field);
                if (null != op_args._2()._1())
                    qb = qb.greaterThan(op_args._2()._1());
                if (null != op_args._2()._2())
                    qb = qb.lessThanEquals(op_args._2()._2());
                return (BasicDBObject) qb.get();
            }).when(op_args -> Operator.range_closed_closed == op_args._1(), op_args -> {
                QueryBuilder qb = QueryBuilder.start(field);
                if (null != op_args._2()._1())
                    qb = qb.greaterThanEquals(op_args._2()._1());
                if (null != op_args._2()._2())
                    qb = qb.lessThanEquals(op_args._2()._2());
                return (BasicDBObject) qb.get();
            }).when(op_args -> Operator.range_closed_open == op_args._1(), op_args -> {
                QueryBuilder qb = QueryBuilder.start(field);
                if (null != op_args._2()._1())
                    qb = qb.greaterThanEquals(op_args._2()._1());
                if (null != op_args._2()._2())
                    qb = qb.lessThan(op_args._2()._2());
                return (BasicDBObject) qb.get();
            }).otherwise(op_args -> new BasicDBObject());
}

From source file:com.jim.im.offline.repo.OfflineMessageRepo.java

License:Open Source License

public List<ImMessage> findByTopicNameIn(Collection<String> topics, ObjectId lastMsgId) {
    DBObject queryCondition = QueryBuilder.start("topicName").in(topics).and("_id").greaterThanEquals(lastMsgId)
            .get();/*from www.j  a va 2 s .c  om*/
    Iterator<DBObject> result = messageCollection.find(queryCondition).limit(100).iterator();
    return MessageConverter.convert(result);
}

From source file:com.linuxbox.enkive.audit.mongodb.MongoAuditService.java

License:Open Source License

@Override
public AuditEntry getEvent(String identifier) throws AuditServiceException {
    final ObjectId idObject = ObjectId.massageToObjectId(identifier);
    final QueryBuilder queryBuilder = QueryBuilder.start(MongoDbConstants.OBJECT_ID_KEY).is(idObject);
    final DBObject resultObject = auditCollection.findOne(queryBuilder.get());
    return dbObjectToAuditEntry(resultObject);
}

From source file:com.linuxbox.util.lockservice.mongodb.MongoLockService.java

License:Open Source License

/**
 * Attempts to create the specified lock. If it fails it returns a record
 * describing the existing lock./*  www .  ja va2s .  c  om*/
 * 
 * @param identifier
 * @param notation
 * @return
 * @throws LockAcquisitionException
 */
public LockRequestFailure lockWithFailureData(String identifier, String notation)
        throws LockAcquisitionException {
    final DBObject query = QueryBuilder.start(LOCK_IDENTIFIER_KEY).is(identifier).get();

    for (int i = 0; i < LOCK_RETRY_ATTEMPTS; i++) {
        try {
            lock(identifier, notation);
            return null;
        } catch (LockAcquisitionException e) {
            final DBObject existingLockRecord = lockCollection.findOne(query);
            if (existingLockRecord != null) {
                return new LockRequestFailure(identifier, (Date) existingLockRecord.get(LOCK_TIMESTAMP_KEY),
                        (String) existingLockRecord.get(LOCK_NOTE_KEY));
            }

            // if we could not find the record, we'll loop back up and
            // re-attempt
        }
    }

    throw new LockAcquisitionException(identifier, "failed after " + LOCK_RETRY_ATTEMPTS + " attempts");
}