List of usage examples for com.mongodb WriteConcern SAFE
WriteConcern SAFE
To view the source code for com.mongodb WriteConcern SAFE.
Click Source Link
Write operations that use this write concern will wait for acknowledgement from the primary server before returning.
From source file:com.mobileman.kuravis.core.Data.java
License:Apache License
/** * @param template/*from w w w . j a v a 2s.c o m*/ * @param userService */ public static void setUp(MongoTemplate template, UserService userService) { if (initialized) { return; } initialized = true; for (String collection : EntityUtils.getAllEntityNames()) { template.getDb().getCollection(collection).remove(new BasicDBObject(), WriteConcern.SAFE); } List<DBObject> users = UserServiceTest.getUsers(); for (DBObject user : users) { if ("peter.novak@test.com".equals(user.get("email"))) { continue; } userService.signup(user); DBObject account = template.getDb().getCollection(EntityUtils.USERACCOUNT) .findOne(new BasicDBObject("email", user.get("email"))); account.put("roles", Arrays.asList(String.class.cast(user.get("roles")).toLowerCase())); template.getDb().getCollection(EntityUtils.USERACCOUNT) .update(new BasicDBObject("email", user.get("email")), account); DBObject savedUser = template.getDb().getCollection(EntityUtils.USER) .findOne(new BasicDBObject("email", user.get("email"))); savedUser.put("state", Arrays.asList(user.get("state"))); template.getDb().getCollection(EntityUtils.USER).update(new BasicDBObject("email", user.get("email")), savedUser); } List<DBObject> diseases = DiseaseServiceTest.getDiseases(); for (DBObject dbObject : diseases) { template.getDb().getCollection(Disease.ENTITY_NAME).save(dbObject); } List<Unit> units = UnitServiceTest.getUnits(); for (Unit dbObject : units) { template.save(dbObject); } List<TreatmentType> treatmentTypes = TreatmentTypeServiceTest.getTreatmentTypes(); for (TreatmentType dbObject : treatmentTypes) { template.save(dbObject); } List<Psychotherapy> psychotherapies = PsychotherapyTest.getPsychotherapies(); for (Psychotherapy object : psychotherapies) { template.save(object); } List<Physiotherapie> physiotherapies = PhysiotherapieTest.getPsychotherapies(); for (Physiotherapie object : physiotherapies) { template.save(object); } users = UserServiceTest.getUsers(); int idx = 0; for (DBObject user : users) { DBObject disease = diseases.get(idx++ % 3); DBObject diseaseCopy = new BasicDBObject(EntityUtils.ID, disease.get(EntityUtils.ID)) .append(Disease.NAME, disease.get(Disease.NAME)); DiseaseState state = idx % 5 == 0 ? User.DiseaseState.CURED : User.DiseaseState.IN_THERAPY; DBObject userDisease = new BasicDBObject("createdOn", new Date()).append("state", state.getValue()) .append("disease", diseaseCopy); user.put("diseases", Arrays.asList(userDisease)); template.getDb().getCollection(EntityUtils.USER).save(user); } List<DBObject> accounts = UserServiceTest.getAccounts(); for (DBObject dbObject : accounts) { template.getDb().getCollection(EntityUtils.USERACCOUNT).save(dbObject); } List<DBObject> treatments = TreatmentServiceTest.getTreatments(); for (DBObject dbObject : treatments) { template.getDb().getCollection(EntityUtils.TREATMENT).save(dbObject); } List<DBObject> treatmentreviews = TreatmentReviewServiceTest.createTreatmentReviews(diseases.get(3), treatments.get(4)); for (DBObject dbObject : treatmentreviews) { template.getDb().getCollection(TreatmentReview.ENTITY_NAME).save(dbObject); } for (DBObject dbObject : TreatmentReviewServiceTest.getTreatmentReviewsSummaries()) { template.getDb().getCollection(TreatmentReviewSummary.ENTITY_NAME).save(dbObject); } for (DBObject dbObject : TreatmentReviewServiceTest.getTreatmentReviewSummaryAgeStatistics()) { template.getDb().getCollection(EntityUtils.TREATMENT_SUMMARY_AGE_STATISTICS).save(dbObject); } initialized = true; }
From source file:com.mobileman.kuravis.core.services.treatment_review.impl.TreatmentReviewServiceImpl.java
License:Apache License
@Override public DBObject voteForTreatmentReview(String entityId) { if (StringUtils.isEmpty(entityId)) { return ErrorUtils.error("Undefine entity ID", ErrorCodes.INCORRECT_PARAMETER); }/* ww w . ja v a2 s . c o m*/ Subject currentUser = SecurityUtils.getSubject(); if (currentUser == null || !currentUser.isAuthenticated()) { return ErrorUtils.error("Not authenticated: currentUser=" + currentUser, ErrorCodes.USER_NOT_AUTHENTICATED); } DBObject review = getCollection().findOne(new BasicDBObject(EntityUtils.ID, entityId)); if (review == null) { return ErrorUtils.error("Specified entity type does not exists: " + entityId, ErrorCodes.INCORRECT_PARAMETER); } DBObject user = (DBObject) currentUser.getPrincipal(); if (user == null) { return ErrorUtils.error("Not authenticated: currentUser=" + currentUser, ErrorCodes.USER_NOT_AUTHENTICATED); } if (RoleUtils.isNonverifiedUser(user)) { return ErrorUtils.error("Not authorized: user=" + user, ErrorCodes.UNAUTHORIZED); } DBObject atributesToUpdate = null; String treatmentReviewVoteId = EntityUtils.createTreatmentReviewVoteId(review.get(EntityUtils.ID), user.get(EntityUtils.ID)); DBObject treatmentReviewVote = getMongoTemplate().getCollection(EntityUtils.TREATMENT_REVIEW_EVENT) .findOne(new BasicDBObject(EntityUtils.ID, treatmentReviewVoteId)); // already voted - unvote if (treatmentReviewVote != null) { getCollection(EntityUtils.TREATMENT_REVIEW_EVENT) .remove(new BasicDBObject(EntityUtils.ID, treatmentReviewVoteId)); atributesToUpdate = new BasicDBObject("$inc", new BasicDBObject("votesCount", -1)).append("$set", new BasicDBObject(EntityUtils.MODIFIED_ON, new Date())); getCollection(EntityUtils.USER).update(new BasicDBObject(EntityUtils.ID, user.get(EntityUtils.ID)), new BasicDBObject("$inc", new BasicDBObject("statistics.votesCount", -1))); } else { // vote treatmentReviewVote = EntityUtils.createTreatmentReviewEvent(review, treatmentReviewVoteId, TreatmentReviewEventType.VOTE, user); getCollection(EntityUtils.TREATMENT_REVIEW_EVENT).save(treatmentReviewVote); atributesToUpdate = new BasicDBObject("$inc", new BasicDBObject("votesCount", 1)).append("$set", new BasicDBObject("lastVotedOn", new Date()).append(EntityUtils.MODIFIED_ON, new Date())); getCollection(EntityUtils.USER).update(new BasicDBObject(EntityUtils.ID, user.get(EntityUtils.ID)), new BasicDBObject("$inc", new BasicDBObject("statistics.votesCount", 1))); this.userNotificationService.createNotificationForTreatmentReviewVote((DBObject) review.get("author"), treatmentReviewVote); this.eventService.createVoteEvent(review, treatmentReviewVote); } WriteResult updateResult = getCollection().update(new BasicDBObject(EntityUtils.ID, entityId), atributesToUpdate, false, false, WriteConcern.SAFE); if (ErrorUtils.isError(updateResult)) { return ErrorUtils.error(updateResult); } DBCursor cursor = getMongoTemplate().getCollection(ENTITY_NAME) .find(new BasicDBObject(EntityUtils.ID, entityId), new BasicDBObject("votesCount", 1)); Number votesCount = (Number) review.get("votesCount"); if (cursor.hasNext()) { DBObject obj = cursor.next(); votesCount = (Number) obj.get("votesCount"); } if (votesCount == null) { votesCount = 1; } DBObject result = ErrorUtils.success(); result.put("count", votesCount.intValue()); return result; }
From source file:com.mobileman.kuravis.core.services.user.impl.UserServiceImpl.java
License:Apache License
/** * {@inheritDoc}//from w ww. j a va 2 s . co m */ @Override public DBObject changeResetedPassword(String resetPasswordUuid, String password) { log.info("changePassword(" + resetPasswordUuid + ", ..., ...) - start"); if (StringUtils.isEmpty(resetPasswordUuid)) { return ErrorUtils.error("Endefined account", ErrorCodes.INCORRECT_PARAMETER); } DBObject account = getCollection(EntityUtils.USERACCOUNT) .findOne(new BasicDBObject("resetPasswordUuid", resetPasswordUuid)); if (account == null) { return ErrorUtils.error("Undefined account", ErrorCodes.UNAUTHORIZED); } String hash = null; try { hash = com.mobileman.kuravis.core.util.security.SecurityUtils.getSaltedHash(password); WriteResult result = getCollection(EntityUtils.USERACCOUNT).update( new BasicDBObject("resetPasswordUuid", resetPasswordUuid), new BasicDBObject("$set", new BasicDBObject("password", hash)).append("$unset", new BasicDBObject("resetPasswordUuid", "")), false, false, WriteConcern.SAFE); if (!StringUtils.isEmpty(result.getError())) { } } catch (Exception e) { return ErrorUtils.error(e.getMessage(), ErrorCodes.INTERNAL_ERROR); } log.info("changePassword(" + resetPasswordUuid + ", ..., ...) - end"); return ErrorUtils.success(); }
From source file:com.mobileman.kuravis.core.services.user.impl.UserServiceImpl.java
License:Apache License
/** * {@inheritDoc}//from ww w. ja v a 2 s. com * @see com.mobileman.kuravis.core.services.user.UserService#changePassword(java.lang.String, java.lang.String) */ @Override public DBObject changePassword(String password, String password2) { log.info("changePassword(..., ...) - start"); DBObject user = UserUtils.getLoggedUser(); if (!ObjectUtils.nullSafeEquals(password, password2)) { return ErrorUtils.error("Password not same", ErrorCodes.PASSWORD_NOT_SAME); } DBObject checkResult = checkPassword(password); if (checkResult != null) { return checkResult; } String hash = null; try { hash = com.mobileman.kuravis.core.util.security.SecurityUtils.getSaltedHash(password2); WriteResult result = getCollection(EntityUtils.USERACCOUNT).update( new BasicDBObject(EntityUtils.ID, user.get(User.ATTR_ACCOUNT_ID)), new BasicDBObject("$set", new BasicDBObject("password", hash)), false, false, WriteConcern.SAFE); if (!StringUtils.isEmpty(result.getError())) { ErrorUtils.error(result.getError(), ErrorCodes.INTERNAL_ERROR); } } catch (Exception e) { return ErrorUtils.error(e.getMessage(), ErrorCodes.INTERNAL_ERROR); } log.info("changePassword(..., ...) - end"); return ErrorUtils.success(); }
From source file:com.mobileman.kuravis.core.services.user.impl.UserServiceImpl.java
License:Apache License
/** * {@inheritDoc}/* w w w. j ava 2 s. c om*/ * @see com.mobileman.kuravis.core.services.user.UserService#signup(com.mongodb.DBObject) */ @SuppressWarnings("unchecked") @Override public DBObject signup(DBObject data) { log.trace("signup(" + data + ") - start"); String email = (String) data.get("email"); if (StringUtils.isEmpty(email)) { return ErrorUtils.error("email not defined", ErrorCodes.INCORRECT_PARAMETER); } String password = (String) data.get("password"); if (StringUtils.isEmpty(password)) { return ErrorUtils.error("password not defined", ErrorCodes.INCORRECT_PARAMETER); } String userName = (String) data.get("name"); if (StringUtils.isEmpty(userName)) { return ErrorUtils.error("user name not defined", ErrorCodes.INCORRECT_PARAMETER); } DBObject validationError = validateEmail(email); if (validationError != null) { return validationError; } List<Map<String, Object>> diseases = (List<Map<String, Object>>) data.get("diseases"); if (diseases != null) { for (Map<String, Object> disease : diseases) { disease.put("createdOn", new Date()); } } DBObject newUser = EntityUtils.newDBObjectId(); newUser.put("name", userName); newUser.put("aboutMe", data.get("aboutMe")); newUser.put(User.ATTR_GENDER, data.get(User.ATTR_GENDER)); newUser.put("location", data.get("location")); newUser.put(User.ATTR_YEAR_OF_BIRTH, data.get(User.ATTR_YEAR_OF_BIRTH)); newUser.put("registrationDate", new Date()); newUser.put("diseases", diseases); newUser.put("email", email); newUser.put("state", UserState.UNVERIFIED.getValue()); newUser.put("invitationCount", 0); createSettings(newUser); String activationUuid = EntityUtils.newId(); DBObject account = EntityUtils.newDBObjectId(); account.put("email", email); account.put("activationUuid", activationUuid); account.put("roles", Arrays.asList(Roles.NONVERIFIED_USER)); account.put("userId", newUser.get(EntityUtils.ID)); try { account.put("password", com.mobileman.kuravis.core.util.security.SecurityUtils.getSaltedHash(password)); } catch (Exception e) { return ErrorUtils.createErrorResult(e); } newUser.put("accountId", account.get(EntityUtils.ID)); WriteResult saveResult = getCollection().save(newUser, WriteConcern.SAFE); if (!StringUtils.isEmpty(saveResult.getError())) { return ErrorUtils.error(saveResult.getError()); } saveResult = getCollection(EntityUtils.USERACCOUNT).save(account, WriteConcern.SAFE); if (!StringUtils.isEmpty(saveResult.getError())) { return ErrorUtils.error(saveResult.getError()); } mailService.sendActivationEmail(newUser, activationUuid); DBObject result = ErrorUtils.success(); return result; }
From source file:com.novemberain.quartz.mongodb.MongoDBJobStore.java
License:Open Source License
private Mongo connectToMongoDB() throws SchedulerConfigException { if (mongoUri != null) { return connectToMongoDB(mongoUri); }//from ww w.j av a 2 s . c om MongoClientOptions.Builder optionsBuilder = MongoClientOptions.builder(); optionsBuilder.writeConcern(WriteConcern.SAFE); if (mongoOptionAutoConnectRetry != null) optionsBuilder.autoConnectRetry(mongoOptionAutoConnectRetry); if (mongoOptionMaxConnectionsPerHost != null) optionsBuilder.connectionsPerHost(mongoOptionMaxConnectionsPerHost); if (mongoOptionConnectTimeoutMillis != null) optionsBuilder.connectTimeout(mongoOptionConnectTimeoutMillis); if (mongoOptionSocketTimeoutMillis != null) optionsBuilder.socketTimeout(mongoOptionSocketTimeoutMillis); if (mongoOptionSocketKeepAlive != null) optionsBuilder.socketKeepAlive(mongoOptionSocketKeepAlive); if (mongoOptionThreadsAllowedToBlockForConnectionMultiplier != null) optionsBuilder.threadsAllowedToBlockForConnectionMultiplier( mongoOptionThreadsAllowedToBlockForConnectionMultiplier); MongoClientOptions options = optionsBuilder.build(); try { ArrayList<ServerAddress> serverAddresses = new ArrayList<ServerAddress>(); for (String a : addresses) { serverAddresses.add(new ServerAddress(a)); } return new MongoClient(serverAddresses, options); } catch (UnknownHostException e) { throw new SchedulerConfigException("Could not connect to MongoDB", e); } catch (MongoException e) { throw new SchedulerConfigException("Could not connect to MongoDB", e); } }
From source file:com.oreilly.springdata.mongodb.ApplicationConfig.java
License:Apache License
@Override public Mongo mongo() throws Exception { Mongo mongo = new Mongo(); mongo.setWriteConcern(WriteConcern.SAFE); return mongo; }
From source file:com.redhat.lightblue.crud.mongo.BasicDocSaver.java
License:Open Source License
@Override public void saveDoc(CRUDOperationContext ctx, Op op, boolean upsert, DBCollection collection, EntityMetadata md, DBObject dbObject, DocCtx inputDoc) { WriteResult result = null;/* www . java 2 s . c om*/ String error = null; Object id = dbObject.get(MongoCRUDController.ID_STR); if (op == DocSaver.Op.insert || (id == null && upsert)) { // Inserting result = insertDoc(ctx, collection, md, dbObject, inputDoc); } else if (op == DocSaver.Op.save && id != null) { // Updating LOGGER.debug("Updating doc {}" + id); BasicDBObject q = new BasicDBObject(MongoCRUDController.ID_STR, new ObjectId(id.toString())); DBObject oldDBObject = new FindOneCommand(null, collection, q).execute(); if (oldDBObject != null) { if (md.getAccess().getUpdate().hasAccess(ctx.getCallerRoles())) { JsonDoc oldDoc = translator.toJson(oldDBObject); inputDoc.setOriginalDocument(oldDoc); List<Path> paths = roleEval.getInaccessibleFields_Update(inputDoc, oldDoc); if (paths == null || paths.isEmpty()) { translator.addInvisibleFields(oldDBObject, dbObject, md); result = new UpdateCommand(null, collection, q, dbObject, upsert, upsert, WriteConcern.SAFE) .execute(); inputDoc.setOperationPerformed(Operation.UPDATE); } else { inputDoc.addError( Error.get("update", CrudConstants.ERR_NO_FIELD_UPDATE_ACCESS, paths.toString())); } } else { inputDoc.addError(Error.get("update", CrudConstants.ERR_NO_ACCESS, "update:" + md.getName())); } } else { // Cannot update, doc does not exist, insert result = insertDoc(ctx, collection, md, dbObject, inputDoc); } } else { // Error, invalid request LOGGER.warn("Invalid request, cannot update or insert"); inputDoc.addError(Error.get(op.toString(), MongoCrudConstants.ERR_SAVE_ERROR, "Invalid request")); } LOGGER.debug("Write result {}", result); if (result != null) { if (error == null) { error = result.getError(); } if (error != null) { inputDoc.addError(Error.get(op.toString(), MongoCrudConstants.ERR_SAVE_ERROR, error)); } } }
From source file:com.redhat.lightblue.crud.mongo.BasicDocSaver.java
License:Open Source License
private WriteResult insertDoc(CRUDOperationContext ctx, DBCollection collection, EntityMetadata md, DBObject dbObject, DocCtx inputDoc) { LOGGER.debug("Inserting doc"); if (!md.getAccess().getInsert().hasAccess(ctx.getCallerRoles())) { inputDoc.addError(Error.get("insert", MongoCrudConstants.ERR_NO_ACCESS, "insert:" + md.getName())); } else {//ww w. j a v a 2 s . co m List<Path> paths = roleEval.getInaccessibleFields_Insert(inputDoc); LOGGER.debug("Inaccessible fields:{}", paths); if (paths == null || paths.isEmpty()) { try { WriteResult r = new InsertCommand(null, collection, dbObject, WriteConcern.SAFE).execute(); inputDoc.setOperationPerformed(Operation.INSERT); return r; } catch (MongoException.DuplicateKey dke) { LOGGER.error("saveOrInsert failed: {}", dke); inputDoc.addError(Error.get("insert", MongoCrudConstants.ERR_DUPLICATE, dke.toString())); } } else { inputDoc.addError(Error.get("insert", CrudConstants.ERR_NO_FIELD_INSERT_ACCESS, paths.toString())); } } return null; }
From source file:com.redhat.lightblue.crud.mongo.IterateDeleter.java
License:Open Source License
@Override public void delete(CRUDOperationContext ctx, DBCollection collection, DBObject mongoQuery, CRUDDeleteResponse response) {//w ww. ja v a 2s. co m LOGGER.debug("Computing the result set for {}", mongoQuery); DBCursor cursor = null; int docIndex = 0; int numDeleted = 0; try { // Find docs cursor = new FindCommand(null, collection, mongoQuery, null).execute(); LOGGER.debug("Found {} documents", cursor.count()); // read-delet while (cursor.hasNext()) { DBObject document = cursor.next(); LOGGER.debug("Retrieved doc {}", docIndex); Object id = document.get(MongoCRUDController.ID_STR); DocCtx doc = ctx.addDocument(translator.toJson(document)); doc.setOriginalDocument(doc); WriteResult result = new RemoveCommand(null, collection, new BasicDBObject("_id", id), WriteConcern.SAFE).execute(); if (result.getN() == 1) { numDeleted++; doc.setOperationPerformed(Operation.DELETE); } docIndex++; } } finally { if (cursor != null) { cursor.close(); } } response.setNumDeleted(numDeleted); }