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.exoplatform.chat.services.mongodb.MongoBootstrap.java
License:Open Source License
private Mongo mongo() { if (m == null) { try {/* www. j av a2 s .c o m*/ if (PropertyManager.PROPERTY_SERVER_TYPE_EMBED .equals(PropertyManager.getProperty(PropertyManager.PROPERTY_SERVER_TYPE))) { LOG.warning("WE WILL NOW USE MONGODB IN EMBED MODE..."); LOG.warning("BE AWARE..."); LOG.warning("EMBED MODE SHOULD NEVER BE USED IN PRODUCTION!"); setupEmbedMongo(); } MongoOptions options = new MongoOptions(); options.connectionsPerHost = 200; options.connectTimeout = 60000; options.threadsAllowedToBlockForConnectionMultiplier = 10; options.autoConnectRetry = true; String host = PropertyManager.getProperty(PropertyManager.PROPERTY_SERVER_HOST); int port = Integer.parseInt(PropertyManager.getProperty(PropertyManager.PROPERTY_SERVER_PORT)); m = new Mongo(new ServerAddress(host, port), options); m.setWriteConcern(WriteConcern.SAFE); } catch (UnknownHostException e) { LOG.warning(e.getMessage()); } catch (IOException e) { LOG.warning(e.getMessage()); } } return m; }
From source file:org.exoplatform.chat.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); }/*from w ww.ja v a 2 s. c om*/ } } } }
From source file:org.exoplatform.mongo.service.impl.MongoRestServiceImpl.java
License:Open Source License
@POST @Path("/databases/{dbName}/collections/{collName}/documents") @Override// ww w . j a v a 2 s.c om public Response createDocument(@PathParam("dbName") String dbName, @PathParam("collName") String collName, org.exoplatform.mongo.entity.request.Document document, @Context HttpHeaders headers, @Context UriInfo uriInfo, @Context SecurityContext securityContext) { if (shutdown) { return Response.status(ServerError.SERVICE_UNAVAILABLE.code()) .entity(ServerError.SERVICE_UNAVAILABLE.message()).build(); } Response response = null; String user = null; try { Credentials credentials = authenticateAndAuthorize(headers, uriInfo, securityContext); user = credentials.getUserName(); String dbNamespace = constructDbNamespace(credentials.getUserName(), dbName); if (mongo.getDatabaseNames().contains(dbNamespace)) { DB db = mongo.getDB(dbNamespace); authServiceAgainstMongo(db); if (db.getCollectionNames().contains(collName)) { DBCollection dbCollection = db.getCollection(collName); String documentJson = document.getJson(); if (!StringUtils.isNullOrEmpty(documentJson)) { DBObject mongoDocument = (DBObject) JSON.parse(document.getJson()); try { dbCollection.insert(mongoDocument, WriteConcern.SAFE); ObjectId documentId = ((ObjectId) mongoDocument.get("_id")); if (documentId != null && !StringUtils.isNullOrEmpty(documentId.toString())) { URI statusSubResource = uriInfo .getBaseUriBuilder().path(MongoRestServiceImpl.class).path("/databases/" + dbName + "/collections/" + collName + "/documents/" + documentId) .build(); response = Response.created(statusSubResource).build(); } else { response = Response.status(ServerError.RUNTIME_ERROR.code()) .entity(ServerError.RUNTIME_ERROR.message()).build(); } } catch (DuplicateKey duplicateObject) { response = Response.status(ClientError.BAD_REQUEST.code()) .entity("Document already exists and could not be created").build(); } } else { response = Response.status(ClientError.BAD_REQUEST.code()) .entity("Document JSON is required").build(); } } else { response = Response.status(ClientError.NOT_FOUND.code()) .entity(collName + " does not exist in " + dbName).build(); } } else { response = Response.status(ClientError.NOT_FOUND.code()).entity(dbName + " does not exist").build(); } } catch (Exception exception) { response = lobException(exception, headers, uriInfo); } finally { updateStats(user, "createDocument"); } return response; }
From source file:org.exoplatform.mongo.service.impl.MongoRestServiceImpl.java
License:Open Source License
@PUT @Path("/databases/{dbName}/collections/{collName}/documents/{docId}") @Override/*from w w w . j av a 2 s .com*/ public Response updateDocument(@PathParam("dbName") String dbName, @PathParam("collName") String collName, @PathParam("docId") String docId, org.exoplatform.mongo.entity.request.Document document, @Context HttpHeaders headers, @Context UriInfo uriInfo, @Context SecurityContext securityContext) { if (shutdown) { return Response.status(ServerError.SERVICE_UNAVAILABLE.code()) .entity(ServerError.SERVICE_UNAVAILABLE.message()).build(); } Response response = null; String user = null; try { Credentials credentials = authenticateAndAuthorize(headers, uriInfo, securityContext); user = credentials.getUserName(); String dbNamespace = constructDbNamespace(credentials.getUserName(), dbName); if (mongo.getDatabaseNames().contains(dbNamespace)) { DB db = mongo.getDB(dbNamespace); authServiceAgainstMongo(db); if (db.getCollectionNames().contains(collName)) { DBCollection dbCollection = db.getCollection(collName); String documentJson = document.getJson(); if (!StringUtils.isNullOrEmpty(documentJson)) { DBObject incomingDocument = (DBObject) JSON.parse(documentJson); DBObject query = new BasicDBObject(); query.put("_id", new ObjectId(docId)); DBObject persistedDocument = dbCollection.findOne(query); URI statusSubResource = null; try { if (persistedDocument == null) { dbCollection.insert(incomingDocument, WriteConcern.SAFE); statusSubResource = uriInfo.getBaseUriBuilder().path(MongoRestServiceImpl.class) .path("/databases/" + dbName + "/collections/" + collName + "/documents/" + ((DBObject) incomingDocument.get("_id"))) .build(); response = Response.created(statusSubResource).build(); } else { dbCollection.save(incomingDocument); statusSubResource = uriInfo .getBaseUriBuilder().path(MongoRestServiceImpl.class).path("/databases/" + dbName + "/collections/" + collName + "/documents/" + docId) .build(); response = Response.ok(statusSubResource).build(); } } catch (DuplicateKey duplicateObject) { response = Response.status(ClientError.BAD_REQUEST.code()) .entity("Document already exists and could not be created").build(); } } else { response = Response.status(ClientError.BAD_REQUEST.code()) .entity("Document JSON is required").build(); } } else { response = Response.status(ClientError.NOT_FOUND.code()) .entity(collName + " does not exist in " + dbName).build(); } } else { response = Response.status(ClientError.NOT_FOUND.code()).entity(dbName + " does not exist").build(); } } catch (Exception exception) { response = lobException(exception, headers, uriInfo); } finally { updateStats(user, "updateDocument"); } return response; }
From source file:org.graylog2.database.MongoConnection.java
License:Open Source License
/** * Connect the instance./*from ww w . ja va 2 s . co m*/ */ public synchronized MongoClient connect() { if (m == null) { Builder options = new MongoClientOptions.Builder(); options.connectionsPerHost(maxConnections); options.threadsAllowedToBlockForConnectionMultiplier(threadsAllowedToBlockMultiplier); try { // Connect to replica servers if given. Else the standard way to one server. if (replicaServers != null && replicaServers.size() > 0) { m = new MongoClient(replicaServers, options.build()); } else { ServerAddress address = new ServerAddress(host, port); m = new MongoClient(address, options.build()); } db = m.getDB(database); db.setWriteConcern(WriteConcern.SAFE); // Try to authenticate if configured. if (useAuth) { if (!db.authenticate(username, password.toCharArray())) { throw new RuntimeException("Could not authenticate to database '" + database + "' with user '" + username + "'."); } } } catch (UnknownHostException e) { throw new RuntimeException("Cannot resolve host name for MongoDB", e); } } return m; }
From source file:org.graylog2.database.MongoConnectionImpl.java
License:Open Source License
/** * Connect the instance.// ww w . ja v a 2 s . com */ @Override public synchronized Mongo connect() { if (m == null) { try { m = new MongoClient(mongoClientURI); db = m.getDB(mongoClientURI.getDatabase()); db.setWriteConcern(WriteConcern.SAFE); } catch (UnknownHostException e) { throw new RuntimeException("Cannot resolve host name for MongoDB", e); } } try { db.command("{ ping: 1 }"); } catch (CommandFailureException e) { if (e.getCode() == 18) { throw new MongoException( "Couldn't connect to MongoDB. Please check the authentication credentials.", e); } else { throw new MongoException("Couldn't connect to MongoDB: " + e.getMessage(), e); } } return m; }
From source file:org.iternine.jeppetto.dao.mongodb.MongoDBQueryModelDAO.java
License:Apache License
@SuppressWarnings({ "unchecked" }) protected MongoDBQueryModelDAO(Class<T> entityClass, Map<String, Object> daoProperties, AccessControlContextProvider accessControlContextProvider) { this.dbCollection = ((DB) daoProperties.get("db")).getCollection(entityClass.getSimpleName()); this.enhancer = EnhancerHelper.getDirtyableDBObjectEnhancer(entityClass); dbCollection.setObjectClass(enhancer.getEnhancedClass()); DBCallback.FACTORY = new DBCallback.Factory() { @Override/* ww w . j a va2s .c o m*/ public DBCallback create(DBCollection dbCollection) { return new MongoDBCallback(dbCollection); } }; this.accessControlContextProvider = accessControlContextProvider; this.uniqueIndexes = ensureIndexes((List<String>) daoProperties.get("uniqueIndexes"), true); ensureIndexes((List<String>) daoProperties.get("nonUniqueIndexes"), false); this.optimisticLockEnabled = Boolean.parseBoolean((String) daoProperties.get("optimisticLockEnabled")); this.shardKeys = extractShardKeys((String) daoProperties.get("shardKeyPattern")); this.saveNulls = Boolean.parseBoolean((String) daoProperties.get("saveNulls")); if (daoProperties.containsKey("writeConcern")) { this.defaultWriteConcern = WriteConcern.valueOf((String) daoProperties.get("writeConcern")); } else { this.defaultWriteConcern = WriteConcern.SAFE; } if (Boolean.parseBoolean((String) daoProperties.get("showQueries"))) { queryLogger = LoggerFactory.getLogger(getClass()); } }
From source file:org.jongo.bench.BenchUtil.java
License:Apache License
public static void injectFriendsIntoDB(int nbDocuments) throws UnknownHostException { MongoCollection collection = getCollectionFromJongo(new JacksonMapper.Builder().build()); collection.drop();/* www .j ava2 s .c o m*/ for (int i = 0; i < nbDocuments; i++) { collection.withWriteConcern(WriteConcern.SAFE).save(createFriend(i)); } long count = collection.count(); if (count < nbDocuments) { throw new RuntimeException( "Not enough documents have been saved into db : expected " + nbDocuments + "/ saved: " + count); } }
From source file:org.jongo.bench.SaveBench.java
License:Apache License
protected void setUp() throws Exception { bsonCollection = getCollectionFromJongo(new JacksonMapper.Builder().build()) .withWriteConcern(WriteConcern.SAFE); dbCollection = getCollectionFromDriver(); bsonCollection.drop();/* www . jav a 2 s . co m*/ }
From source file:org.jwebsocket.http.MongoDBConnectorsManager.java
License:Apache License
/** * * @param aConnectorId//from w ww .ja va 2s . c o m * @throws Exception */ @Override public void remove(String aConnectorId) throws Exception { mConnectors.remove(new BasicDBObject().append(Attributes.CONNECTION_ID, aConnectorId), WriteConcern.SAFE); }