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:com.stratio.ingestion.source.rest.url.filter.MongoFilterHandler.java

License:Apache License

protected void initMongo(String mongoUri) {
    try {/*from w  w  w .  ja  va  2s .com*/
        this.mongoClientURI = new MongoClientURI(mongoUri,
                MongoClientOptions.builder().writeConcern(WriteConcern.SAFE));
        this.mongoClient = new MongoClient(mongoClientURI);
        this.mongoDb = mongoClient
                .getDB(checkNotNull(mongoClientURI.getDatabase(), "Non-null database expected"));
        this.mongoCollection = mongoDb.getCollection(
                checkNotNull(mongoClientURI.getCollection(), "Non-null " + "collection expected"));
    } catch (UnknownHostException e) {
        throw new MongoFilterException("mongo host could not be reached", e);
    } catch (IllegalArgumentException e) {
        throw new MongoFilterException("Valid mongo uri expected.", e);
    } catch (NullPointerException e) {
        throw new MongoFilterException("Non-null db/collection expected", e);
    }
}

From source file:com.teamj.distribuidas.ebanking.persistence.PersistenceManager.java

public PersistenceManager() {
    MongoClientOptions mongoOptions = MongoClientOptions.builder().socketTimeout(60000).connectTimeout(60000)
            .build();//from w  w w .  ja  va 2 s  .co m

    try {

        mongoClient = new MongoClient(new ServerAddress("localhost"), mongoOptions);

    } catch (Exception e) {

        throw new RuntimeException("Error", e);
    }

    mongoClient.setWriteConcern(WriteConcern.SAFE);
    morphia = new Morphia();

    morphia.mapPackage(DB_PACKAGE, true);
    mds = morphia.createDatastore(mongoClient, DB_NAME);
    mds.ensureIndexes();
}

From source file:com.trenako.web.config.ApplicationConfig.java

License:Apache License

/**
 * Returns a {@code MongoTemplate} instance.
 *
 * @return the MongoDB template bean/*from  w w  w .  j av  a 2s. c om*/
 * @throws Exception
 */
@Bean
public MongoTemplate mongoTemplate() throws Exception {
    MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory());
    mongoTemplate.setWriteConcern(WriteConcern.SAFE);
    return mongoTemplate;
}

From source file:com.tristrambrasil.ladder.social.canvas.config.SocialConfig.java

License:Apache License

public @Bean MongoTemplate mongoTemplate() throws Exception {
    MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory());
    mongoTemplate.setWriteConcern(WriteConcern.SAFE);
    return mongoTemplate;
}

From source file:de.belaso.mongolyn.ui.TaskDataHandler.java

License:Open Source License

@Override
public RepositoryResponse postTaskData(TaskRepository repository, TaskData taskData,
        Set<TaskAttribute> oldAttributes, IProgressMonitor monitor) throws CoreException {
    DBCollection dbCollection = MongolynUtils.getDBCollection(repository);
    BasicDBObjectBuilder bob = BasicDBObjectBuilder.start();
    for (Map.Entry<String, TaskAttribute> entry : taskData.getRoot().getAttributes().entrySet()) {
        String key = entry.getKey();
        TaskAttribute attribute = entry.getValue();
        String attributeValue = attribute.getValue();
        if (attributeValue != null) {
            bob.add(key.replace('.', '_'), attributeValue);
        }/* w  ww  . j av a2s .com*/
    }
    DBObject dbObject = bob.get();
    try {
        if (taskData.isNew()) {
            dbCollection.insert(dbObject, WriteConcern.SAFE);
            return new RepositoryResponse(ResponseKind.TASK_CREATED, dbObject.get("_id").toString());
        } else {
            dbCollection.findAndModify(new BasicDBObject("_id", new ObjectId(taskData.getTaskId())), dbObject);
            return new RepositoryResponse(ResponseKind.TASK_UPDATED, taskData.getTaskId());
        }
    } catch (MongoException mongoException) {
        throw new CoreException(Activator.INSTANCE.getErrorStatus(mongoException));
    }
}

From source file:de.uni_koeln.spinfo.maalr.mongo.core.Database.java

License:Apache License

public void delete(LexEntry entry) throws InvalidEntryException {
    if (entry == null || entry.getId() == null) {
        throw new InvalidEntryException("Cannot delete entry without id!");
    }//from   w  ww  .j a v  a  2s  .  com
    BasicDBObject object = new BasicDBObject();
    object.put("_id", new ObjectId(entry.getId()));
    WriteResult result = entryCollection.remove(object, WriteConcern.SAFE);
    operationResult(result);
    logger.info("DELETED: " + toLogString(entry.getCurrent()) + ", entry " + entry.getId());
}

From source file:dk.au.cs.karibu.backend.mongo.MongoDBStorage.java

License:Apache License

private void createConnection(MongoConfiguration conf) {

    String databaseName = conf.getDatabaseName();
    List<ServerAddress> addr = conf.getServerAddressList();

    // connect to the database server 
    mongoDB = null;/*from   w ww . j  a v a  2  s .com*/
    try {
        mongoDB = new MongoClient(addr);
    } catch (MongoException e) {
        String theTrace = ExceptionUtils.getStackTrace(e);
        log.error("MongoException. " + theTrace);
        System.exit(-1);
    }
    // get handle to the required database 
    database = mongoDB.getDB(databaseName);
    // authenticate in case there is a username in the config
    if (conf.getUsername() != null) {
        boolean auth = database.authenticate(conf.getUsername(), conf.getPassword().toCharArray());
        if (!auth) {
            log.error("Mongo authentication failed for username: " + conf.getUsername() + " on DB: "
                    + conf.getDatabaseName());
            System.out.println("MongoDB authentication failed. Review log.");
            // Fail fast!
            System.exit(-1);
        }
    }

    // From javadoc:  
    // By default, all read and write operations will be made on the primary,  
    // but it's possible to read from secondaries by changing the read preference 
    mongoDB.setReadPreference(ReadPreference.secondaryPreferred());

    // From javadoc: Exceptions are raised for network issues, and server errors;  
    // waits on a server for the write operation 
    mongoDB.setWriteConcern(WriteConcern.SAFE);

    log.info("MongoDB connected...");

    // Register a shutdown hook to close the mongo  
    // connection 
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            log.info("MongoDB disconnected...");
            mongoDB.close();
        }
    });

}

From source file:ec.edu.espe.persistence.PersistenceManager.java

public PersistenceManager() {
    MongoClientOptions mongoOptions = MongoClientOptions.builder().socketTimeout(60000).connectTimeout(60000)
            .build();/*from ww  w.  j  a v  a  2  s. co m*/

    try {

        //mongoClient = new MongoClient(new ServerAddress("ds038739.mlab.com:38739"), mongoOptions);
        String textUri = "mongodb://xmatch:xmatch@ds038739.mlab.com:38739/xmatch";
        MongoClientURI uri = new MongoClientURI(textUri);
        mongoClient = new MongoClient(uri);
    } catch (Exception e) {

        throw new RuntimeException("Error", e);
    }

    mongoClient.setWriteConcern(WriteConcern.SAFE);
    mongoClient.setReadPreference(ReadPreference.primary());
    morphia = new Morphia();

    morphia.mapPackage(DB_PACKAGE, true);
    mds = morphia.createDatastore(mongoClient, DB_NAME);
    mds.ensureIndexes();
}

From source file:fr.eolya.utils.nosql.mongodb.MongoDBConnection.java

License:Apache License

/**
 * @param hostName         The MongoDB server host name
 * @param hostPort         The MongoDB server host port
 * @return/* w w  w.  ja  v a 2 s  .  c  o m*/
 * @throws UnknownHostException 
 */
public MongoDBConnection(String hostName, int hostPort, String userName, String userPassword)
        throws UnknownHostException {

    MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
    builder.autoConnectRetry(true);
    builder.socketKeepAlive(true);
    builder.writeConcern(WriteConcern.SAFE);

    if ("".equals(hostName))
        hostName = "localhost";
    if (hostPort > 0) {
        ServerAddress addr = new ServerAddress(hostName, hostPort);
        m = new MongoClient(addr, builder.build());
    } else {
        m = new MongoClient(hostName, builder.build());
    }
    this.hostName = hostName;
    this.hostPort = hostPort;
}

From source file:fr.eolya.utils.nosql.mongodb.MongoDBDatabase.java

License:Apache License

/**
 * @param con              The MongoDB connection
 * @param dbName           The MongoDB db name
 * @return//www .j av  a2 s  .  co m
 * @throws UnknownHostException 
 */
public MongoDBDatabase(MongoDBConnection con, String dbName) {
    db = con.getMongo().getDB(dbName);
    db.setWriteConcern(WriteConcern.SAFE);
    this.dbName = dbName;
}