Example usage for com.mongodb WriteResult getN

List of usage examples for com.mongodb WriteResult getN

Introduction

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

Prototype

public int getN() 

Source Link

Document

Gets the "n" field, which contains the number of documents affected in the write operation.

Usage

From source file:com.ikanow.infinit.e.processing.custom.scheduler.CustomScheduleManager.java

License:Open Source License

public static void createOrUpdatedSavedQueryCache() {
    if (null == _appLock) {
        _appLock = MongoApplicationLock.getLock(DbManager.getCustom().getSavedQueryCache().getDB().getName());
    }//from w w  w . j a  va  2s .c o m
    // the built-in applock acquisition code requires more persistent threads so we use the alternate mechanism that
    // just wipes out anything that hasn't been used in the last 2 minutes and then uses the existing contention handling to
    // allow one thread to grab it
    _appLock.clearStaleLocksOnTime(120);
    if (_appLock.acquire(100)) {
        BasicDBObject query = new BasicDBObject(SharePojo.type_, DocumentQueueControlPojo.SavedQueryQueue);
        List<SharePojo> savedQueries = SharePojo.listFromDb(DbManager.getSocial().getShare().find(query),
                SharePojo.listType());
        if (null != savedQueries) {
            for (SharePojo savedQueryShare : savedQueries) {
                if (null != savedQueryShare.getShare()) {
                    DocumentQueueControlPojo savedQuery = DocumentQueueControlPojo
                            .fromApi(savedQueryShare.getShare(), DocumentQueueControlPojo.class);

                    // Is this query well formed?
                    if ((null != savedQuery.getQueryInfo()) && ((null != savedQuery.getQueryInfo().getQuery())
                            || (null != savedQuery.getQueryInfo().getQueryId()))) {
                        Date now = new Date();
                        long freqOffset;
                        // Check if it's time to run the query
                        if (savedQuery.getQueryInfo()
                                .getFrequency() == DocumentQueueControlPojo.SavedQueryInfo.DocQueueFrequency.Hourly) {
                            freqOffset = 3600L * 1000L;
                            //(nothing to do here, just run whenever)
                        } //TESTED (test3)
                        else if (savedQuery.getQueryInfo()
                                .getFrequency() == DocumentQueueControlPojo.SavedQueryInfo.DocQueueFrequency.Daily) {
                            if (null != savedQuery.getQueryInfo().getFrequencyOffset()) { // hour of day
                                freqOffset = 12L * 3600L * 1000L; // (already check vs hour of day so be more relaxed) 
                                Calendar calendar = GregorianCalendar.getInstance();
                                calendar.setTime(now);

                                //DEBUG
                                //System.out.println("DAILY: " + calendar.get(Calendar.HOUR_OF_DAY) + " VS " + savedQuery.getQueryInfo().getFrequencyOffset());   

                                if (calendar.get(Calendar.HOUR_OF_DAY) != savedQuery.getQueryInfo()
                                        .getFrequencyOffset()) {
                                    continue;
                                } //TESTED (test4)
                            } else {
                                freqOffset = 24L * 3600L * 1000L; // (just run every 24 hours)                            
                            }
                        } //TESTED (test4)
                        else if (savedQuery.getQueryInfo()
                                .getFrequency() == DocumentQueueControlPojo.SavedQueryInfo.DocQueueFrequency.Weekly) {
                            if (null != savedQuery.getQueryInfo().getFrequencyOffset()) { // day of week
                                freqOffset = 3L * 24L * 3600L * 1000L; // (already check vs day of week so be more relaxed) 
                                Calendar calendar = GregorianCalendar.getInstance();
                                calendar.setTime(now);

                                //DEBUG
                                //System.out.println("WEEKLY: " + calendar.get(Calendar.DAY_OF_WEEK) + " VS " + savedQuery.getQueryInfo().getFrequencyOffset());

                                if (calendar.get(Calendar.DAY_OF_WEEK) != savedQuery.getQueryInfo()
                                        .getFrequencyOffset()) {
                                    continue;
                                }
                            } else {
                                freqOffset = 7L * 24L * 3600L * 1000L; //(just run every 7 days)
                            }
                        } //TESTED (test5)
                        else
                            continue; // (no -supported- frequency, don't run)

                        long nowTime = now.getTime();

                        //DEBUG
                        //System.out.println("Comparing: " + savedQuery.getQueryInfo().getLastRun() + " VS " + now + " @ " + freqOffset/1000L);

                        if ((null == savedQuery.getQueryInfo().getLastRun()) || ((nowTime
                                - savedQuery.getQueryInfo().getLastRun().getTime()) > freqOffset)) {
                            try {
                                //(does nothing if the share already exists)
                                WriteResult wr = DbManager.getCustom().getSavedQueryCache()
                                        .insert(savedQueryShare.toDb(), WriteConcern.ACKNOWLEDGED);

                                if (wr.getN() > 0) { // if we've actually done something, update the main share table also
                                    savedQuery.getQueryInfo().setLastRun(now);
                                    savedQueryShare.setShare(savedQuery.toApi());
                                    // (this will overwrite the existing version)
                                    DbManager.getSocial().getShare().save(savedQueryShare.toDb());
                                } //TESTED (by hand with prints)
                            } catch (MongoException e) {
                            } // just carry on - this is equivalent to getLastERror returning true

                        } //TESTED (test3-5)

                    } // (end saved query actually has a query)
                }
            } //(end loop over saved queries)
        }
    } //(end acquired app lock)
}

From source file:com.images3.data.impl.MongoDBAccess.java

License:Apache License

protected void checkForAffectedDocuments(WriteResult result, int expectedAffectedNumber) {
    if (result.getN() != expectedAffectedNumber) {
        throw new RuntimeException("Unexpected affected number of documents," + "" + result.getN() + " != "
                + expectedAffectedNumber);
    }/*w  w w .ja  v a2 s  .  c  o m*/
}

From source file:com.impetus.client.mongodb.MongoDBClient.java

License:Apache License

/**
 * Handle update functions.//ww  w  .j  a  va  2 s .  c o  m
 * 
 * @param query
 *            the query
 * @param update
 *            the update
 * @param collName
 *            the coll name
 * @return the int
 */
public int handleUpdateFunctions(BasicDBObject query, BasicDBObject update, String collName) {
    DBCollection collection = mongoDb.getCollection(collName);
    KunderaCoreUtils.printQuery("Update collection:" + query, showQuery);
    WriteResult result = null;
    try {
        result = collection.update(query, update);
    } catch (MongoException ex) {
        return -1;
    }
    if (result.getN() <= 0)
        return -1;
    return result.getN();
}

From source file:com.jjorgemoura.hangmanz.model.ZDHangmanGame.java

public void persist() {

    if (this.dbEngine == null) {

        return;/*from   w  w  w.ja v a  2  s .  c o  m*/
    }

    //Prepare JSON Document from Entity
    DBObject docX = this.createDBObject();

    //Prepare Collection
    DBCollection dbCollection = this.dbEngine.getCollection(ZDHangmanGame.DB_COLLECTION_ID);

    //Save - Write
    WriteResult dbInsertResult = dbCollection.insert(docX);

    //Finalise
    int n = dbInsertResult.getN();
    Object upsertedId = dbInsertResult.getUpsertedId();

    WriteConcern lastConcernObject = dbInsertResult.getLastConcern();

    String s = "ok";
}

From source file:com.mobileman.kuravis.core.services.event.impl.EventServiceImpl.java

License:Apache License

private int getAffectedCount(WriteResult result) {
    try {//  ww w .j ava2  s. co  m
        return result.getN();
    } catch (Exception e) {
        return -1;
    }
}

From source file:com.mobileman.moments.core.services.impl.EntityServiceImpl.java

License:Apache License

@Override
public boolean delete(T entity) {
    if (entity == null) {
        return false;
    }//w  ww  .  j a  v a2  s .co m

    WriteResult result = this.mongoTemplate.remove(Query.query(Criteria.where("_id").is(entity.getId())),
            getEntityType());
    if (result.getN() == 0) {
        return false;
    }

    return true;
}

From source file:com.mobileman.moments.core.services.social.impl.FriendshipServiceImpl.java

License:Apache License

@Override
public void deleteAllForUser(User user) {

    final Criteria where = new Criteria().orOperator(Criteria.where("fromUser.id").is(user.getId()),
            Criteria.where("toUser.id").is(user.getId()));
    final Query query = Query.query(where);
    WriteResult result = mongoTemplate.remove(query, Friendship.class);
    if (getLog().isInfoEnabled()) {
        getLog().info("Removed all friendship (" + result.getN() + ") of user: " + user);
    }//from   www  . j ava 2 s.c  om
}

From source file:com.mobileman.moments.core.services.user.impl.UserServiceImpl.java

License:Apache License

@Override
@ServiceActivator(inputChannel = MomentsESBConstants.QUESTION_DELETED_CHANNEL)
public void questionDeleted(final Question question) {

    mongoTemplate.execute(User.class, new CollectionCallback<Boolean>() {

        @Override//from w  ww . jav a  2 s  .  com
        public Boolean doInCollection(DBCollection collection) throws MongoException, DataAccessException {

            final Query query = Query
                    .query(Criteria.where("followed_questions._id").is(new ObjectId(question.getId())));
            final Update update = new Update().pull("followed_questions",
                    new BasicDBObject("_id", new ObjectId(question.getId())));
            WriteResult result = collection.update(query.getQueryObject(), update.getUpdateObject(), false,
                    true);

            return result.getN() > 0;
        }
    });

}

From source file:com.picdrop.repository.mongo.MorphiaRepository.java

@Override
public boolean delete(String id) {
    log.traceEntry();//from  www  . ja  va2s . c o m
    log.debug(REPO_DELETE, "Deleting entity of type '{}'", this.entityType.toString());
    if (!isValidIdentifier(id)) {
        return false;
    }
    Query<T> q = ds.createQuery(entityType).field("_id").equal(new ObjectId(id));
    WriteResult wr = ds.delete(q, wc);
    log.traceExit();
    return wr.getN() > 0;
}

From source file:com.redhat.lightblue.crud.mongo.BasicDocDeleter.java

License:Open Source License

@Override
public void delete(CRUDOperationContext ctx, DBCollection collection, DBObject mongoQuery,
        CRUDDeleteResponse response) {//from  www . j a  v  a  2  s  .  co  m
    LOGGER.debug("Removing docs with {}", mongoQuery);
    WriteResult result = new RemoveCommand(null, collection, mongoQuery).execute();
    LOGGER.debug("Removal complete, write result={}", result);
    response.setNumDeleted(result.getN());
}