Example usage for com.mongodb WriteConcern ACKNOWLEDGED

List of usage examples for com.mongodb WriteConcern ACKNOWLEDGED

Introduction

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

Prototype

WriteConcern ACKNOWLEDGED

To view the source code for com.mongodb WriteConcern ACKNOWLEDGED.

Click Source Link

Document

Write operations that use this write concern will wait for acknowledgement, using the default write concern configured on the server.

Usage

From source file:com.picdrop.guice.RepositoryModule.java

@Override
protected MorphiaRepository<Comment> provideCommentRepo() {
    return MorphiaRepository.Builder.forType(Comment.class).withWriteConcern(WriteConcern.ACKNOWLEDGED)
            .withDatastore(null).build();
}

From source file:com.picdrop.guice.RepositoryModule.java

@Override
protected MorphiaRepository<Rating> provideRatingRepo() {
    return MorphiaRepository.Builder.forType(Rating.class).withWriteConcern(WriteConcern.ACKNOWLEDGED)
            .withDatastore(null).build();
}

From source file:com.ptoceti.mongo.geoname.GeoNameCollection.java

License:Open Source License

public boolean insertLocation(GeoNameLoc location) {

    WriteResult result = geonames.insert(location, WriteConcern.ACKNOWLEDGED);
    return result.getLastError(WriteConcern.ACKNOWLEDGED).ok();
}

From source file:com.redhat.lightblue.mongo.crud.MongoLocking.java

License:Open Source License

/**
 * Attempts to insert a lock record to the db
 *
 * @returns true if successful, false if lock already exists. Any other case
 * would be an exception./*  w  w  w. j  a va 2  s . co m*/
 */
private boolean acquire(String callerId, String resourceId, Long ttl, Date now, Date expiration) {
    BasicDBObject update = new BasicDBObject().append(CALLERID, callerId).append(RESOURCEID, resourceId)
            .append(TIMESTAMP, now).append(TTL, ttl).append(EXPIRATION, expiration).append(COUNT, 1)
            .append(VERSION, 1);

    try {
        LOGGER.debug("insert: {}", update);
        coll.insert(update, WriteConcern.ACKNOWLEDGED);
    } catch (DuplicateKeyException dke) {
        return false;
    }
    return true;
}

From source file:com.redhat.lightblue.mongo.crud.MongoLocking.java

License:Open Source License

/**
 * Attempt to acquire a lock. If successful, return true, otherwise return
 * false.//from w  ww .  ja va  2 s  .c o m
 */
public boolean acquire(String callerId, String resourceId, Long ttl) {
    /*
      Creating an atomic acquire() method in mongodb is not
      easy. The key is to use the uniqueness of a unique index, in
      this case, a unique index on resourceId. There can be at
      most one lock record for a resource in the db at any given
      time.
            
      The insertion operation is atomic: if it is successful, we
      acquire the lock. We assume the update operation is
      transactional: once a document is found to be matching to
      the query of the update operation, it is locked, and no
      other caller can modify that document until our update
      operation is complete.
            
      We will use a version number to make sure we are updating
      the correct doc.
     */
    LOGGER.debug("acquire({}/{},ttl={})", callerId, resourceId, ttl);
    // Try to insert doc
    Date now = new Date();
    Date expiration;
    if (ttl == null) {
        ttl = defaultTTL;
    }
    expiration = new Date(now.getTime() + ttl);
    LOGGER.debug("{}/{}: lock will expire on {}", callerId, resourceId, expiration);
    BasicDBObject query;
    BasicDBObject update;
    WriteResult wr;
    int readVer = -1;
    String readCallerId = null;
    int readCount = -1;
    boolean locked = acquire(callerId, resourceId, ttl, now, expiration);
    if (!locked) {
        // At this point, we can add "if expired" predicate to the
        // queries to filter expired locks, but it is not safe to
        // rely on timestamps. Not all nodes have the same
        // timestamp, and any node can wait an arbitrary amount of
        // time at any point. So, we read the existing lock at
        // this point, and use the version number for all the
        // updates. if anybody updates the lock before we do, the
        // version number will change, and we will fail.
        query = new BasicDBObject(RESOURCEID, resourceId);
        LOGGER.debug("find: {}", query);
        DBObject lockObject = coll.findOne(query, null, ReadPreference.primary());
        if (lockObject == null) {
            LOGGER.debug("{}/{}: lock cannot be read. Retrying to acquire", callerId, resourceId);
            locked = acquire(callerId, resourceId, ttl, now, expiration);
            LOGGER.debug("{}/{}: acquire result: {}", callerId, resourceId, locked);
            // No need to continue here. If insertion fails, that means someone else inserted a record
            return locked;
        }
        readVer = ((Number) lockObject.get(VERSION)).intValue();
        readCallerId = (String) lockObject.get(CALLERID);
        readCount = ((Number) lockObject.get(COUNT)).intValue();

        // Lock already exists
        // Possibilities:
        //  - lock is not expired, but ours : increment count
        //  - lock is not expired, but someone else owns it : fail
        //  - lock is expired : attempt to acquire
        //  - lock count is less than 1 : attempt to acquire
        // lock is not expired and we own it: increment lock count
        LOGGER.debug("{}/{} locked, assuming lock is ours, attempting to increment lock count", callerId,
                resourceId);
        if (readCallerId.equals(callerId)) {
            query = new BasicDBObject().append(CALLERID, callerId).append(RESOURCEID, resourceId)
                    .append(EXPIRATION, new BasicDBObject("$gt", now)).append(VERSION, readVer);
            update = new BasicDBObject()
                    .append("$set",
                            new BasicDBObject(TIMESTAMP, now).append(EXPIRATION, expiration).append(TTL, ttl))
                    .append("$inc", new BasicDBObject(VERSION, 1).append(COUNT, 1));
            LOGGER.debug("update: {} {}", query, update);
            wr = coll.update(query, update, false, false, WriteConcern.ACKNOWLEDGED);
            if (wr.getN() == 1) {
                LOGGER.debug("{}/{} locked again", callerId, resourceId);
                locked = true;
            }
        }
    }
    if (!locked) {
        // assume lock is expired or count <=0, and try to acquire it
        LOGGER.debug("{}/{} lock is expired or count <= 0, attempting to reacquire expired lock", callerId,
                resourceId);
        query = new BasicDBObject().append(RESOURCEID, resourceId)
                .append("$or",
                        Arrays.asList(new BasicDBObject(EXPIRATION, new BasicDBObject("$lte", now)),
                                new BasicDBObject(COUNT, new BasicDBObject("$lte", 0))))
                .append(VERSION, readVer);
        update = new BasicDBObject()
                .append("$set",
                        new BasicDBObject(CALLERID, callerId).append(TIMESTAMP, now)
                                .append(EXPIRATION, expiration).append(TTL, ttl).append(COUNT, 1))
                .append("$inc", new BasicDBObject(VERSION, 1));
        LOGGER.debug("update: {} {}", query, update);
        wr = coll.update(query, update, false, false, WriteConcern.ACKNOWLEDGED);
        if (wr.getN() == 1) {
            LOGGER.debug("{}/{} locked", callerId, resourceId);
            locked = true;
        }
    }
    LOGGER.debug("{}/{}: {}", callerId, resourceId, locked ? "locked" : "not locked");
    return locked;
}

From source file:com.redhat.lightblue.mongo.crud.MongoLocking.java

License:Open Source License

/**
 * Release the lock. Returns true if the lock is released by this call
 */// w  ww .  jav a  2 s  . c o m
public boolean release(String callerId, String resourceId) {
    LOGGER.debug("release({}/{})", callerId, resourceId);
    Date now = new Date();
    // If lock count is only one, we can remove the lock
    BasicDBObject query = new BasicDBObject().append(CALLERID, callerId).append(RESOURCEID, resourceId)
            .append(EXPIRATION, new BasicDBObject("$gt", now)).append(COUNT, 1);
    LOGGER.debug("remove {}", query);
    WriteResult wr = coll.remove(query, WriteConcern.ACKNOWLEDGED);
    if (wr.getN() == 1) {
        LOGGER.debug("{}/{} released", callerId, resourceId);
        return true;
    }
    // Retrieve the lock
    query = new BasicDBObject(RESOURCEID, resourceId).append(CALLERID, callerId);
    DBObject lock = coll.findOne(query, null, ReadPreference.primary());
    if (lock != null) {
        long ttl = ((Number) lock.get(TTL)).longValue();
        Date expiration = new Date(now.getTime() + ttl);
        int ver = ((Number) lock.get(VERSION)).intValue();
        // Try decrementing the lock count of our lock
        query = new BasicDBObject().append(CALLERID, callerId).append(RESOURCEID, resourceId)
                .append(EXPIRATION, new BasicDBObject("$gt", now)).append(COUNT, new BasicDBObject("$gt", 0))
                .append(VERSION, ver);
        BasicDBObject update = new BasicDBObject()
                .append("$set",
                        new BasicDBObject(EXPIRATION, expiration).append(TTL, ttl).append(TIMESTAMP, now))
                .append("$inc", new BasicDBObject(COUNT, -1).append(VERSION, 1));
        wr = coll.update(query, update, false, false, WriteConcern.ACKNOWLEDGED);
        if (wr.getN() == 1) {
            LOGGER.debug("{}/{} lock count decremented, still locked", callerId, resourceId);
            return false;
        }
    }
    // Both attempts failed, Lock is no longer owned by us
    throw new InvalidLockException(resourceId);
}

From source file:com.redhat.lightblue.mongo.crud.MongoLocking.java

License:Open Source License

public void ping(String callerId, String resourceId) {
    Date now = new Date();
    BasicDBObject q = new BasicDBObject().append(CALLERID, callerId).append(RESOURCEID, resourceId)
            .append(EXPIRATION, new BasicDBObject("$gt", now)).append(COUNT, new BasicDBObject("$gt", 0));
    DBObject lock = coll.findOne(q, null, ReadPreference.primary());
    if (lock != null) {
        Date expiration = new Date(now.getTime() + ((Number) lock.get(TTL)).longValue());
        int ver = ((Number) lock.get(VERSION)).intValue();
        BasicDBObject update = new BasicDBObject()
                .append("$set", new BasicDBObject(TIMESTAMP, now).append(EXPIRATION, expiration))
                .append("$inc", new BasicDBObject(VERSION, 1));
        q = q.append(VERSION, ver);//from w w  w  . j  av  a 2s  . com
        WriteResult wr = coll.update(q, update, false, false, WriteConcern.ACKNOWLEDGED);
        if (wr.getN() != 1) {
            throw new InvalidLockException(resourceId);
        }
        LOGGER.debug("{}/{} pinged", callerId, resourceId);
    } else {
        throw new InvalidLockException(resourceId);
    }
}

From source file:com.redhat.lightblue.mongo.crud.MongoSequenceGenerator.java

License:Open Source License

/**
 * Atomically increments and returns the sequence value. If this is the
 * first use of the sequence, the sequence is created
 *
 * @param name The sequence name// w  w  w  .ja  v  a2 s.  c  om
 * @param init The initial value of the sequence. Used only if the sequence
 * does not exists prior to this call
 * @param inc The increment, Could be negative or positive. If 0, it is
 * assumed to be 1. Used only if the sequence does not exist prior to this
 * call
 *
 * If the sequence already exists, the <code>init</code> and
 * <code>inc</code> are ignored.
 *
 * @return The value of the sequence before the call
 */
public long getNextSequenceValue(String name, long init, long inc) {
    LOGGER.debug("getNextSequenceValue({})", name);
    // Read the sequence document
    BasicDBObject q = new BasicDBObject(NAME, name);
    DBObject doc = coll.findOne(q, null, ReadPreference.primary());
    if (doc == null) {
        // Sequence document does not exist. Insert a new document using the init and inc
        LOGGER.debug("inserting sequence record name={}, init={}, inc={}", name, init, inc);
        if (inc == 0) {
            inc = 1;
        }

        BasicDBObject u = new BasicDBObject().append(NAME, name).append(INIT, init).append(INC, inc)
                .append(VALUE, init);
        try {
            coll.insert(u, WriteConcern.ACKNOWLEDGED);
        } catch (Exception e) {
            // Someone else might have inserted already, try to re-read
            LOGGER.debug("Insertion failed with {}, trying to read", e);
        }
        doc = coll.findOne(q, null, ReadPreference.primary());
        if (doc == null) {
            throw new RuntimeException("Cannot generate value for " + name);
        }
    }
    LOGGER.debug("Sequence doc={}", doc);
    Long increment = (Long) doc.get(INC);
    BasicDBObject u = new BasicDBObject().append("$inc", new BasicDBObject(VALUE, increment));
    // This call returns the unmodified document
    doc = coll.findAndModify(q, u);
    Long l = (Long) doc.get(VALUE);
    LOGGER.debug("{} -> {}", name, l);
    return l;
}

From source file:com.ricardolorenzo.identity.user.impl.UserIdentityManagerMongoDB.java

License:Open Source License

public UserIdentityManagerMongoDB(final Properties conf) throws UnknownHostException {
    this.properties = conf;

    this.databaseUsers = new Boolean(this.properties.getProperty("mongodb.databaseUsers", "true"));

    WriteConcern writeConcern = WriteConcern.MAJORITY;
    String writeConcernType = conf.getProperty("mongodb.writeConcern", "majority").toLowerCase();
    if ("majority".equals(writeConcernType)) {
        writeConcern = WriteConcern.UNACKNOWLEDGED;
    } else if ("unacknowledged".equals(writeConcernType)) {
        writeConcern = WriteConcern.UNACKNOWLEDGED;
    } else if ("acknowledged".equals(writeConcernType)) {
        writeConcern = WriteConcern.ACKNOWLEDGED;
    } else if ("journaled".equals(writeConcernType)) {
        writeConcern = WriteConcern.JOURNALED;
    } else if ("replica_acknowledged".equals(writeConcernType)) {
        writeConcern = WriteConcern.REPLICA_ACKNOWLEDGED;
    }/*ww  w.j a va 2  s .co  m*/

    ReadPreference readPreference = null;
    String readPreferenceType = conf.getProperty("mongodb.readPreference", "primary").toLowerCase();
    if ("primary".equals(readPreferenceType)) {
        readPreference = ReadPreference.primary();
    } else if ("primary_preferred".equals(readPreferenceType)) {
        readPreference = ReadPreference.primaryPreferred();
    } else if ("secondary".equals(readPreferenceType)) {
        readPreference = ReadPreference.secondary();
    } else if ("secondary_preferred".equals(readPreferenceType)) {
        readPreference = ReadPreference.secondaryPreferred();
    } else if ("nearest".equals(readPreferenceType)) {
        readPreference = ReadPreference.nearest();
    }

    MongoClientOptions.Builder options = MongoClientOptions.builder();
    options.writeConcern(writeConcern);
    options.readPreference(readPreference);
    try {
        options.connectionsPerHost(Integer.parseInt(conf.getProperty("mongodb.threads", "100")));
    } catch (NumberFormatException e) {
        options.connectionsPerHost(100);
    }

    MongoClientURI mongoClientURI = new MongoClientURI(
            conf.getProperty("mongodb.url", "mongodb://localhost:27017"), options);
    if (!this.properties.containsKey("mongodb.database")) {
        if (mongoClientURI.getDatabase() != null && !mongoClientURI.getDatabase().isEmpty()) {
            this.properties.setProperty("mongodb.database", mongoClientURI.getDatabase());
        } else {
            this.properties.setProperty("mongodb.database", DEFAULT_DATABASE);
        }
    }
    mongoClient = new MongoClient(mongoClientURI);
}

From source file:com.setronica.ucs.storage.MongoCategoryStorage.java

License:LGPL

@Override
public void open() throws IOException {
    DB db = mongoClient.getDB(mongoDbName);
    collection = db.getCollection(mongoCollectionName);
    if (collection == null) {
        collection = db.createCollection(mongoCollectionName, null);
        DBObject object = new BasicDBObject();
        object.put("ownerId", 1);
        object.put("treeId", 1);
        object.put("treeName", 1);
        object.put("categoryId", 1);
        collection.createIndex(object);//from   www. j  a va 2 s  .c  om
    }
    collection.setWriteConcern(WriteConcern.ACKNOWLEDGED);

    DBCursor cursor = collection.find();
    for (DBObject entry : cursor) {
        int treeId = (Integer) entry.get("treeId");
        MemPackedTree tree = treeStorage.get(treeId);
        if (tree == null) {
            tree = new MemPackedTree();
            tree.treeId = treeId;
            tree.ownerId = (Integer) entry.get("ownerId");
            tree.treeName = (String) entry.get("treeName");
            tree.categories = new ArrayList<MemCategoryDAO.MemPackedCategory>();
            treeStorage.put(treeId, tree);
        }

        List<MemCategoryDAO.MemPackedCategory> categories = tree.categories;
        int index = (Integer) entry.get("categoryId");
        while (index >= categories.size()) {
            categories.add(null);
        }
        categories.set(index, readObject(entry));
    }
    populateOwnerMap();
}