Example usage for com.mongodb WriteConcern WriteConcern

List of usage examples for com.mongodb WriteConcern WriteConcern

Introduction

In this page you can find the example usage for com.mongodb WriteConcern WriteConcern.

Prototype

@Deprecated
public WriteConcern(final boolean fsync) 

Source Link

Document

Constructs an instance with the given value for fsync.

Usage

From source file:com.github.sakserv.storm.bolt.MongoBolt.java

License:Apache License

@Override
public void execute(Tuple input) {
    if (shouldActOnInput(input)) {
        String collectionName = getMongoCollectionForInput(input);
        DBObject dbObject = getDBObjectForInput(input);
        if (dbObject != null) {
            try {
                mongoDB.getCollection(collectionName).save(dbObject, new WriteConcern(1));
                collector.ack(input);/*w  w  w.  j av  a  2s  .  c  o  m*/
            } catch (MongoException me) {
                collector.fail(input);
            }
        }
    } else {
        collector.ack(input);
    }
}

From source file:com.github.sakserv.storm.bolt.MongoUpsertBolt.java

License:Apache License

@Override
public void execute(Tuple input) {
    if (shouldActOnInput(input)) {
        DBObject dbObject = getDBObjectForInput(input);
        String collectionName = input.getValueByField("table").toString();
        String mutationType = input.getValueByField("mutation").toString();
        Integer idVal = (int) input.getValueByField("_id");

        if (dbObject != null) {
            try {

                if (mutationType.equals("DeleteMutation")) {
                    mongoDB.getCollection(collectionName).remove(new BasicDBObject("_id", idVal));
                } else {
                    // Insert or update
                    mongoDB.getCollection(collectionName).save(dbObject, new WriteConcern(1));
                    collector.ack(input);
                }/* w ww.j  a va  2s.com*/
            } catch (MongoException me) {
                collector.fail(input);
            }
        }
    } else {
        collector.ack(input);
    }
}

From source file:com.torodb.testing.mongodb.docker.ReplicaSet.java

License:Apache License

/**
 * Returns a {@link WriteConcern} that guarantees that the write will be seen by all nodes before
 * returning./*from  www  .ja va  2 s. co  m*/
 *
 * @throws IllegalStateException if the service is not running
 */
public default WriteConcern getTotalWriteConcern() throws IllegalStateException {
    return new WriteConcern(getMongos().size());
}

From source file:net.handle.server.MongoDBHandleStorage.java

License:Open Source License

/**
 * Initialize the MongoDB storage object with the given settings.
 */// ww w .  j ava  2  s  . c o  m
public void init(StreamTable config) throws Exception {

    // load the MongoDB driver, if configured. Otherwise this will throw a class not found exception.
    if (config.containsKey(DRIVER_CLASS)) {
        Class.forName(String.valueOf(config.get(DRIVER_CLASS)));
    }

    // get the database URL and other connection parameters
    this.username = (String) config.get(LOGIN);
    this.passwd = (String) config.get(PASSWD);
    setDatabase((String) config.get(DATABASE_NAME));
    this.databaseURL = (StreamVector) config.get(URL);
    StreamVector indices = (StreamVector) config.get(COLLECTION_INDICES);
    if (indices == null) {
        indices = new StreamVector();
        indices.add("handle");
    }
    this.indices = indices.subList(0, indices.size());
    this.collection_nas = (String) config.get(COLLECTION_NAS);
    final String c_s = ((String) config.get(CASE_SENSITIVE, "no")).toLowerCase();
    this.case_sensitive = (c_s.equalsIgnoreCase("yes"));
    this.readOnly = config.getBoolean(READ_ONLY, false);
    if (mongo == null) {
        final MongoClientOptions.Builder builder = new MongoClientOptions.Builder()
                .description("Handle System driver " + getClass())
                .writeConcern(new WriteConcern(config.getInt(WRITECONCERN, 1)))
                .connectionsPerHost(config.getInt(CONNECTIONS_PER_HOST, 11))
                .readPreference(ReadPreference.nearest());

        this.mongo = new MongoDBSingleton((String[]) databaseURL.toArray(new String[databaseURL.size()]),
                builder.build()).getInstance();
        if (username != null && passwd != null) {
            final boolean authenticate = authenticate(database, username, passwd.toCharArray());
            if (!authenticate) {
                throw new HandleException(HandleException.UNABLE_TO_AUTHENTICATE, "Access denied.");
            }
        }
    }
}

From source file:org.datanucleus.store.mongodb.MongoDBPersistenceHandler.java

License:Open Source License

@Override
public void insertObjects(ObjectProvider... ops) {
    // This is called by the flush() process, so groups inserts.
    List<ObjectProvider> insertOps = new ArrayList<ObjectProvider>();
    for (int i = 0; i < ops.length; i++) {
        insertOps.add(ops[i]);// ww w.  j  a va2s. co m
    }

    if (ops.length == 1) {
        insertObject(ops[0]);
        return;
    }

    // Process "identity" cases first in case they are referenced
    for (int i = 0; i < ops.length; i++) {
        AbstractClassMetaData cmd = ops[i].getClassMetaData();
        if (cmd.pkIsDatastoreAttributed(storeMgr)) {
            insertObject(ops[i]);
        }
    }

    // Separate the objects to be persisted into groups, for the "table" in question
    Map<String, Set<ObjectProvider>> opsByTable = new HashMap();
    for (int i = 0; i < ops.length; i++) {
        AbstractClassMetaData cmd = ops[i].getClassMetaData();
        if (!cmd.pkIsDatastoreAttributed(storeMgr)) {
            String tableName = storeMgr.getNamingFactory().getTableName(cmd);
            Set<ObjectProvider> opsForTable = opsByTable.get(tableName);
            if (opsForTable == null) {
                opsForTable = new HashSet<ObjectProvider>();
                opsByTable.put(tableName, opsForTable);
            }
            opsForTable.add(ops[i]);
        }
    }

    for (String tableName : opsByTable.keySet()) {
        Set<ObjectProvider> opsForTable = opsByTable.get(tableName);
        ExecutionContext ec = ops[0].getExecutionContext();
        ManagedConnection mconn = storeMgr.getConnection(ec);
        try {
            DB db = (DB) mconn.getConnection();
            long startTime = System.currentTimeMillis();

            DBCollection collection = db.getCollection(tableName);
            DBObject[] dbObjects = new DBObject[opsForTable.size()];
            int i = 0;
            for (ObjectProvider op : opsForTable) {
                assertReadOnlyForUpdateOfObject(op);
                AbstractClassMetaData cmd = op.getClassMetaData();
                if (!storeMgr.managesClass(cmd.getFullClassName())) {
                    // Make sure schema exists (using this connection)
                    ((MongoDBStoreManager) storeMgr).addClasses(new String[] { cmd.getFullClassName() },
                            op.getExecutionContext().getClassLoaderResolver(), db);
                }

                if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled()) {
                    NucleusLogger.DATASTORE_PERSIST.debug(LOCALISER_MONGODB.msg("MongoDB.Insert.Start",
                            op.getObjectAsPrintable(), op.getInternalObjectId()));
                }

                dbObjects[i] = getDBObjectForObjectProviderToInsert(op, true);

                if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled()) {
                    NucleusLogger.DATASTORE_PERSIST
                            .debug(LOCALISER_MONGODB.msg("MongoDB.Insert.ObjectPersisted",
                                    op.getObjectAsPrintable(), op.getInternalObjectId()));
                }

                i++;
            }

            if (NucleusLogger.DATASTORE_NATIVE.isDebugEnabled()) {
                NucleusLogger.DATASTORE_NATIVE
                        .debug("Persisting objects as " + StringUtils.objectArrayToString(dbObjects));
            }
            collection.insert(dbObjects, new WriteConcern(1));
            if (ec.getStatistics() != null) {
                ec.getStatistics().incrementNumWrites();
                for (int j = 0; j < dbObjects.length; j++) {
                    ec.getStatistics().incrementInsertCount();
                }
            }

            if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled()) {
                NucleusLogger.DATASTORE_PERSIST.debug(LOCALISER_MONGODB.msg("MongoDB.ExecutionTime",
                        (System.currentTimeMillis() - startTime)));
            }
        } catch (MongoException me) {
            NucleusLogger.PERSISTENCE.error("Exception inserting objects", me);
            throw new NucleusDataStoreException("Exception inserting objects", me);
        } finally {
            mconn.release();
        }
    }
}

From source file:org.datanucleus.store.mongodb.MongoDBPersistenceHandler.java

License:Open Source License

public void insertObject(ObjectProvider op) {
    assertReadOnlyForUpdateOfObject(op);

    ExecutionContext ec = op.getExecutionContext();
    ManagedConnection mconn = storeMgr.getConnection(ec);
    try {//from w ww.  ja v  a 2s.co m
        DB db = (DB) mconn.getConnection();

        AbstractClassMetaData cmd = op.getClassMetaData();
        if (!storeMgr.managesClass(cmd.getFullClassName())) {
            // Make sure schema exists, using this connection
            ((MongoDBStoreManager) storeMgr).addClasses(new String[] { cmd.getFullClassName() },
                    ec.getClassLoaderResolver(), db);
        }

        long startTime = System.currentTimeMillis();
        if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled()) {
            NucleusLogger.DATASTORE_PERSIST.debug(LOCALISER_MONGODB.msg("MongoDB.Insert.Start",
                    op.getObjectAsPrintable(), op.getInternalObjectId()));
        }

        DBCollection collection = db.getCollection(storeMgr.getNamingFactory().getTableName(cmd));
        DBObject dbObject = getDBObjectForObjectProviderToInsert(op, !cmd.pkIsDatastoreAttributed(storeMgr));

        NucleusLogger.DATASTORE_NATIVE.debug("Persisting object " + op + " as " + dbObject);
        collection.insert(dbObject, new WriteConcern(1));
        if (ec.getStatistics() != null) {
            ec.getStatistics().incrementNumWrites();
        }

        if (cmd.pkIsDatastoreAttributed(storeMgr)) {
            // Set the identity of the object based on the datastore-generated IDENTITY strategy value
            if (cmd.getIdentityType() == IdentityType.DATASTORE) {
                // Set identity from MongoDB "_id" field
                ObjectId idKey = (ObjectId) dbObject.get("_id");
                op.setPostStoreNewObjectId(idKey.toString());
                if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled()) {
                    NucleusLogger.DATASTORE_PERSIST.debug(LOCALISER_MONGODB.msg(
                            "MongoDB.Insert.ObjectPersistedWithIdentity", op.getObjectAsPrintable(), idKey));
                }
            } else if (cmd.getIdentityType() == IdentityType.APPLICATION) {
                int[] pkFieldNumbers = cmd.getPKMemberPositions();
                for (int i = 0; i < pkFieldNumbers.length; i++) {
                    AbstractMemberMetaData mmd = cmd
                            .getMetaDataForManagedMemberAtAbsolutePosition(pkFieldNumbers[i]);
                    if (storeMgr.isStrategyDatastoreAttributed(cmd, pkFieldNumbers[i])) {
                        if (mmd.getType() != String.class) {
                            // Field type must be String since MongoDB "_id" is a hex String.
                            throw new NucleusUserException(
                                    "Any field using IDENTITY value generation with MongoDB should be of type String");
                        }
                        ObjectId idKey = (ObjectId) dbObject.get("_id");
                        op.replaceField(mmd.getAbsoluteFieldNumber(), idKey.toString());
                        op.setPostStoreNewObjectId(idKey); // TODO This is incorrect if part of a composite PK
                        if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled()) {
                            NucleusLogger.DATASTORE_PERSIST
                                    .debug(LOCALISER_MONGODB.msg("MongoDB.Insert.ObjectPersistedWithIdentity",
                                            op.getObjectAsPrintable(), idKey));
                        }
                    }
                }
            }

            // Update any relation fields
            StoreFieldManager fieldManager = new StoreFieldManager(op, dbObject, true);
            int[] fieldNumbers = cmd.getRelationMemberPositions(ec.getClassLoaderResolver(),
                    ec.getMetaDataManager());
            if (fieldNumbers != null && fieldNumbers.length > 0) {
                op.provideFields(fieldNumbers, fieldManager);
                NucleusLogger.DATASTORE_NATIVE.debug("Saving object " + op + " as " + dbObject);
                collection.save(dbObject);
                if (ec.getStatistics() != null) {
                    ec.getStatistics().incrementNumWrites();
                }
            }
        } else {
            if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled()) {
                NucleusLogger.DATASTORE_PERSIST.debug(LOCALISER_MONGODB.msg("MongoDB.Insert.ObjectPersisted",
                        op.getObjectAsPrintable(), op.getInternalObjectId()));
            }
        }

        if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled()) {
            NucleusLogger.DATASTORE_PERSIST.debug(
                    LOCALISER_MONGODB.msg("MongoDB.ExecutionTime", (System.currentTimeMillis() - startTime)));
        }
        if (ec.getStatistics() != null) {
            ec.getStatistics().incrementInsertCount();
        }
    } catch (MongoException me) {
        NucleusLogger.PERSISTENCE.error("Exception inserting object " + op, me);
        throw new NucleusDataStoreException("Exception inserting object for " + op, me);
    } finally {
        mconn.release();
    }
}

From source file:org.infinispan.loaders.mongodb.MongoDBCacheStore.java

License:Open Source License

@Override
public void start() throws CacheLoaderException {
    super.start();
    try {/*from  w  w w.  jav a 2s .  co  m*/
        MongoClientOptions.Builder optionBuilder = new MongoClientOptions.Builder();
        optionBuilder.connectTimeout(this.cfg.getTimeout());

        WriteConcern writeConcern = new WriteConcern(this.cfg.getAcknowledgment());
        optionBuilder.writeConcern(writeConcern);

        log.connectingToMongo(this.cfg.getHost(), this.cfg.getPort(), this.cfg.getTimeout(),
                this.cfg.getAcknowledgment());

        ServerAddress serverAddress = new ServerAddress(this.cfg.getHost(), this.cfg.getPort());

        this.mongo = new MongoClient(serverAddress, optionBuilder.build());
    } catch (UnknownHostException e) {
        throw log.mongoOnUnknownHost(this.cfg.getHost());
    } catch (RuntimeException e) {
        throw log.unableToInitializeMongoDB(e);
    }
    mongoDb = extractDatabase();
    this.collection = mongoDb.getCollection(this.cfg.getCollectionName());

}

From source file:org.socialhistoryservices.dao.MongoDBSingleton.java

License:Open Source License

public MongoDBSingleton(String[] hosts, int connectionsPerHost, int writeConcern) {
    final MongoClientOptions.Builder builder = new MongoClientOptions.Builder()
            .connectionsPerHost(connectionsPerHost).writeConcern(new WriteConcern(writeConcern));
    setMongo(hosts, builder.build());/*from ww  w.j av a 2s  .  com*/
}

From source file:org.springframework.data.mongodb.config.StringToWriteConcernConverter.java

License:Apache License

public WriteConcern convert(String source) {

    WriteConcern writeConcern = WriteConcern.valueOf(source);
    return writeConcern != null ? writeConcern : new WriteConcern(source);
}

From source file:org.springframework.data.mongodb.config.WriteConcernPropertyEditor.java

License:Apache License

/**
 * Parse a string to a List<ServerAddress>
 *//*from w ww .  j av a 2 s  .c o m*/
@Override
public void setAsText(String writeConcernString) {

    WriteConcern writeConcern = WriteConcern.valueOf(writeConcernString);
    if (writeConcern != null) {
        // have a well known string
        setValue(writeConcern);
    } else {
        // pass on the string to the constructor
        setValue(new WriteConcern(writeConcernString));
    }

}