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:org.alfresco.bm.user.UserDataServiceImpl.java

License:Open Source License

/**
 * {@inheritDoc}/*from www .  jav  a 2 s . c  o m*/
 */
@Override
public void setUserPassword(String username, String password) {
    DBObject queryObj = BasicDBObjectBuilder.start().add(FIELD_USERNAME, username).get();
    DBObject updateObj = BasicDBObjectBuilder.start().push("$set").add(FIELD_PASSWORD, password).pop().get();
    WriteResult result = collection.update(queryObj, updateObj);
    if (result.getN() != 1) {
        throw new RuntimeException("Failed to update user ticket: \n" + "   Username: " + username + "\n"
                + "   Password: " + password + "\n" + "   Result:   " + result);
    }
}

From source file:org.alfresco.bm.user.UserDataServiceImpl.java

License:Open Source License

/**
 * {@inheritDoc}/*from  w w  w. j a  v a  2 s . com*/
 */
@Override
public void setUserCreationState(String username, DataCreationState creationState) {
    DBObject queryObj = BasicDBObjectBuilder.start().add(FIELD_USERNAME, username).get();
    DBObject updateObj = BasicDBObjectBuilder.start().push("$set")
            .add(FIELD_CREATION_STATE, creationState.toString()).pop().get();
    WriteResult result = collection.update(queryObj, updateObj);
    if (result.getN() != 1) {
        throw new RuntimeException("Failed to update user creation state: \n" + "   Username:       " + username
                + "\n" + "   Creation State: " + creationState + "\n" + "   Result:         " + result);
    }
}

From source file:org.alfresco.bm.user.UserDataServiceImpl.java

License:Open Source License

@Override
public long deleteUsers(DataCreationState creationState) {
    BasicDBObjectBuilder queryObjBuilder = BasicDBObjectBuilder.start();
    if (creationState != null) {
        queryObjBuilder.add(FIELD_CREATION_STATE, creationState.toString());
    }// w  w  w. jav a2  s.c o m
    DBObject queryObj = queryObjBuilder.get();

    WriteResult result = collection.remove(queryObj);
    return result.getN();
}

From source file:org.alfresco.cacheserver.dao.mongo.MongoWebSocketDAO.java

License:Open Source License

protected void checkResult(WriteResult result, int expectedNum) {
    boolean ok = result.getLastError().ok();
    if (!ok) {/*  w w  w . ja  v a2s .c o m*/
        throw new RuntimeException("Mongo write failed");
    }
    if (expectedNum != result.getN()) {
        throw new RuntimeException(
                "Mongo write failed, expected " + expectedNum + " writes, got " + result.getN());
    }
}

From source file:org.apache.airavata.userprofile.core.UserProfileDao.java

License:Apache License

public boolean createUserProfile(UserProfile userProfile) throws UserProfileException {
    try {//  w  w w  .  j  a  v a  2s.co  m
        WriteResult result = collection
                .insert((DBObject) JSON.parse(modelConversionHelper.serializeObject(userProfile)));
        logger.debug("No of inserted results " + result.getN());
        return true;
    } catch (JsonProcessingException e) {
        throw new UserProfileException(e);
    }
}

From source file:org.apache.airavata.userprofile.core.UserProfileDao.java

License:Apache License

/**
 * The following operation replaces the document with item equal to
 * the given user id. The newly replaced document will only
 * contain the the _id field and the fields in the replacement document.
 * @param userProfile//from   w  w w .  j  ava  2s.  c o m
 * @throws org.apache.airavata.registry.cpi.UserProfileException
 */
public boolean updateUserProfile(UserProfile userProfile) throws UserProfileException {
    try {
        DBObject query = BasicDBObjectBuilder.start().add(USER_ID, userProfile.getUserId()).get();
        WriteResult result = collection.update(query,
                (DBObject) JSON.parse(modelConversionHelper.serializeObject(userProfile)));
        logger.debug("No of updated results " + result.getN());
        return true;
    } catch (JsonProcessingException e) {
        throw new UserProfileException(e);
    }
}

From source file:org.apache.airavata.userprofile.core.UserProfileDao.java

License:Apache License

public boolean deleteUserProfile(String userId) throws UserProfileException {
    DBObject query = BasicDBObjectBuilder.start().add(USER_ID, userId).get();
    WriteResult result = collection.remove(query);
    logger.debug("No of removed user profiles " + result.getN());
    return true;//from   w ww. j  a  v a2  s  . c  o m
}

From source file:org.apache.camel.component.mongodb.MongoDbProducer.java

License:Apache License

protected void doRemove(Exchange exchange) throws Exception {
    DBCollection dbCol = calculateCollection(exchange);
    DBObject removeObj = exchange.getIn().getMandatoryBody(DBObject.class);

    WriteConcern wc = extractWriteConcern(exchange);
    WriteResult result = wc == null ? dbCol.remove(removeObj) : dbCol.remove(removeObj, wc);

    Message resultMessage = prepareResponseMessage(exchange, MongoDbOperation.remove);
    // we always return the WriteResult, because whether the getLastError was called or not,
    // the user will have the means to call it or obtain the cached CommandResult
    processAndTransferWriteResult(result, exchange);
    resultMessage.setHeader(MongoDbConstants.RECORDS_AFFECTED, result.getN());
}

From source file:org.apache.camel.component.mongodb.MongoDbProducer.java

License:Apache License

@SuppressWarnings("unchecked")
protected void doUpdate(Exchange exchange) throws Exception {
    DBCollection dbCol = calculateCollection(exchange);
    List<DBObject> saveObj = exchange.getIn().getMandatoryBody((Class<List<DBObject>>) (Class<?>) List.class);
    if (saveObj.size() != 2) {
        throw new CamelMongoDbException(
                "MongoDB operation = insert, failed because body is not a List of DBObject objects with size = 2");
    }//from w  ww. ja  v a2 s .c om

    DBObject updateCriteria = saveObj.get(0);
    DBObject objNew = saveObj.get(1);

    Boolean multi = exchange.getIn().getHeader(MongoDbConstants.MULTIUPDATE, Boolean.class);
    Boolean upsert = exchange.getIn().getHeader(MongoDbConstants.UPSERT, Boolean.class);

    WriteResult result;
    WriteConcern wc = extractWriteConcern(exchange);
    // In API 2.7, the default upsert and multi values of update(DBObject, DBObject) are false, false, so we unconditionally invoke the
    // full-signature method update(DBObject, DBObject, boolean, boolean). However, the default behaviour may change in the future, 
    // so it's safer to be explicit at this level for full determinism
    if (multi == null && upsert == null) {
        // for update with no multi nor upsert but with specific WriteConcern there is no update signature without multi and upsert args,
        // so assume defaults
        result = wc == null ? dbCol.update(updateCriteria, objNew)
                : dbCol.update(updateCriteria, objNew, false, false, wc);
    } else {
        // we calculate the final boolean values so that if any of these
        // parameters is null, it is resolved to false
        result = wc == null
                ? dbCol.update(updateCriteria, objNew, calculateBooleanValue(upsert),
                        calculateBooleanValue(multi))
                : dbCol.update(updateCriteria, objNew, calculateBooleanValue(upsert),
                        calculateBooleanValue(multi), wc);
    }

    Message resultMessage = prepareResponseMessage(exchange, MongoDbOperation.update);
    // we always return the WriteResult, because whether the getLastError was called or not, the user will have the means to call it or 
    // obtain the cached CommandResult
    processAndTransferWriteResult(result, exchange);
    resultMessage.setHeader(MongoDbConstants.RECORDS_AFFECTED, result.getN());
}

From source file:org.apache.chemistry.opencmis.mongodb.MongodbUtils.java

License:Apache License

public BasicDBObject addNode(BasicDBObject node, BasicDBObject parent) {
    // Update all affected right and left values which are greater or equal
    // to the parents right value - we are incrementing to 'make room' for the 
    // new node//from www  . j a v a 2  s  .  c o m
    db.getCollection(COLLECTION_CONTENT).update(
            new BasicDBObject().append("right", new BasicDBObject().append("$gte", parent.getLong("right"))),
            new BasicDBObject().append("$inc", new BasicDBObject().append("right", 2)), false, true);

    db.getCollection(COLLECTION_CONTENT).update(
            new BasicDBObject().append("left", new BasicDBObject().append("$gte", parent.getLong("right"))),
            new BasicDBObject().append("$inc", new BasicDBObject().append("left", 2)), false, true);

    // Finally insert the node into the created space in the tree, under the parent
    node.append("left", parent.getLong("right")).append("right", parent.getLong("right") + 1).append("level",
            parent.getLong("level") + 1);

    WriteResult result = db.getCollection(COLLECTION_CONTENT).insert(node);
    if (result.getN() != 1) {
        throw new MongoException("Error while inserting the node into the database.");
    } else {
        return node.append("_id", result.getUpsertedId());
    }
}