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.eclipse.jetty.nosql.mongodb.MongoSessionManager.java
License:Open Source License
@Override protected synchronized Object save(NoSqlSession session, Object version, boolean activateAfterSave) { try {//from ww w. j a v a2 s . c om __log.debug("MongoSessionManager:save session {}", session.getClusterId()); session.willPassivate(); // Form query for upsert BasicDBObject key = new BasicDBObject(__ID, session.getClusterId()); // Form updates BasicDBObject update = new BasicDBObject(); boolean upsert = false; BasicDBObject sets = new BasicDBObject(); BasicDBObject unsets = new BasicDBObject(); // handle valid or invalid if (session.isValid()) { long expiry = (session.getMaxInactiveInterval() > 0 ? (session.getAccessed() + (1000L * getMaxInactiveInterval())) : 0); __log.debug("MongoSessionManager: calculated expiry {} for session {}", expiry, session.getId()); // handle new or existing if (version == null) { // New session upsert = true; version = new Long(1); sets.put(__CREATED, session.getCreationTime()); sets.put(__VALID, true); sets.put(getContextAttributeKey(__VERSION), version); sets.put(__MAX_IDLE, getMaxInactiveInterval()); sets.put(__EXPIRY, expiry); } else { version = new Long(((Number) version).longValue() + 1); 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", session.getClusterId()), fields); if (o != null) { Integer currentMaxIdle = (Integer) o.get(__MAX_IDLE); Long currentExpiry = (Long) o.get(__EXPIRY); if (currentMaxIdle != null && getMaxInactiveInterval() > 0 && getMaxInactiveInterval() < currentMaxIdle) sets.put(__MAX_IDLE, getMaxInactiveInterval()); if (currentExpiry != null && expiry > 0 && expiry != currentExpiry) sets.put(__EXPIRY, expiry); } } sets.put(__ACCESSED, session.getAccessed()); Set<String> names = session.takeDirty(); if (isSaveAllAttributes() || upsert) { names.addAll(session.getNames()); // note dirty may include removed names } for (String name : names) { Object value = session.getAttribute(name); if (value == null) unsets.put(getContextKey() + "." + encodeName(name), 1); else sets.put(getContextKey() + "." + encodeName(name), encodeName(value)); } } else { sets.put(__VALID, false); sets.put(__INVALIDATED, System.currentTimeMillis()); unsets.put(getContextKey(), 1); } // Do the upsert if (!sets.isEmpty()) update.put("$set", sets); if (!unsets.isEmpty()) update.put("$unset", unsets); _dbSessions.update(key, update, upsert, false, WriteConcern.SAFE); if (__log.isDebugEnabled()) __log.debug("MongoSessionManager:save:db.sessions.update( {}, {} )", key, update); if (activateAfterSave) session.didActivate(); return version; } catch (Exception e) { LOG.warn(e); } return null; }
From source file:org.eclipse.jetty.nosql.mongodb.MongoSessionManager.java
License:Open Source License
@Override protected Object refresh(NoSqlSession session, Object version) { __log.debug("MongoSessionManager:refresh session {}", session.getId()); // check if our in memory version is the same as what is on the disk if (version != null) { DBObject o = _dbSessions.findOne(new BasicDBObject(__ID, session.getClusterId()), _version_1); if (o != null) { Object saved = getNestedValue(o, getContextAttributeKey(__VERSION)); if (saved != null && saved.equals(version)) { __log.debug("MongoSessionManager:refresh not needed session {}", session.getId()); return version; }/*from w w w . j av a 2s. c om*/ version = saved; } } // If we are here, we have to load the object DBObject o = _dbSessions.findOne(new BasicDBObject(__ID, session.getClusterId())); // If it doesn't exist, invalidate if (o == null) { __log.debug("MongoSessionManager:refresh:marking session {} invalid, no object", session.getClusterId()); session.invalidate(); return null; } // If it has been flagged invalid, invalidate Boolean valid = (Boolean) o.get(__VALID); if (valid == null || !valid) { __log.debug("MongoSessionManager:refresh:marking session {} invalid, valid flag {}", session.getClusterId(), valid); session.invalidate(); return null; } // We need to update the attributes. We will model this as a passivate, // followed by bindings and then activation. session.willPassivate(); try { DBObject attrs = (DBObject) getNestedValue(o, getContextKey()); //if disk version now has no attributes, get rid of them if (attrs == null || attrs.keySet().size() == 0) { session.clearAttributes(); } else { //iterate over the names of the attributes on the disk version, updating the value for (String name : attrs.keySet()) { //skip special metadata field which is not one of the session attributes if (__METADATA.equals(name)) continue; String attr = decodeName(name); Object value = decodeValue(attrs.get(name)); //session does not already contain this attribute, so bind it if (session.getAttribute(attr) == null) { session.doPutOrRemove(attr, value); session.bindValue(attr, value); } else //session already contains this attribute, update its value { session.doPutOrRemove(attr, value); } } // cleanup, remove values from session, that don't exist in data anymore: for (String str : session.getNames()) { if (!attrs.keySet().contains(encodeName(str))) { session.doPutOrRemove(str, null); session.unbindValue(str, session.getAttribute(str)); } } } /* * We are refreshing so we should update the last accessed time. */ BasicDBObject key = new BasicDBObject(__ID, session.getClusterId()); BasicDBObject sets = new BasicDBObject(); // Form updates BasicDBObject update = new BasicDBObject(); sets.put(__ACCESSED, System.currentTimeMillis()); // Do the upsert if (!sets.isEmpty()) { update.put("$set", sets); } _dbSessions.update(key, update, false, false, WriteConcern.SAFE); session.didActivate(); return version; } catch (Exception e) { LOG.warn(e); } return null; }
From source file:org.eclipse.jetty.nosql.mongodb.MongoSessionManager.java
License:Open Source License
/** * Remove the per-context sub document for this session id. * @see org.eclipse.jetty.nosql.NoSqlSessionManager#remove(org.eclipse.jetty.nosql.NoSqlSession) *///from w w w . j a v a 2s .c o m @Override protected boolean remove(NoSqlSession session) { __log.debug("MongoSessionManager:remove:session {} for context {}", session.getClusterId(), getContextKey()); /* * Check if the session exists and if it does remove the context * associated with this session */ BasicDBObject key = new BasicDBObject(__ID, session.getClusterId()); DBObject o = _dbSessions.findOne(key, _version_1); if (o != null) { BasicDBObject remove = new BasicDBObject(); BasicDBObject unsets = new BasicDBObject(); unsets.put(getContextKey(), 1); remove.put("$unset", unsets); _dbSessions.update(key, remove, false, false, WriteConcern.SAFE); return true; } else { return false; } }
From source file:org.eclipse.jetty.nosql.mongodb.MongoSessionManager.java
License:Open Source License
/** * @see org.eclipse.jetty.nosql.NoSqlSessionManager#expire(java.lang.String) *///from ww w. java 2 s . c om @Override protected void expire(String idInCluster) { __log.debug("MongoSessionManager:expire session {} ", idInCluster); //Expire the session for this context super.expire(idInCluster); //If the outer session document has not already been marked invalid, do so. DBObject validKey = new BasicDBObject(__VALID, true); DBObject o = _dbSessions.findOne(new BasicDBObject(__ID, idInCluster), validKey); if (o != null && (Boolean) o.get(__VALID)) { BasicDBObject update = new BasicDBObject(); BasicDBObject sets = new BasicDBObject(); sets.put(__VALID, false); sets.put(__INVALIDATED, System.currentTimeMillis()); update.put("$set", sets); BasicDBObject key = new BasicDBObject(__ID, idInCluster); _dbSessions.update(key, update, false, false, WriteConcern.SAFE); } }
From source file:org.eclipse.jetty.nosql.mongodb.MongoSessionManager.java
License:Open Source License
/** * Change the session id. Note that this will change the session id for all contexts for which the session id is in use. * @see org.eclipse.jetty.nosql.NoSqlSessionManager#update(org.eclipse.jetty.nosql.NoSqlSession, java.lang.String, java.lang.String) *///from w w w . j ava 2 s . co m @Override protected void update(NoSqlSession session, String newClusterId, String newNodeId) throws Exception { BasicDBObject key = new BasicDBObject(__ID, session.getClusterId()); BasicDBObject sets = new BasicDBObject(); BasicDBObject update = new BasicDBObject(__ID, newClusterId); sets.put("$set", update); _dbSessions.update(key, sets, false, false, WriteConcern.SAFE); }
From source file:org.eclipse.jetty.nosql.mongodb.MongoSessionStore.java
License:Open Source License
/** * @see org.eclipse.jetty.server.session.SessionStore#delete(String) *//*from w w w . j av a 2 s . c om*/ @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); if (sessionDocument != null) { DBObject c = (DBObject) getNestedValue(sessionDocument, __CONTEXT); if (c == null) { //delete whole doc _dbSessions.remove(mongoKey); return false; } Set<String> contexts = c.keySet(); if (contexts.isEmpty()) { //delete whole doc _dbSessions.remove(mongoKey); return false; } if (contexts.size() == 1 && contexts.iterator().next().equals(getCanonicalContextId())) { //delete whole doc _dbSessions.remove(mongoKey); return true; } //just remove entry for my context BasicDBObject remove = new BasicDBObject(); BasicDBObject unsets = new BasicDBObject(); unsets.put(getContextField(), 1); remove.put("$unset", unsets); _dbSessions.update(mongoKey, remove, false, false, WriteConcern.SAFE); return true; } else { return false; } }
From source file:org.eclipse.jetty.nosql.mongodb.MongoSessionStore.java
License:Open Source License
/** * @see org.eclipse.jetty.server.session.AbstractSessionStore#doStore(String, SessionData, long) */// ww w . j a v a 2 s . c o m @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(__MAX_IDLE, nsqd.getMaxInactiveMs()); sets.put(__EXPIRY, nsqd.getExpiry()); nsqd.setVersion(version); } else { 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); _dbSessions.update(key, update, upsert, false, WriteConcern.SAFE); if (LOG.isDebugEnabled()) LOG.debug("Save:db.sessions.update( {}, {} )", key, update); }
From source file:org.eclipse.persistence.nosql.adapters.mongo.MongoConnectionSpec.java
License:Open Source License
/** * Connect with the specified properties and return the Connection. *///from w ww . jav a 2 s . c o m public Connection connectToDataSource(EISAccessor accessor, Properties properties) throws DatabaseException, ValidationException { if ((this.connectionFactory == null) && (this.name == null)) { this.connectionFactory = new MongoConnectionFactory(); } if (!properties.isEmpty()) { if (this.connectionSpec == null) { this.connectionSpec = new MongoJCAConnectionSpec(); } MongoJCAConnectionSpec spec = (MongoJCAConnectionSpec) this.connectionSpec; String host = (String) properties.get(HOST); String port = (String) properties.get(PORT); String db = (String) properties.get(DB); if (host != null) { if (host.indexOf(',') == -1) { spec.getHosts().add(host); if (port != null) { spec.getPorts().add(new Integer(port)); } } else { int startIndex = 0; while (startIndex < (host.length() - 1)) { int endIndex = host.indexOf(',', startIndex); if (endIndex == -1) { endIndex = host.length(); } String nextHost = host.substring(startIndex, endIndex); spec.getHosts().add(nextHost); startIndex = endIndex + 1; } while (startIndex < (port.length() - 1)) { int endIndex = port.indexOf(',', startIndex); if (endIndex == -1) { endIndex = port.length(); } String nextPort = port.substring(startIndex, endIndex); spec.getPorts().add(new Integer(nextPort)); startIndex = endIndex + 1; } } } if (db != null) { spec.setDB(db); } String user = (String) properties.get("user"); Object password = properties.get("password"); if (password instanceof String) { password = ((String) password).toCharArray(); } if ((user != null) && (user.length() != 0)) { spec.setUser(user); spec.setPassword((char[]) password); } // Allows setting of read preference as a property. Object preference = properties.get(READ_PREFERENCE); if (preference instanceof ReadPreference) { spec.setReadPreference((ReadPreference) preference); } else if (preference instanceof String) { String constant = (String) preference; if (constant.equals("PRIMARY")) { spec.setReadPreference(ReadPreference.PRIMARY); } else if (constant.equals("SECONDARY")) { spec.setReadPreference(ReadPreference.SECONDARY); } else { throw new EISException("Invalid read preference property value: " + constant); } } // Allows setting of write concern as a property. Object concern = properties.get(WRITE_CONCERN); if (concern instanceof WriteConcern) { spec.setWriteConcern((WriteConcern) concern); } else if (concern instanceof String) { String constant = (String) concern; if (constant.equals("FSYNC_SAFE")) { spec.setWriteConcern(WriteConcern.FSYNC_SAFE); } else if (constant.equals("ACKNOWLEDGED")) { spec.setWriteConcern(WriteConcern.ACKNOWLEDGED); } else if (constant.equals("JOURNAL_SAFE")) { spec.setWriteConcern(WriteConcern.JOURNAL_SAFE); } else if (constant.equals("MAJORITY")) { spec.setWriteConcern(WriteConcern.MAJORITY); } else if (constant.equals("NONE")) { spec.setWriteConcern(WriteConcern.NONE); } else if (constant.equals("NORMAL")) { spec.setWriteConcern(WriteConcern.NORMAL); } else if (constant.equals("REPLICAS_SAFE")) { spec.setWriteConcern(WriteConcern.REPLICAS_SAFE); } else if (constant.equals("SAFE")) { spec.setWriteConcern(WriteConcern.SAFE); } else { throw new EISException("Invalid read preference property value: " + constant); } } // Allows setting of options as a property. Object options = properties.get(OPTIONS); if (options instanceof Number) { spec.setOptions(((Number) options).intValue()); } else if (options instanceof String) { spec.setOptions(Integer.valueOf(((String) options))); } } return super.connectToDataSource(accessor, properties); }
From source file:org.exoplatform.addons.persistence.services.mongodb.MongoBootstrap.java
License:Open Source License
private Mongo mongo() { if (m == null) { try {/*w w w . ja v a 2 s . c o m*/ if (PropertyManager.PROPERTY_DB_SERVER_TYPE_EMBED .equals(PropertyManager.getProperty(PropertyManager.PROPERTY_DB_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_DB_SERVER_HOST); int port = Integer.parseInt(PropertyManager.getProperty(PropertyManager.PROPERTY_DB_SERVER_PORT)); m = new Mongo(new ServerAddress(host, port), options); m.setWriteConcern(WriteConcern.SAFE); } catch (UnknownHostException e) { } catch (IOException e) { } } return m; }
From source file:org.exoplatform.addons.storage.services.mongodb.MongoBootstrap.java
License:Open Source License
private Mongo mongo() { if (m == null) { try {/*from w w w .jav a 2s . c o m*/ 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) { } catch (IOException e) { } } return m; }