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.github.trask.sandbox.commandq.QueuedCommandDao.java

License:Apache License

public void delete(final ObjectId id) {
    Query<QueuedCommand> updateQuery = getDatastore().createQuery(QueuedCommand.class).filter("id =", id);
    WriteResult result = getDatastore().delete(updateQuery);
    // hopefully morphia WriteResult will introduce getHadError() like for UpdateResult
    String error = result.getError();
    if (!StringUtils.isEmpty(error)) {
        logger.error("deleteQueuedCommandOnSuccess(): delete error: {}", result.getError());
        // TODO what's the best fallback, if anything?
    }//from  w  ww. jav  a2  s  .  c o m
    if (result.getN() == 0) {
        logger.error("deleteQueuedCommandOnSuccess(): could not find id {} for deletion", id);
    }
}

From source file:com.hangum.tadpole.mongodb.core.query.MongoDBQuery.java

License:Open Source License

/**
 * insert document// www . j  a  va2 s .  com
 * 
 * @param userDB
 * @param colName
 * @param dbObject
 * @throws Exception
 */
public static void insertDocument(UserDBDAO userDB, String colName, List<DBObject> dbObject) throws Exception {
    if (dbObject.size() == 0)
        return;

    DBCollection collection = findCollection(userDB, colName);
    WriteResult wr = collection.insert(dbObject);
    if (logger.isDebugEnabled()) {
        try {
            logger.debug("[writer document]" + wr != null ? wr.toString() : "");
            logger.debug("[wr error]" + wr != null ? wr.getError() : "");
            logger.debug("[n]" + wr != null ? wr.getN() : "");
        } catch (Exception e) {
            logger.error("insert document", e);
        }
    }
}

From source file:com.hangum.tadpole.mongodb.core.query.MongoDBQuery.java

License:Open Source License

/**
 * delete document/* w  w w.j  ava2 s.  c om*/
 * 
 * @param userDB
 * @param colName
 * @param objectId
 * @throws Exception
 */
public static void deleteDocument(UserDBDAO userDB, String colName, DBObject dbObject) throws Exception {
    DBCollection collection = findCollection(userDB, colName);
    WriteResult wr = collection.remove(dbObject);

    if (logger.isDebugEnabled()) {
        logger.debug("[writer document]" + wr.toString());
        logger.debug(wr.getError());
        logger.debug("[n]" + wr.getN());
    }

    //     ?  
    if (wr.getN() == 0 && !"".equals(wr.getError())) {
        throw new Exception(wr.getError());
    }
}

From source file:com.ikanow.aleph2.security.web.IkanowV1CookieAuthentication.java

License:Apache License

private boolean saveSessionCookieInDb(CookieBean cookie) {
    int dwritten = 0;
    try {//from w w w  .  j a v  a2  s .c o  m
        BasicDBObject query = new BasicDBObject();
        query.put("_id", new ObjectId(cookie.get_id()));
        query.put("profileId", new ObjectId(cookie.getProfileId()));
        query.put("cookieId", new ObjectId(cookie.getCookieId()));
        query.put("startDate", cookie.getStartDate());
        query.put("lastActivity", cookie.getLastActivity());
        if (cookie.getApiKey() != null) {
            query.put("apiKey", cookie.getApiKey());
        }
        WriteResult result = getCookieStore().insert(query);
        dwritten = result.getN();

    } catch (Exception e) {
        logger.error("saveSessionCookieInDb caught exception", e);
    }
    return dwritten > 0;
}

From source file:com.ikanow.aleph2.security.web.IkanowV1CookieAuthentication.java

License:Apache License

public boolean deleteSessionCookieInDb(String userId) {
    int deleted = 0;
    try {/*  w  w  w  .j a  va 2s  .  c o m*/
        BasicDBObject query = new BasicDBObject();
        query.put("profileId", new ObjectId(userId));
        WriteResult result = getCookieStore().remove(query);
        deleted = result.getN();

    } catch (Exception e) {
        logger.error("deleteSessionCookieInDb caught exception", e);
    }
    return deleted > 0;
}

From source file:com.ikanow.aleph2.security.web.IkanowV1CookieAuthentication.java

License:Apache License

public boolean deleteSessionCookieInDbById(String cookieId) {
    int deleted = 0;
    try {/*from w  w w  . j  a v  a 2  s  . c om*/
        BasicDBObject query = new BasicDBObject();
        query.put("_id", new ObjectId(cookieId));
        WriteResult result = getCookieStore().remove(query);
        deleted = result.getN();

    } catch (Exception e) {
        logger.error("deleteSessionCookieInDbById caught exception", e);
    }
    return deleted > 0;
}

From source file:com.ikanow.infinit.e.api.authentication.CookieManager.java

License:Open Source License

public String cleanCookies(long milliInactive) {
    int removedCount = 0;
    //calculate time of last activity to remove things
    long inactiveBefore = new Date().getTime() - milliInactive;
    //Remove every cookie that has been inactive longer than milliInactive
    try {/* w ww  .ja v  a 2s .  co m*/
        BasicDBObject query = new BasicDBObject();
        query.put("apiKey", new BasicDBObject(DbManager.exists_, false)); // (don't ever delete API keys)
        query.put("lastActivity", new BasicDBObject("$lt", new Date(inactiveBefore)));
        // (pojo method doesn't support this type of query)

        WriteResult wr = DbManager.getSocial().getCookies().remove(query);
        removedCount = wr.getN();
    } catch (Exception e) {
        // If an exception occurs log the error
        logger.error("Exception Message: " + e.getMessage(), e);
    }
    return "Removed " + removedCount + " inactive cookies";
}

From source file:com.ikanow.infinit.e.api.social.sharing.ShareHandler.java

License:Open Source License

/**
 * removeShare/*from ww w .  j a  va 2s.c  o  m*/
 * Remove an individual share from the share collection, shares can only be removed by the
 * owner via the rest API (id retrieved via cookielookup).
 * @param shareIdStr
 * @return
 */
public ResponsePojo removeShare(String ownerIdStr, String shareIdStr) {
    ResponsePojo rp = new ResponsePojo();
    // Query = share._id and share.shareOwner._id (unless admin)
    BasicDBObject query = new BasicDBObject();
    query.put("_id", new ObjectId(shareIdStr));
    mustBeOwnerOrAdmin(ownerIdStr, query);

    try {
        //first we must get the share to see if we need to remove the binary portion
        SharePojo sp = SharePojo.fromDb(DbManager.getSocial().getShare().findOne(query), SharePojo.class);
        WriteResult wr = DbManager.getSocial().getShare().remove(query);
        if (wr.getN() == 1) {
            //if remvoe was successful, attempt to remove the gridfs entry
            if (sp.getBinaryId() != null) {
                //remove gridfs
                DbManager.getSocial().getShareBinary().remove(sp.getBinaryId());
            }
            rp.setResponse(new ResponseObject("Share", true, "Share removed from database successfully"));
        } else {
            rp.setResponse(new ResponseObject("Share", false,
                    "Unable to remove share from database successfully (reason: share does not exist or user does not own the share)."));
        }
    } catch (Exception e) {
        logger.error("Exception Message: " + e.getMessage(), e);
        rp.setResponse(new ResponseObject("Share", false, "Unable to remove share: " + e.getMessage()));
    }
    return rp;
}

From source file:com.ikanow.infinit.e.data_model.store.MongoDbManager.java

License:Apache License

@SuppressWarnings("deprecation")
public static void main(String[] args) throws UnknownHostException {
    MongoClient mc = new MongoClient(args[0]);
    long tnow = 0;
    DB db = mc.getDB("test");
    DBCollection test = db.getCollection("test123");
    BasicDBObject outObj = new BasicDBObject();
    int ITS = 1000;
    test.drop();/*  www. jav  a  2s .  c  o  m*/

    boolean checkPerformance = false;
    boolean checkFunctionality = false;
    boolean checkErrors = false;

    // 1] Performance

    if (checkPerformance) {

        // ack'd
        db.setWriteConcern(WriteConcern.ACKNOWLEDGED);
        test.drop();
        tnow = new Date().getTime();
        for (int i = 0; i < ITS; ++i) {
            outObj.remove("_id");
            outObj.put("val", i);
            test.save(outObj);
        }
        tnow = new Date().getTime() - tnow;
        System.out.println("1: Ack'd: " + tnow);

        // un ack'd
        db.setWriteConcern(WriteConcern.UNACKNOWLEDGED);
        test.drop();
        tnow = new Date().getTime();
        outObj = new BasicDBObject();
        for (int i = 0; i < ITS; ++i) {
            outObj.remove("_id");
            outObj.put("val", i);
            test.save(outObj);
        }
        tnow = new Date().getTime() - tnow;
        System.out.println("2: unAck'd: " + tnow);

        // un ack'd but call getLastError
        db.setWriteConcern(WriteConcern.UNACKNOWLEDGED);
        test.drop();
        tnow = new Date().getTime();
        outObj = new BasicDBObject();
        for (int i = 0; i < ITS; ++i) {
            outObj.remove("_id");
            outObj.put("val", i);
            test.save(outObj);
            db.getLastError();
        }
        tnow = new Date().getTime() - tnow;
        test.drop();
        System.out.println("3: unAck'd but GLEd: " + tnow);

        // ack'd override
        db.setWriteConcern(WriteConcern.UNACKNOWLEDGED);
        test.drop();
        tnow = new Date().getTime();
        outObj = new BasicDBObject();
        for (int i = 0; i < ITS; ++i) {
            outObj.remove("_id");
            outObj.put("val", i);
            test.save(outObj, WriteConcern.ACKNOWLEDGED);
            db.getLastError();
        }
        tnow = new Date().getTime() - tnow;
        System.out.println("4: unAck'd but ACKd: " + tnow);

        // Performance Results:
        // 2.6) (unack'd 100ms ... ack'd 27000)
        // 2.4) (same)
    }

    // 2] Functionality

    if (checkFunctionality) {

        // Unack:
        db.setWriteConcern(WriteConcern.UNACKNOWLEDGED);
        WriteResult wr = test.update(new BasicDBObject(),
                new BasicDBObject(DbManager.set_, new BasicDBObject("val2", "x")), false, true);
        CommandResult cr = db.getLastError();
        System.out.println("UNACK: wr: " + wr);
        System.out.println("UNACK: cr: " + cr);

        // bonus, check that we get N==0 when insert dup object
        WriteResult wr2 = test.insert(outObj);
        System.out.println("ACK wr2 = " + wr2.getN() + " all = " + wr2);
        CommandResult cr2 = db.getLastError();
        System.out.println("ACK cr2 = " + cr2);

        // Ack1:
        db.setWriteConcern(WriteConcern.ACKNOWLEDGED);
        wr = test.update(new BasicDBObject(), new BasicDBObject(DbManager.set_, new BasicDBObject("val3", "x")),
                false, true);
        cr = db.getLastError();
        System.out.println("ACK1: wr: " + wr);
        System.out.println("ACK1: cr: " + cr);

        // Ack2:
        db.setWriteConcern(WriteConcern.UNACKNOWLEDGED);
        wr = test.update(new BasicDBObject(), new BasicDBObject(DbManager.set_, new BasicDBObject("val4", "x")),
                false, true, WriteConcern.ACKNOWLEDGED);
        cr = db.getLastError();
        System.out.println("ACK2: wr: " + wr);
        System.out.println("ACK2: cr: " + cr);

        // bonus, check that we get N==0 when insert dup object
        wr2 = test.insert(outObj);
        System.out.println("ACK wr2 = " + wr2.getN() + " all = " + wr2);

        // Functionality results:
        // 2.6: unack wr == N/A, otherwise both have "n", "ok"
        // 2.4: unack wr == N/A all other wrs + crs identical 
    }

    if (checkErrors) {

        //set up sharding
        DbManager.getDB("admin").command(new BasicDBObject("enablesharding", "test"));
        // Ack:
        try {
            test.drop();
            test.createIndex(new BasicDBObject("key", 1));
            BasicDBObject command1 = new BasicDBObject("shardcollection", "test.test123");
            command1.append("key", new BasicDBObject("key", 1));
            DbManager.getDB("admin").command(command1);

            db.setWriteConcern(WriteConcern.ACKNOWLEDGED);
            outObj = new BasicDBObject("key", "test");
            test.save(outObj);
            WriteResult wr = test.update(new BasicDBObject(),
                    new BasicDBObject(DbManager.set_, new BasicDBObject("key", "test2")));
            System.out.println("ACK wr = " + wr);
        } catch (Exception e) {
            System.out.println("ACK err = " + e.toString());
        }

        // UnAck:
        try {
            test.drop();
            test.createIndex(new BasicDBObject("key", 1));
            BasicDBObject command1 = new BasicDBObject("shardcollection", "test.test123");
            command1.append("key", new BasicDBObject("key", 1));
            DbManager.getDB("admin").command(command1);

            db.setWriteConcern(WriteConcern.UNACKNOWLEDGED);
            outObj = new BasicDBObject("key", "test");
            test.save(outObj);
            WriteResult wr = test.update(new BasicDBObject(),
                    new BasicDBObject(DbManager.set_, new BasicDBObject("key", "test2")), false, false,
                    WriteConcern.ACKNOWLEDGED);
            System.out.println("ACK override wr = " + wr);
        } catch (Exception e) {
            System.out.println("ACK override  err = " + e.toString());
        }

        // UnAck:
        try {
            test.drop();
            test.createIndex(new BasicDBObject("key", 1));
            BasicDBObject command1 = new BasicDBObject("shardcollection", "test.test123");
            command1.append("key", new BasicDBObject("key", 1));
            DbManager.getDB("admin").command(command1);

            db.setWriteConcern(WriteConcern.UNACKNOWLEDGED);
            outObj = new BasicDBObject("key", "test");
            test.save(outObj);
            WriteResult wr = test.update(new BasicDBObject(),
                    new BasicDBObject(DbManager.set_, new BasicDBObject("key", "test2")));
            System.out.println("UNACK wr = " + wr);
        } catch (Exception e) {
            System.out.println("UNACK err = " + e.toString());
        }

        // UnAck + GLE:
        try {
            test.drop();
            test.createIndex(new BasicDBObject("key", 1));
            BasicDBObject command1 = new BasicDBObject("shardcollection", "test.test123");
            command1.append("key", new BasicDBObject("key", 1));
            DbManager.getDB("admin").command(command1);

            db.setWriteConcern(WriteConcern.UNACKNOWLEDGED);
            outObj = new BasicDBObject("key", "test");
            test.save(outObj);
            WriteResult wr = test.update(new BasicDBObject(),
                    new BasicDBObject(DbManager.set_, new BasicDBObject("key", "test2")));
            CommandResult cr = db.getLastError();
            System.out.println("UNACK GLE wr = " + wr);
            System.out.println("UNACK GLE cr = " + cr);
        } catch (Exception e) {
            System.out.println("UNACK GLE err = " + e.toString());
        }

        // Error handling:

        // 2.6:
        // Ack - exception
        // Ack override - exception
        // UnAck - no error given
        // UnAck + GLE  - gle error

        // 2.4:
        // Ack - exception
        // Ack override - exception
        // UnAck - no error given
        // UnAck + GLE  - gle error

    }
}

From source file:com.ikanow.infinit.e.data_model.utils.MongoTransactionLock.java

License:Apache License

protected synchronized boolean updateToken(boolean bForce) {
    if (_bHaveControl || bForce) {
        DBCollection cachedCollection = _collections.get();
        BasicDBObject lockObj = new BasicDBObject();

        long nOneUp = Long.parseLong(_savedOneUp);
        lockObj.put(hostname_, getHostname());
        String newOneUp = Long.toString(nOneUp + 1);
        lockObj.put(oneUp_, newOneUp);//  w  w  w  .jav a2  s. c o  m
        lockObj.put(lastUpdated_, new Date());
        BasicDBObject queryObj = new BasicDBObject();
        queryObj.put(hostname_, _savedHostname);
        queryObj.put(oneUp_, _savedOneUp);
        WriteResult wr = cachedCollection.update(queryObj, new BasicDBObject(MongoDbManager.set_, lockObj),
                false, true);
        // (need the true in case the db is sharded)

        if (wr.getN() > 0) {
            _savedOneUp = newOneUp;
            _bHaveControl = true;
            _nLastCheck = 0;
            return true;
        } else {
            return false;
        }
    }
    return false;
}