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:me.philnate.textmanager.entities.Setting.java

License:Open Source License

@Override
public void delete() {
    ds.delete(this, WriteConcern.SAFE);
}

From source file:models.datasource.SingletonDataSource.java

public static User insertIntoUsersCollection(User user) {
    // Get the collection (connection to our mongo database)
    DBCollection collection = connectDB("mongo.usersCollection");

    // Create the query
    BasicDBObject query = new BasicDBObject().append(Constants.USER_NAME, user.name)
            .append(Constants.USER_SURNAMES, user.surnames).append(Constants.USER_EMAIL, user.email)
            .append(Constants.USER_PASSWORD, Utils.encryptWithSHA1(user.password))
            .append(Constants.USER_EMAIL_VERIFICATION_KEY, user.emailVerificationKey)
            .append(Constants.USER_CONNECTION_TIMESTAMP, user.connectionTimestamp)
            .append(Constants.USER_RESTORE_PASSWORD_TOKEN, user.restorePasswordToken)
            .append(Constants.USER_RESTORE_PASSWORD_TIMESTAMP, user.restorePasswordTimestamp)
            .append(Constants.USER_REGISTRATION_DATE, user.registrationDate)
            .append(Constants.USER_BIRTH_DATE, user.birthDate)
            .append(Constants.USER_RESIDENCE_CITY, user.residenceCity)
            .append(Constants.USER_RESIDENCE_ADDRESS, user.residenceAddress)
            .append(Constants.USER_RESIDENCE_NUMBER, user.residenceNumber)
            .append(Constants.USER_RESIDENCE_ZIP_CODE, user.residenceZipCode)
            .append(Constants.USER_PHONE_NUMBER, user.phoneNumber)
            .append(Constants.USER_STUDY_TITLE, user.studyTitle)
            .append(Constants.USER_STUDY_LOCATION, user.studyLocation)
            .append(Constants.USER_EDUCATION_LEVEL, user.educationLevel)
            .append(Constants.USER_DRIVING_LICENSE, user.drivingLicense)
            .append(Constants.USER_CERTIFICATE_OF_DISABILITY, user.certificateOfDisability)
            .append(Constants.USER_COURSES, JSON.parse(user.coursesToJson()))
            .append(Constants.USER_LANGUAGES, JSON.parse(user.languagesToJson()))
            .append(Constants.USER_SOFTWARE, JSON.parse(user.softwareToJson()))
            .append(Constants.USER_ORIENTATION_STEPS,
                    JSON.parse(user.completedOrientationSteps.orientationStepsToJson()))
            .append(Constants.USER_CURRENT_SITUATION, JSON.parse(user.currentSituation.toJsonString()))
            .append(Constants.USER_SKILLS_LIST, JSON.parse(user.skillsToJson()))
            .append(Constants.USER_INTERESTS_LIST, user.interests)
            .append(Constants.USER_PERSONAL_CHARACTERISTICS_LIST, user.personalCharacteristics)
            .append(Constants.USER_PROFESSIONAL_VALUES_LIST, JSON.parse(user.professionalValuesToJson()))
            .append(Constants.USER_PHOTO, JSON.parse(user.photo.toJsonString()))
            .append(Constants.USER_NEXT_INTERVIEWS_LIST, JSON.parse(user.interviewScheduleListToJson()));
    collection.insert(WriteConcern.SAFE, query);

    // Close connection
    mongoClient.close();/*from  www.j a  v a2 s.c om*/

    // Returns the new user
    return user;
}

From source file:mongoDB.MongoDbClientAllImagesAsByteArrays.java

License:Open Source License

/**
 * Initialize any state for this DB. Called once per DB instance; there is
 * one DB instance per client thread.//w  w  w.jav a  2s.  c o  m
 */
public boolean init() throws DBException {
    // initialize MongoDb driver
    props = getProperties();
    String url = props.getProperty(MONGODB_URL_PROPERTY);
    database = props.getProperty(MONGODB_DB_PROPERTY);
    String writeConcernType = props.getProperty(MONGODB_WRITE_CONCERN_PROPERTY,
            MONGODB_WRITE_CONCERN_PROPERTY_DEFAULT);
    manipulationArray = Boolean.parseBoolean(props.getProperty(MONGODB_MANIPULATION_ARRAY_PROPERTY,
            MONGODB_MANIPULATION_ARRAY_PROPERTY_DEFAULT));
    friendListReq = Boolean.parseBoolean(
            props.getProperty(MONGODB_FRNDLIST_REQ_PROPERTY, MONGODB_FRNDLIST_REQ_PROPERTY_DEFAULT));
    scanResources = Boolean
            .parseBoolean(props.getProperty(MONGODB_SCANFORRES_PROPERTY, MONGODB_SCANFORRES_PROPERTY_DEFAULT));

    if ("none".equals(writeConcernType)) {
        // don't return error on writes
        writeConcern = WriteConcern.NONE;
    } else if ("strict".equals(writeConcernType)) {
        // The write will wait for a response from the server and raise an
        // exception on any error
        writeConcern = WriteConcern.SAFE;
    } else if ("normal".equals(writeConcernType)) {
        // normal error handling - just raise exceptions when problems, don
        // wait for response form servers
        writeConcern = WriteConcern.NORMAL;
    }

    try {
        // System.out.println("new database url = "+url);
        /*
         * MongoOptions mo = new MongoOptions(); mo.connectionsPerHost =
         * 100; mongo = new Mongo(new DBAddress(url), mo);
         */

        /*
         * List<ServerAddress> addrs = new ArrayList<ServerAddress>();
         * addrs.add( new ServerAddress( "10.0.0.122" , 27017 ) );
         * addrs.add( new ServerAddress( "10.0.0.122" , 10002 ) );
         * addrs.add( new ServerAddress( "10.0.0.120" , 10003 ) );
         * MongoOptions mongoOptions = new MongoOptions(); mongo = new
         * Mongo( addrs, mongoOptions);
         * mongo.setReadPreference(ReadPreference.SECONDARY);
         */
        // System.out.println("mongo connection created with "+url);
        try {
            crtcl.acquire();

            if (NumThreads == null) {
                NumThreads = new AtomicInteger();
                NumThreads.set(0);
                MongoOptions mo = new MongoOptions();
                mo.connectionsPerHost = 100;
                String urls[];
                if (!url.contains(";")) { //multiple mongos servers
                    url += "/" + database;
                    mongo = new Mongo(new DBAddress(url), mo);
                } /*else{ // need to append db to url.
                    urls = url.split(";");
                     List<ServerAddress> addrs = new ArrayList<ServerAddress>();
                     for(int i=0; i< urls.length; i++){
                        addrs.add( new ServerAddress(urls[i].split(":")[0] , Integer.parseInt(urls[i].split(":")[1]) ) );
                        //no need to add the database name here as each action does a mongo.getDB(database)
                     } 
                     mongo = new Mongo( addrs);
                  }*/
                else { // need to append db to url.
                    urls = url.split(";");
                    mo = new MongoOptions();
                    mo.connectionsPerHost = 100;
                    //trying to direct clients to different routers
                    url = urls[(Integer.parseInt(props.getProperty(Client.MACHINE_ID_PROPERTY, "0")))
                            % urls.length];
                    url += "/" + database;
                    mongo = new Mongo(new DBAddress(url), mo);
                }

                //mongo = new MongoClient(new DBAddress(url));
                // checking to see if the connection is established
                try {
                    Socket socket = mongo.getMongoOptions().socketFactory.createSocket();
                    socket.connect(mongo.getAddress().getSocketAddress());
                    socket.close();
                } catch (IOException ex) {
                    System.out.println("ERROR: Can't create connection, check if MongDB is running");
                    return false;
                }
            }
            incrementNumThreads();

        } catch (Exception e) {
            System.out.println("MongoDB init failed to acquire semaphore.");
            e.printStackTrace(System.out);
        } finally {
            crtcl.release();
        }
    } catch (Exception e1) {
        System.out.println("Could not initialize MongoDB connection pool for Loader: " + e1.toString());
        e1.printStackTrace(System.out);
        return false;
    }
    return true;
}

From source file:mongodb1.Mongodb1.java

/**
 * @param args the command line arguments
 *//*from ww  w  .ja v  a  2 s .co m*/
public static void main(String[] args) {

    try { //Connect

        MongoClient mongo = new MongoClient();
        DB db = mongo.getDB("labbd2016");
        System.out.println("Connect to database successfully");

        DBCollection table = db.getCollection("alunos");
        System.out.println("Collection retrieved successfully");

        List<String> dbs = mongo.getDatabaseNames();
        System.out.println(dbs);

        Set<String> collections = db.getCollectionNames();
        System.out.println(collections);
        //Insert
        BasicDBObject document = new BasicDBObject();
        document.put("nome", "Adao");
        document.put("idade", 30);
        table.insert(WriteConcern.SAFE, document);
        for (DBObject doc : table.find()) {
            System.out.println(doc);
        }
        //Find
        BasicDBObject searchQuery = new BasicDBObject();
        searchQuery.put("idade", new BasicDBObject("$gt", 1));
        DBCursor cursor = table.find(searchQuery);
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }
}

From source file:net.bunselmeyer.mongo.maven.plugin.MigrateMojo.java

License:Apache License

private void runMigrations(List<MigrationDetails> migrations) {
    if (migrations.isEmpty()) {
        return;//from  www  .jav  a  2  s .c om
    }

    MigrationDetails migrationDetails = migrations.get(0);

    Mongo mongo;
    try {
        mongo = new Mongo(migrationDetails.host, Integer.parseInt(port));
    } catch (UnknownHostException e) {
        getLog().error("Failed to connect to " + migrationDetails.host + ":" + port);
        return;
    } catch (NumberFormatException e) {
        getLog().error("Invalid port: " + port);
        return;
    }

    mongo.setWriteConcern(WriteConcern.SAFE);

    DB db = mongo.getDB(migrationDetails.db);

    JacksonDBCollection<MigrationVersionDetails, ObjectId> migrationVersionCollection = createMigrationVersionCollection(
            db);

    getLog().info("Running migrations. Host: " + migrationDetails.host + ". DB: " + migrationDetails.db);

    sortMigrationDetails(migrations);

    Class<? extends Migration> lastMigration = null;
    try {
        for (MigrationDetails details : migrations) {
            lastMigration = details.migration;
            Migration m = details.migration.newInstance();

            MigrationVersionDetails versionDetails = new MigrationVersionDetails();
            versionDetails.setMigrationName(details.migration.getName());
            versionDetails.setVersion(details.version);

            if (migrationVersionCollection.getCount(versionDetails) == 0) {
                m.up(db);
                db.getLastError().throwOnError();
                getLog().info(
                        "    " + details.migration.getName() + ", v" + details.version + " migration complete");
                versionDetails.setRun(DateTime.now(DateTimeZone.UTC));
                migrationVersionCollection.insert(versionDetails);
            } else {
                getLog().info(
                        "    " + details.migration.getName() + ", v" + details.version + " was already run");
            }
        }
    } catch (Exception e) {
        String name = lastMigration != null ? lastMigration.getName() : "";
        getLog().info("    FAIL! " + name + " migration error", e);
    } finally {
        mongo.close();
    }
}

From source file:org.alfresco.bm.cm.FileFolderService.java

License:Open Source License

/**
 * Ensure that the MongoDB collection has the required indexes associated with
 * this user bean./*from   ww w  .  j av a  2s  .  co m*/
 */
private void checkIndexes() {
    collection.setWriteConcern(WriteConcern.SAFE);

    DBObject uidxCtxPath = BasicDBObjectBuilder.start().add(FIELD_CONTEXT, 1).add(FIELD_PATH, 1).get();
    DBObject optCtxPath = BasicDBObjectBuilder.start().add("name", "uidxCtxPath").add("unique", Boolean.TRUE)
            .get();
    collection.createIndex(uidxCtxPath, optCtxPath);

    DBObject uidxCtxParentName = BasicDBObjectBuilder.start().add(FIELD_CONTEXT, 1).add(FIELD_PARENT_PATH, 1)
            .add(FIELD_NAME, 1).get();
    DBObject optCtxParentName = BasicDBObjectBuilder.start().add("name", "uidxCtxParentName")
            .add("unique", Boolean.FALSE).get();
    collection.createIndex(uidxCtxParentName, optCtxParentName);

    DBObject idxCtxLevel = BasicDBObjectBuilder.start().add(FIELD_CONTEXT, 1).add(FIELD_LEVEL, 1).get();
    DBObject optCtxLevel = BasicDBObjectBuilder.start().add("name", "idxCtxLevel").add("unique", Boolean.FALSE)
            .get();
    collection.createIndex(idxCtxLevel, optCtxLevel);

    DBObject idxCtxFileCount = BasicDBObjectBuilder.start().add(FIELD_CONTEXT, 1).add(FIELD_FILE_COUNT, 1)
            .add(FIELD_LEVEL, 1).get();
    DBObject optCtxFileCount = BasicDBObjectBuilder.start().add("name", "idxCtxFileCount")
            .add("unique", Boolean.FALSE).get();
    collection.createIndex(idxCtxFileCount, optCtxFileCount);

    DBObject idxCtxFolderCount = BasicDBObjectBuilder.start().add(FIELD_CONTEXT, 1).add(FIELD_FOLDER_COUNT, 1)
            .add(FIELD_LEVEL, 1).get();
    DBObject optCtxFolderCount = BasicDBObjectBuilder.start().add("name", "idxCtxFolderCount")
            .add("unique", Boolean.FALSE).get();
    collection.createIndex(idxCtxFolderCount, optCtxFolderCount);
}

From source file:org.alfresco.bm.devicesync.dao.mongo.MongoMetricsService.java

License:Open Source License

/**
 * Ensure that the MongoDB collection has the required indexes associated
 * with this user bean.
 */
private void checkIndexes() {
    collection.setWriteConcern(WriteConcern.SAFE);
}

From source file:org.alfresco.bm.file.FileDataServiceImpl.java

License:Open Source License

/**
 * Ensure that the MongoDB collection has the required indexes associated with
 * this user bean.//from  w w  w  . j a v a  2s  . co  m
 */
private void checkIndexes() {
    collection.setWriteConcern(WriteConcern.SAFE);

    DBObject idxRandomizer = BasicDBObjectBuilder.start(FIELD_FILESET, 1).add(FIELD_RANDOMIZER, 1).get();
    DBObject optRandomizer = BasicDBObjectBuilder.start("name", "idx_randomizer").add("unique", Boolean.FALSE)
            .get();
    collection.createIndex(idxRandomizer, optRandomizer);

    DBObject idxExtension = BasicDBObjectBuilder.start(FIELD_FILESET, 1).add(FIELD_EXTENSION, 1)
            .add(FIELD_RANDOMIZER, 1).get();
    DBObject optExtension = BasicDBObjectBuilder.start("name", "idx_extension").add("unique", Boolean.FALSE)
            .get();
    collection.createIndex(idxExtension, optExtension);

    DBObject uidxRemoteName = BasicDBObjectBuilder.start(FIELD_FILESET, 1).add(FIELD_REMOTE_NAME, 1).get();
    DBObject optRemoteName = BasicDBObjectBuilder.start("name", "uidx_remoteName").add("unique", Boolean.TRUE)
            .get();
    collection.createIndex(uidxRemoteName, optRemoteName);

    DBObject uidxLocalName = BasicDBObjectBuilder.start(FIELD_FILESET, 1).add(FIELD_LOCAL_NAME, 1).get();
    DBObject optLocalName = BasicDBObjectBuilder.start("name", "uidx_localName").add("unique", Boolean.TRUE)
            .get();
    collection.createIndex(uidxLocalName, optLocalName);
}

From source file:org.alfresco.bm.session.MongoSessionService.java

License:Open Source License

/**
 * Ensure that the MongoDB collection has the required indexes
 *//*from www .  jav a2s  .c o  m*/
private void checkIndexes() {
    collection.setWriteConcern(WriteConcern.SAFE);

    // Ensure unique session ID
    // This is guaranteed by MongoDB

    // Ensure ordering by start time
    DBObject idxSessionIdStartTime = BasicDBObjectBuilder.start(FIELD_START_TIME, 1).get();
    DBObject optSessionIdStartTime = BasicDBObjectBuilder.start("name", "idxSessionIdStartTime")
            .add("unique", Boolean.FALSE).get();
    collection.createIndex(idxSessionIdStartTime, optSessionIdStartTime);

    // Find unfinished sessions
    DBObject idxEndTimeStartTime = BasicDBObjectBuilder.start(FIELD_END_TIME, 1).add(FIELD_START_TIME, 1).get();
    DBObject optEndTimeStartTime = BasicDBObjectBuilder.start("name", "idxEndTimeStartTime")
            .add("unique", Boolean.FALSE).get();
    collection.createIndex(idxEndTimeStartTime, optEndTimeStartTime);
}

From source file:org.alfresco.bm.test.mongo.MongoTestDAO.java

License:Open Source License

/**
 * Record a final set of locked properties for a test run. The properties
 * written will not be updatable./*  w  ww  .  j  a v a2s  .  c o m*/
 * 
 * @param testObjId
 *        the ID of the test
 * @param runObjId
 *        the ID of the test run
 * 
 * @throws ObjectNotFoundException
 */
public void lockProperties(ObjectId testObjId, ObjectId runObjId) throws ObjectNotFoundException {
    // Get all the test run overrides
    DBObject runObj = getTestRun(runObjId, true);
    BasicDBList propObjs = (BasicDBList) runObj.get(FIELD_PROPERTIES);

    // First remove all current property overrides for the run
    DBObject propDelObj = BasicDBObjectBuilder.start().add(FIELD_TEST, testObjId).add(FIELD_RUN, runObjId)
            .get();
    testProps.remove(propDelObj);

    // Now add them all back
    int version = Short.MAX_VALUE + 1; // This puts it out of
                                       // the normal range of
                                       // editing
    List<DBObject> insertObjList = new ArrayList<DBObject>(propObjs.size());
    for (Object obj : propObjs) {
        DBObject propObj = (DBObject) obj;
        String propName = (String) propObj.get(FIELD_NAME);
        String propOrigin = (String) propObj.get(FIELD_ORIGIN);
        Object defValue = propObj.get(FIELD_DEFAULT);
        Object value = propObj.get(FIELD_VALUE);
        if (value == null) {
            // We override ALL values
            value = defValue;
        }

        DBObject insertObj = BasicDBObjectBuilder.start().add(FIELD_TEST, testObjId).add(FIELD_RUN, runObjId)
                .add(FIELD_NAME, propName).add(FIELD_VERSION, Integer.valueOf(version))
                .add(FIELD_ORIGIN, propOrigin).add(FIELD_VALUE, value).get();
        insertObjList.add(insertObj);
    }

    // Do the bulk insert
    try {
        testProps.insert(insertObjList, WriteConcern.SAFE);
    } catch (MongoException e) {
        StringBuilder sb = new StringBuilder();
        sb.append("Lost test run property overrides: \n" + "   Error: " + e.getMessage() + "\n" + "   Props:");
        for (Object propObj : propObjs) {
            sb.append("\n").append("      ").append(propObj);
        }
        String msg = sb.toString();
        logger.error(msg);
        throw new RuntimeException(msg, e);
    }
    // Done
    if (logger.isDebugEnabled()) {
        logger.debug("Successfully fixed property overrides for run: " + runObjId);
    }
}