Example usage for com.mongodb WriteConcern SAFE

List of usage examples for com.mongodb WriteConcern SAFE

Introduction

In this page you can find the example usage for com.mongodb WriteConcern SAFE.

Prototype

WriteConcern SAFE

To view the source code for com.mongodb WriteConcern SAFE.

Click Source Link

Document

Write operations that use this write concern will wait for acknowledgement from the primary server before returning.

Usage

From source file:org.sdsai.dsds.mongo.MongoNodeStore.java

License:Open Source License

/**
 * @see #MongoNodeStore(DBCollection, DBCollection, WriteConcern)
 *//*from   w  w  w. j av  a  2 s.  co m*/
public MongoNodeStore(final DBCollection nodeCollection, final DBCollection dataCollection) {
    this(nodeCollection, dataCollection, WriteConcern.SAFE);
}

From source file:org.slc.sli.dal.convert.ContainerDocumentAccessor.java

License:Apache License

protected boolean updateContainerDoc(final Query query, Map<String, Object> newValues, String collectionName,
        String type) {//from   w ww.  ja v  a2  s.  co  m
    final ContainerDocument containerDocument = containerDocumentHolder.getContainerDocument(type);
    if (containerDocument.isContainerSubdoc()) {
        Update update = new Update();
        for (Map.Entry<String, Object> patch : newValues.entrySet()) {
            update.set("body." + patch.getKey(), patch.getValue());
        }
        return getLocation(type).doUpdate(query, update);
    }

    //empty attendanceEvent(or other) array
    DBObject emptyArray = new BasicDBObject();
    emptyArray.put("body." + containerDocument.getFieldToPersist(), new ArrayList());
    DBObject setEmptyArray = new BasicDBObject("$set", emptyArray);
    mongoTemplate.getCollection(collectionName).update(query.getQueryObject(), setEmptyArray, false, false,
            WriteConcern.SAFE);

    TenantContext.setIsSystemCall(false);
    final String fieldToPersist = containerDocument.getFieldToPersist();
    DBObject entityDetails = new BasicDBObject();
    for (Map.Entry<String, Object> newValue : newValues.entrySet()) {
        if (!newValue.getKey().equals(containerDocument.getFieldToPersist())) {
            entityDetails.put("body." + newValue.getKey(), newValue.getValue());
        }
    }
    DBObject set = new BasicDBObject("$set", entityDetails);
    DBObject docToPersist = null;
    if (newValues.containsKey(containerDocument.getFieldToPersist())) {
        docToPersist = BasicDBObjectBuilder.start().push("$pushAll")
                .add("body." + fieldToPersist, newValues.get(fieldToPersist)).get();
    } else {
        docToPersist = new BasicDBObject();
    }

    docToPersist.putAll(set);

    return mongoTemplate.getCollection(collectionName)
            .update(query.getQueryObject(), docToPersist, true, false, WriteConcern.SAFE).getLastError().ok();
}

From source file:org.slc.sli.dal.convert.ContainerDocumentAccessor.java

License:Apache License

protected String insertContainerDoc(final DBObject query, final Entity entity) {
    TenantContext.setIsSystemCall(false);

    boolean persisted = true;

    final DBObject docToPersist = ContainerDocumentHelper.buildDocumentToPersist(containerDocumentHolder,
            entity, generatorStrategy, naturalKeyExtractor);
    ContainerDocument containerDocument = containerDocumentHolder.getContainerDocument(entity.getType());
    persisted &= mongoTemplate.getCollection(containerDocument.getCollectionToPersist())
            .update(query, docToPersist, true, false, WriteConcern.SAFE).getLastError().ok();

    String key = (String) query.get("_id");

    if (containerDocument.isContainerSubdoc()) {
        key = ContainerDocumentHelper.getContainerDocId(entity, generatorStrategy, naturalKeyExtractor);
        getLocation(entity.getType()).create(entity);

    }/*from w  w  w .jav a  2 s .  c o m*/

    if (persisted) {
        return key;
    } else {
        return "";
    }
}

From source file:org.slc.sli.ingestion.model.da.BatchJobMongoDA.java

License:Apache License

@Override
public boolean createFileLatch(String jobId, List<String> fileEntries) {
    try {//from  www .  j  a v  a2  s  . c o m
        final BasicDBObject latchObject = new BasicDBObject();
        latchObject.put(BATCHJOBID_FIELDNAME, jobId);
        latchObject.put(FILES, fileEntries);

        RetryMongoCommand retry = new RetryMongoCommand() {

            @Override
            public Object execute() {
                batchJobMongoTemplate.getCollection(FILE_ENTRY_LATCH).insert(latchObject, WriteConcern.SAFE);
                return null;
            }
        };

        retry.executeOperation(numberOfRetries);

    } catch (MongoException me) {
        if (me.getCode() == DUP_KEY_CODE) {
            LOG.debug(me.getMessage());
        }
        return false;
    }
    return true;
}

From source file:org.slc.sli.ingestion.model.da.BatchJobWriteConcernResolver.java

License:Apache License

@Override
public WriteConcern resolve(MongoAction action) {

    Class<?> entityClass = action.getEntityClass();
    if (entityClass != null && "Error".equals(entityClass.getSimpleName())) {
        return WriteConcern.NORMAL;
    }/*from  w w  w.j a v  a2 s  .c  o m*/

    return WriteConcern.SAFE;
}

From source file:org.socialhistoryservices.security.MongoUserDetailService.java

License:Open Source License

public void createUser(MongoUserDetails user) {

    if (user.getPassword() != null)
        user.setPassword(HashPassword.encrypt(HASH, user.getPassword()));

    final DBCollection coll = coll();
    BasicDBObject query = new BasicDBObject("username", user.getUsername());
    DBObject tmp = coll.findOne(query);//from  ww w. j  av  a  2s  .  c om
    if (tmp != null) {
        if (user.getPassword() == null) {
            user.setPassword((String) tmp.get("password"));
        }
        if (user.getAuthorities().size() == 0) {
            BasicDBList authorities = (BasicDBList) tmp.get("authorities");
            for (Object authority : authorities) {
                user.getAuthorities()
                        .add(new org.socialhistoryservices.security.MongoAuthority((String) authority));
            }
        }
    }

    BasicDBObject document = new BasicDBObject();
    document.put("username", user.getUsername());
    document.put("password", user.getPassword());
    document.put("enabled", user.isEnabled());
    document.put("accountNonExpired", user.isAccountNonExpired());
    document.put("accountNonLocked", user.isAccountNonLocked());
    document.put("credentialsNonExpired", user.isCredentialsNonExpired());
    BasicDBList authorities = new BasicDBList();
    for (GrantedAuthority authority : user.getAuthorities()) {
        authorities.add(authority.getAuthority());
    }
    document.put("authorities", authorities);
    final WriteResult result = coll.update(query, document, true, false, WriteConcern.SAFE);
    if (result.getN() == 0)
        log.error(new Exception("Adding the user failed: " + result.getError()));
    log.info("Persisted:\n" + document.toString());
}

From source file:org.socialhistoryservices.security.MongoUserDetailService.java

License:Open Source License

public boolean remove(String username) {

    final DBCollection coll = coll();
    final BasicDBObject query = new BasicDBObject("username", username);
    WriteResult result = coll.remove(query, WriteConcern.SAFE);
    return (result.getN() != 0);
}

From source file:org.springframework.social.connect.mongo.MongoConnectionService.java

License:Apache License

/**
 * Update a connection.//from  w  w  w  . java2 s.  c  om
 * 
 * @see org.springframework.social.connect.mongo.ConnectionService#update(java.lang.String, org.springframework.social.connect.Connection)
 */
@Override
public void update(String userId, Connection<?> userConn) {
    MongoConnection mongoCnn = converter.convert(userConn);
    mongoCnn.setUserId(userId);
    try {
        mongoTemplate.setWriteConcern(WriteConcern.SAFE);
        mongoTemplate.save(mongoCnn);
    } catch (DuplicateKeyException e) {
        Query q = query(where("userId").is(userId).and("providerId").is(mongoCnn.getProviderId())
                .and("providerUserId").is(mongoCnn.getProviderUserId()));

        Update update = Update.update("expireTime", mongoCnn.getExpireTime())
                .set("accessToken", mongoCnn.getAccessToken()).set("profileUrl", mongoCnn.getProfileUrl())
                .set("imageUrl", mongoCnn.getImageUrl()).set("displayName", mongoCnn.getDisplayName());

        mongoTemplate.findAndModify(q, update, MongoConnection.class);
    }
}

From source file:org.uom.fit.level2.datavis.repository.ChatServicesImpl.java

@Override
public boolean saveChatData(ChatData chatData) {
    try {//from ww w .  j  av a  2 s. co m
        Mongo mongo = new Mongo("localhost", 27017);
        DB db = mongo.getDB("datarepo");
        DBCollection collection = db.getCollection("message");
        Gson gson = new Gson();
        DBObject dbObject = (DBObject) JSON.parse(gson.toJson(chatData));
        WriteResult result = collection.insert(WriteConcern.SAFE, dbObject);
        return true;
    } catch (Exception e) {
        System.out.println("Exception Error createProect");
        return false;
    }
}

From source file:org.yla.demo.thymeleaf.core.config.db.MongoDBConfig.java

License:Apache License

@Bean
@Override//from  w ww  . j  av  a 2  s.co m
public Mongo mongo() throws Exception {

    Mongo mongo = new MongoClient("127.0.0.1", 27017);
    mongo.setWriteConcern(WriteConcern.SAFE);

    return mongo;
}