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:org.benjp.services.mongodb.UserServiceImpl.java
License:Open Source License
public void toggleFavorite(String user, String targetUser) { DBCollection coll = db().getCollection(M_USERS_COLLECTION); BasicDBObject query = new BasicDBObject(); query.put("user", user); DBCursor cursor = coll.find(query);/* w ww .j a v a2 s.c o m*/ if (cursor.hasNext()) { DBObject doc = cursor.next(); List<String> favorites = new ArrayList<String>(); if (doc.containsField("favorites")) { favorites = (List<String>) doc.get("favorites"); } if (favorites.contains(targetUser)) favorites.remove(targetUser); else favorites.add(targetUser); doc.put("favorites", favorites); coll.save(doc, WriteConcern.SAFE); } }
From source file:org.benjp.services.mongodb.UserServiceImpl.java
License:Open Source License
public void setSpaces(String user, List<SpaceBean> spaces) { List<String> spaceIds = new ArrayList<String>(); DBCollection coll = db().getCollection(M_ROOMS_COLLECTION); for (SpaceBean bean : spaces) { String room = ChatUtils.getRoomId(bean.getId()); spaceIds.add(room);//w w w. j av a 2 s. c o m BasicDBObject query = new BasicDBObject(); query.put("_id", room); DBCursor cursor = coll.find(query); if (!cursor.hasNext()) { BasicDBObject doc = new BasicDBObject(); doc.put("_id", room); doc.put("space_id", bean.getId()); doc.put("displayName", bean.getDisplayName()); doc.put("groupId", bean.getGroupId()); doc.put("shortName", bean.getShortName()); doc.put("type", ChatService.TYPE_ROOM_SPACE); coll.insert(doc); } else { DBObject doc = cursor.next(); String displayName = doc.get("displayName").toString(); if (!bean.getDisplayName().equals(displayName)) { doc.put("_id", room); doc.put("displayName", bean.getDisplayName()); doc.put("groupId", bean.getGroupId()); doc.put("shortName", bean.getShortName()); coll.save(doc); } } } coll = db().getCollection(M_USERS_COLLECTION); BasicDBObject query = new BasicDBObject(); query.put("user", user); DBCursor cursor = coll.find(query); if (cursor.hasNext()) { DBObject doc = cursor.next(); doc.put("spaces", spaceIds); coll.save(doc, WriteConcern.SAFE); } else { BasicDBObject doc = new BasicDBObject(); doc.put("_id", user); doc.put("user", user); doc.put("spaces", spaceIds); coll.insert(doc); } }
From source file:org.benjp.services.mongodb.UserServiceImpl.java
License:Open Source License
public void addTeamRoom(String user, String teamRoomId) { List<String> teamIds = new ArrayList<String>(); teamIds.add(teamRoomId);//from www . j a v a 2 s . co m DBCollection coll = db().getCollection(M_USERS_COLLECTION); BasicDBObject query = new BasicDBObject(); query.put("user", user); DBCursor cursor = coll.find(query); if (cursor.hasNext()) { DBObject doc = cursor.next(); if (doc.containsField("teams")) { List<String> existingTeams = ((List<String>) doc.get("teams")); if (!existingTeams.contains(teamRoomId)) existingTeams.add(teamRoomId); doc.put("teams", existingTeams); } else { doc.put("teams", teamIds); } coll.save(doc, WriteConcern.SAFE); } else { BasicDBObject doc = new BasicDBObject(); doc.put("_id", user); doc.put("user", user); doc.put("teams", teamIds); coll.insert(doc); } }
From source file:org.benjp.services.mongodb.UserServiceImpl.java
License:Open Source License
public void removeTeamUsers(String teamRoomId, List<String> users) { DBCollection coll = db().getCollection(M_USERS_COLLECTION); for (String user : users) { log.info("Team Remove : " + user); BasicDBObject query = new BasicDBObject(); query.put("user", user); DBCursor cursor = coll.find(query); if (cursor.hasNext()) { DBObject doc = cursor.next(); if (doc.containsField("teams")) { List<String> teams = (List<String>) doc.get("teams"); if (teams.contains(teamRoomId)) { teams.remove(teamRoomId); doc.put("teams", teams); coll.save(doc, WriteConcern.SAFE); }//w w w.j a v a 2s .c om } } } }
From source file:org.benjp.services.mongodb.UserServiceImpl.java
License:Open Source License
public String setStatus(String user, String status) { DBCollection coll = db().getCollection(M_USERS_COLLECTION); BasicDBObject query = new BasicDBObject(); query.put("user", user); DBCursor cursor = coll.find(query);//from w w w . ja va2 s.co m if (cursor.hasNext()) { DBObject doc = cursor.next(); doc.put("status", status); coll.save(doc, WriteConcern.SAFE); } else { BasicDBObject doc = new BasicDBObject(); doc.put("_id", user); doc.put("user", user); doc.put("status", status); coll.insert(doc); } return status; }
From source file:org.benjp.services.mongodb.UserServiceImpl.java
License:Open Source License
public void setAsAdmin(String user, boolean isAdmin) { DBCollection coll = db().getCollection(M_USERS_COLLECTION); BasicDBObject query = new BasicDBObject(); query.put("user", user); DBCursor cursor = coll.find(query);/*from ww w .j av a 2s.c o m*/ if (cursor.hasNext()) { DBObject doc = cursor.next(); doc.put("isSupportAdmin", isAdmin); coll.save(doc, WriteConcern.SAFE); } else { BasicDBObject doc = new BasicDBObject(); doc.put("_id", user); doc.put("user", user); doc.put("isSupportAdmin", isAdmin); coll.insert(doc); } }
From source file:org.bireme.interop.fromJson.Json2Mongo.java
License:Open Source License
@Override public void exportDocuments(final Iterable<JSONObject> it, final int tell) { if (it == null) { throw new NullPointerException("it"); }//w ww. java 2 s . co m if (tell <= 0) { throw new IllegalArgumentException("tell <= 0"); } BulkWriteOperation builder = coll.initializeOrderedBulkOperation(); //coll.initializeUnorderedBulkOperation(); int tot = 0; int bulkNum = 0; for (JSONObject obj : it) { if (++tot % tell == 0) { System.out.println("+++" + tot); } try { coll.insert(convertToDBObj(obj), WriteConcern.SAFE); } catch (IllegalArgumentException iae) { Logger.getLogger(this.getClass().getName()).severe(iae.getMessage()); } } /*for (JSONObject obj : it) { if (++tot % tell == 0) { System.out.println("+++" + tot); } bulkNum++; builder.insert(convertToDBObj(obj)); if (bulkNum >= MAX_BULK_DOCS) { System.out.print("Sending documents to MongoDB - "); final BulkWriteResult result = builder.execute(); final int inserted = result.getInsertedCount(); System.out.println("OK"); if (inserted < bulkNum) { final String msg = "Insertion error: inserted[" + inserted + "] expected[" + bulkNum + "]"; Logger.getLogger(Json2Mongo.class.getName()) .log(Level.SEVERE, msg); } bulkNum = 0; builder = coll.initializeOrderedBulkOperation(); //builder = coll.initializeUnorderedBulkOperation(); } } if (bulkNum > 0) { final BulkWriteResult result = builder.execute(); final int inserted = result.getInsertedCount(); if (inserted < bulkNum) { final String msg = "Insertion error: inserted[" + inserted + "] expected[" + bulkNum + "]"; Logger.getLogger(Json2Mongo.class.getName()) .log(Level.SEVERE, msg); } }*/ }
From source file:org.chililog.server.data.Controller.java
License:Apache License
/** * Returns the mongoDB write strategy used in saving. By default, it is set to <code>SAFE</code>. This means * exceptions are raised for network issues, and server errors; waits on a server for the write operation. However, * it can be overridden.//from ww w. java 2 s .co m */ protected WriteConcern getDBWriteConern() { return WriteConcern.SAFE; }
From source file:org.eclipse.jetty.nosql.mongodb.MongoSessionDataStore.java
License:Open Source License
/** * @see org.eclipse.jetty.server.session.SessionDataStore#delete(String) */// w ww . j a v a 2s .co m @Override public boolean delete(String id) throws Exception { if (LOG.isDebugEnabled()) LOG.debug("Remove:session {} for context ", id, _context); /* * Check if the session exists and if it does remove the context * associated with this session */ BasicDBObject mongoKey = new BasicDBObject(__ID, id); //DBObject sessionDocument = _dbSessions.findOne(mongoKey,_version_1); DBObject sessionDocument = _dbSessions.findOne(new BasicDBObject(__ID, id)); if (sessionDocument != null) { DBObject c = (DBObject) getNestedValue(sessionDocument, __CONTEXT); if (c == null) { //delete whole doc _dbSessions.remove(mongoKey, WriteConcern.SAFE); return false; } Set<String> contexts = c.keySet(); if (contexts.isEmpty()) { //delete whole doc _dbSessions.remove(mongoKey, WriteConcern.SAFE); return false; } if (contexts.size() == 1 && contexts.iterator().next().equals(getCanonicalContextId())) { //delete whole doc _dbSessions.remove(new BasicDBObject(__ID, id), WriteConcern.SAFE); return true; } //just remove entry for my context BasicDBObject remove = new BasicDBObject(); BasicDBObject unsets = new BasicDBObject(); unsets.put(getContextField(), 1); remove.put("$unset", unsets); WriteResult result = _dbSessions.update(mongoKey, remove, false, false, WriteConcern.SAFE); return true; } else { return false; } }
From source file:org.eclipse.jetty.nosql.mongodb.MongoSessionDataStore.java
License:Open Source License
/** * @see org.eclipse.jetty.server.session.AbstractSessionDataStore#doStore(String, SessionData, long) *//* w w w .jav a 2 s .c om*/ @Override public void doStore(String id, SessionData data, long lastSaveTime) throws Exception { NoSqlSessionData nsqd = (NoSqlSessionData) data; // Form query for upsert BasicDBObject key = new BasicDBObject(__ID, id); // Form updates BasicDBObject update = new BasicDBObject(); boolean upsert = false; BasicDBObject sets = new BasicDBObject(); BasicDBObject unsets = new BasicDBObject(); Object version = ((NoSqlSessionData) data).getVersion(); // New session if (lastSaveTime <= 0) { upsert = true; version = new Long(1); sets.put(__CREATED, nsqd.getCreated()); sets.put(__VALID, true); sets.put(getContextSubfield(__VERSION), version); sets.put(getContextSubfield(__LASTSAVED), data.getLastSaved()); sets.put(getContextSubfield(__LASTNODE), data.getLastNode()); sets.put(__MAX_IDLE, nsqd.getMaxInactiveMs()); sets.put(__EXPIRY, nsqd.getExpiry()); nsqd.setVersion(version); } else { sets.put(getContextSubfield(__LASTSAVED), data.getLastSaved()); sets.put(getContextSubfield(__LASTNODE), data.getLastNode()); version = new Long(((Number) version).longValue() + 1); nsqd.setVersion(version); update.put("$inc", _version_1); //if max idle time and/or expiry is smaller for this context, then choose that for the whole session doc BasicDBObject fields = new BasicDBObject(); fields.append(__MAX_IDLE, true); fields.append(__EXPIRY, true); DBObject o = _dbSessions.findOne(new BasicDBObject("id", id), fields); if (o != null) { Long tmpLong = (Long) o.get(__MAX_IDLE); long currentMaxIdle = (tmpLong == null ? 0 : tmpLong.longValue()); tmpLong = (Long) o.get(__EXPIRY); long currentExpiry = (tmpLong == null ? 0 : tmpLong.longValue()); if (currentMaxIdle != nsqd.getMaxInactiveMs()) sets.put(__MAX_IDLE, nsqd.getMaxInactiveMs()); if (currentExpiry != nsqd.getExpiry()) sets.put(__EXPIRY, nsqd.getExpiry()); } else LOG.warn("Session {} not found, can't update", id); } sets.put(__ACCESSED, nsqd.getAccessed()); Set<String> names = nsqd.takeDirtyAttributes(); if (lastSaveTime <= 0) { names.addAll(nsqd.getAllAttributeNames()); // note dirty may include removed names } for (String name : names) { Object value = data.getAttribute(name); if (value == null) unsets.put(getContextField() + "." + encodeName(name), 1); else sets.put(getContextField() + "." + encodeName(name), encodeName(value)); } // Do the upsert if (!sets.isEmpty()) update.put("$set", sets); if (!unsets.isEmpty()) update.put("$unset", unsets); WriteResult res = _dbSessions.update(key, update, upsert, false, WriteConcern.SAFE); if (LOG.isDebugEnabled()) LOG.debug("Save:db.sessions.update( {}, {},{} )", key, update, res); }