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.alfresco.bm.user.UserDataServiceImpl.java

License:Open Source License

/**
 * Ensure that the MongoDB collection has the required indexes associated with
 * this user bean./*from  w  w  w.  ja  va  2  s.com*/
 */
private void checkIndexes() {
    collection.setWriteConcern(WriteConcern.SAFE);

    DBObject uidxUserName = BasicDBObjectBuilder.start(FIELD_USERNAME, 1).get();
    DBObject optUserName = BasicDBObjectBuilder.start("name", "uidxUserName").add("unique", Boolean.TRUE).get();
    collection.createIndex(uidxUserName, optUserName);

    DBObject uidxEmail = BasicDBObjectBuilder.start(FIELD_EMAIL, 1).get();
    DBObject optEmail = BasicDBObjectBuilder.start("name", "uidxEmail").add("unique", Boolean.TRUE).get();
    collection.createIndex(uidxEmail, optEmail);

    DBObject idxDomainRand = BasicDBObjectBuilder.start(FIELD_DOMAIN, 1).add(FIELD_RANDOMIZER, 2).get();
    DBObject optDomainRand = BasicDBObjectBuilder.start("name", "idxDomainRand").add("unique", Boolean.FALSE)
            .get();
    collection.createIndex(idxDomainRand, optDomainRand);

    DBObject idxCreationStateRand = BasicDBObjectBuilder.start(FIELD_CREATION_STATE, 1).add(FIELD_RANDOMIZER, 2)
            .get();
    DBObject optCreationStateRand = BasicDBObjectBuilder.start("name", "idxCreationStateRand")
            .add("unique", Boolean.FALSE).get();
    collection.createIndex(idxCreationStateRand, optCreationStateRand);
}

From source file:org.apache.camel.component.mongodb.MongoDbTailTrackingManager.java

License:Apache License

public void initialize() throws Exception {
    if (!config.persistent) {
        return;//  w  ww.  j a  va 2s. c o  m
    }

    dbCol = connection.getDB(config.db).getCollection(config.collection);
    DBObject filter = new BasicDBObject("persistentId", config.persistentId);
    trackingObj = dbCol.findOne(filter);
    if (trackingObj == null) {
        dbCol.insert(filter, WriteConcern.SAFE);
        trackingObj = dbCol.findOne();
    }
    // keep only the _id, the rest is useless and causes more overhead during update
    trackingObj = new BasicDBObject("_id", trackingObj.get("_id"));
}

From source file:org.apache.camel.component.mongodb.MongoDbTailTrackingManager.java

License:Apache License

public synchronized void persistToStore() {
    if (!config.persistent || lastVal == null) {
        return;/*from w  w w  .  ja va 2 s .  c  o m*/
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Persisting lastVal={} to store, collection: {}", lastVal, config.collection);
    }

    DBObject updateObj = BasicDBObjectBuilder.start().add("$set", new BasicDBObject(config.field, lastVal))
            .get();
    dbCol.update(trackingObj, updateObj, false, false, WriteConcern.SAFE);
    trackingObj = dbCol.findOne();
}

From source file:org.apache.jmeter.protocol.mongodb.config.MongoSourceElement.java

License:Apache License

@Override
public void testStarted() {
    if (log.isDebugEnabled()) {
        log.debug(getTitle() + " testStarted");
    }/*from  ww  w  .ja  va 2  s.c om*/

    MongoClientOptions.Builder builder = MongoClientOptions.builder().autoConnectRetry(getAutoConnectRetry())
            .connectTimeout(getConnectTimeout()).connectionsPerHost(getConnectionsPerHost())
            .maxAutoConnectRetryTime(getMaxAutoConnectRetryTime()).maxWaitTime(getMaxWaitTime())
            .socketKeepAlive(getSocketKeepAlive()).socketTimeout(getSocketTimeout())
            .threadsAllowedToBlockForConnectionMultiplier(getThreadsAllowedToBlockForConnectionMultiplier());

    if (getSafe()) {
        builder.writeConcern(WriteConcern.SAFE);
    } else {
        builder.writeConcern(new WriteConcern(getWriteOperationNumberOfServers(), getWriteOperationTimeout(),
                getFsync(), getWaitForJournaling(), getContinueOnInsertError()));
    }
    MongoClientOptions mongoOptions = builder.build();

    if (log.isDebugEnabled()) {
        log.debug("options : " + mongoOptions.toString());
    }

    if (getThreadContext().getVariables().getObject(getSource()) != null) {
        if (log.isWarnEnabled()) {
            log.warn(getSource() + " has already been defined.");
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug(getSource() + "  is being defined.");
        }
        try {
            getThreadContext().getVariables().putObject(getSource(),
                    new MongoDB(MongoUtils.toServerAddresses(getConnection()), mongoOptions));
        } catch (UnknownHostException e) {
            throw new IllegalStateException(e);
        }
    }
}

From source file:org.apache.tapestry5.mongodb.modules.MongodbModule.java

License:Apache License

/**
 * Contribute coercions for {@link WriteConcern} and {@link ReadPreference} to have them from
 * {@link org.apache.tapestry5.ioc.annotations.Symbol}
 *
 * @param configuration lets help the {@link org.apache.tapestry5.ioc.services.TypeCoercer} service
 *//*  w  w w . j a  va2  s.  c  o  m*/
public static void contributeTypeCoercer(Configuration<CoercionTuple> configuration) {
    configuration.add(new CoercionTuple(String.class, WriteConcern.class, new Coercion<String, WriteConcern>() {
        public WriteConcern coerce(String input) {
            if (input.equalsIgnoreCase("FSYNC_SAFE")) {
                return WriteConcern.FSYNC_SAFE;
            } else if (input.equalsIgnoreCase("JOURNAL_SAFE")) {
                return WriteConcern.JOURNAL_SAFE;
            } else if (input.equalsIgnoreCase("MAJORITY")) {
                return WriteConcern.MAJORITY;
            } else if (input.equalsIgnoreCase("NONE")) {
                return WriteConcern.NONE;
            } else if (input.equalsIgnoreCase("REPLICAS_SAFE")) {
                return WriteConcern.REPLICAS_SAFE;
            } else if (input.equalsIgnoreCase("SAFE")) {
                return WriteConcern.SAFE;
            } else if (input.equalsIgnoreCase("NORMAL")) {
                return WriteConcern.NORMAL;
            } else // WriteConcern.ACKNOWLEDGED IS OUR DEFAULT
            {
                return WriteConcern.ACKNOWLEDGED;
            }
        }
    }));

    configuration
            .add(new CoercionTuple(String.class, ReadPreference.class, new Coercion<String, ReadPreference>() {
                public ReadPreference coerce(String input) {
                    if (input.equalsIgnoreCase("SECONDARY")) {
                        return ReadPreference.secondary();
                    } else // PRIMARY IS OUR DEFAULT
                    {
                        return ReadPreference.primary();
                    }
                }
            }));
}

From source file:org.apache.whirr.service.mongodb.integration.MongoDBServiceController.java

License:Apache License

private void getMongo(InetAddress mongoAddr) throws Exception {
    if (mongo == null || mongo.getAddress() != new ServerAddress(mongoAddr))
        mongo = new Mongo(new ServerAddress(mongoAddr));
    /**//from w w w  .jav a2s  .com
     * Test the connection...
     */
    mongo.getDB("test").getCollection("whirr_conn_validation").save(new BasicDBObject("foo", "bar"),
            WriteConcern.SAFE);

    LOG.info("Connected to MongoDB Server. ");
}

From source file:org.basex.modules.nosql.MongoDB.java

License:BSD License

/**
 * Mongodb Save function./*w ww . ja  v  a2  s  .  co m*/
 * @param handler database handler DB handler
 * @param col collection name
 * @param saveStr string to save(Map or Josn)
 * @param options other writeconcern options
 * @return Item result as item
 * @throws Exception exception
 */
public Item save(final Str handler, final Str col, final Item saveStr, final Map options) throws Exception {
    final DB db = getDbHandler(handler);
    db.requestStart();
    try {
        if (options == null) {
            WriteResult wr = db.getCollection(col.toJava()).save(getDbObjectFromItem(saveStr));
            return returnResult(handler, Str.get(wr.toString()));
        }
        //TODO write concern from the options
        WriteResult wr = db.getCollection(col.toJava()).save(getDbObjectFromItem(saveStr), WriteConcern.SAFE);
        return returnResult(handler, Str.get(wr.toString()));

    } catch (MongoException e) {
        throw MongoDBErrors.generalExceptionError(db.getLastError().getString("err"));
    } finally {
        db.requestDone();
    }
}

From source file:org.benjp.services.mongodb.MongoBootstrap.java

License:Open Source License

private Mongo mongo() {
    if (m == null) {
        try {//from w w  w .j av  a  2 s  . com
            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) {
        } catch (IOException e) {
        }
    }
    return m;
}

From source file:org.benjp.services.mongodb.TokenServiceImpl.java

License:Open Source License

public void addUser(String user, String token) {
    if (!hasUserWithToken(user, token)) {
        //System.out.println("TOKEN SERVICE :: ADDING :: " + user + " : " + token);
        //      removeUser(user);
        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();
            doc.put("token", token);
            doc.put("validity", System.currentTimeMillis());
            doc.put("isDemoUser", user.startsWith(ANONIM_USER));
            coll.save(doc, WriteConcern.SAFE);
        } else {// ww w  . j a v a  2  s .c o m
            BasicDBObject doc = new BasicDBObject();
            doc.put("_id", user);
            doc.put("user", user);
            doc.put("token", token);
            doc.put("validity", System.currentTimeMillis());
            doc.put("isDemoUser", user.startsWith(ANONIM_USER));
            coll.insert(doc);
        }
    }
}

From source file:org.benjp.services.mongodb.TokenServiceImpl.java

License:Open Source License

public void updateValidity(String user, String token) {
    DBCollection coll = db().getCollection(M_USERS_COLLECTION);
    BasicDBObject query = new BasicDBObject();
    query.put("user", user);
    query.put("token", token);
    DBCursor cursor = coll.find(query);/*w ww  .ja va 2 s.  com*/
    while (cursor.hasNext()) {
        DBObject doc = cursor.next();
        doc.put("validity", System.currentTimeMillis());
        coll.save(doc, WriteConcern.SAFE);
    }
}