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:br.bireme.scl.UndoUpdate.java

License:Open Source License

private static void undo(final String host, final int port, final String database, final String fromDate,
        final String docId) throws UnknownHostException, ParseException {
    assert host != null;
    assert port > 0;
    assert database != null;
    assert (fromDate != null || docId != null);

    final MongoClient client = new MongoClient(host, port);
    final DB db = client.getDB(database);
    final DBCollection from_coll = db.getCollection(HISTORY_COL);
    final DBCollection to_coll = db.getCollection(BROKEN_LINKS_COL);
    final String prefix = ELEM_LST_FIELD + ".0.";
    final BasicDBObject query;

    if (fromDate == null) {
        query = new BasicDBObject("_id", docId);
    } else {/*  w  w w  . java 2 s  .co m*/
        final SimpleDateFormat simple = new SimpleDateFormat(
                "yyyyMMdd" + (fromDate.contains(":") ? "-HH:mm:ss" : ""));
        final Date fDate = simple.parse(fromDate);
        query = new BasicDBObject(prefix + LAST_UPDATE_FIELD, new BasicDBObject("$gte", fDate));
    }
    final DBCursor cursor = from_coll.find(query);
    int total = 0;
    int reverted = 0;

    System.out.println("host=" + host);
    System.out.println("port=" + port);
    System.out.println("database=" + database);
    if (fromDate == null) {
        System.out.println("doc id=" + docId);
    } else {
        System.out.println("from date=" + fromDate);
    }
    System.out.println("found=" + cursor.size());

    while (cursor.hasNext()) {
        final BasicDBObject doc_from = (BasicDBObject) cursor.next();
        final BasicDBObject doc_to = new BasicDBObject(doc_from);
        final String id = doc_from.getString(ID_FIELD);
        final BasicDBList list = (BasicDBList) doc_from.get(ELEM_LST_FIELD);
        final BasicDBObject elem = (BasicDBObject) list.get(0);
        final Date date = elem.getDate(LAST_UPDATE_FIELD);

        doc_to.put(LAST_UPDATE_FIELD, date);
        doc_to.put(BROKEN_URL_FIELD, elem.getString(BROKEN_URL_FIELD));
        doc_to.put(MSG_FIELD, elem.getString(MSG_FIELD));
        doc_to.put(CENTER_FIELD, elem.get(CENTER_FIELD));
        doc_to.removeField(ELEM_LST_FIELD);

        final WriteResult wr = to_coll.save(doc_to, WriteConcern.ACKNOWLEDGED);
        if (wr.getCachedLastError().ok()) {
            final WriteResult wr2 = from_coll.remove(doc_from, WriteConcern.ACKNOWLEDGED);
            if (wr2.getCachedLastError().ok()) {
                reverted++;
                System.out.println("+++id=" + id + " date=" + date);
            } else {
                System.err.println("Document[" + id + "] delete error.");
            }
        } else {
            System.err.println("Document[" + id + "] update error.");
        }
        total++;
    }
    cursor.close();

    System.out.println("total/undo: " + total + "/" + reverted);
}

From source file:br.bireme.tmp.AddPrettyField.java

License:Open Source License

private static void add(final String mongo_host, final int mongo_port, final String mongo_db,
        final String mongo_col) throws UnknownHostException {
    assert mongo_host != null;
    assert mongo_port > 0;
    assert mongo_db != null;
    assert mongo_col != null;

    final MongoClient client = new MongoClient(mongo_host, mongo_port);
    final DB db = client.getDB(mongo_db);
    final DBCollection coll = db.getCollection(HISTORY_COL);
    final DBCursor cursor = coll.find();
    int total = 0;

    System.out.println("host=" + mongo_host);
    System.out.println("port=" + mongo_port);
    System.out.println("database=" + mongo_db);
    System.out.println("collection=" + mongo_col);
    System.out.println("num of documents=" + cursor.size());

    while (cursor.hasNext()) {
        final BasicDBObject doc1 = (BasicDBObject) cursor.next();
        final BasicDBList list = (BasicDBList) doc1.get(ELEM_LST_FIELD);

        for (Object obj : list) {
            final BasicDBObject doc2 = (BasicDBObject) obj;
            if (!doc2.containsField(PRETTY_BROKEN_URL_FIELD)) {
                final String burl = doc2.getString(BROKEN_URL_FIELD);
                try {
                    final String pburl = EncDecUrl.decodeUrl(burl);
                    doc2.append(PRETTY_BROKEN_URL_FIELD, pburl);

                    final WriteResult wr = coll.save(doc1, WriteConcern.ACKNOWLEDGED);
                    if (wr.getCachedLastError().ok()) {
                        total++;//from   w ww.  j a  v  a 2  s  . c  o m
                    } else {
                        System.err.println("Document[" + doc1.getString("_id") + "] update error.");
                    }
                } catch (IOException ioe) {
                    System.err.println("Document[" + doc1.getString("_id") + "] bad encode conversion"
                            + " url=[" + burl + "]");
                }
            }
        }
    }
    cursor.close();
    System.out.println("num of added fields: " + total);
}

From source file:calliope.core.database.MongoConnection.java

License:Open Source License

/**
 * PUT a new json file to the database/*from  ww w  . j a v  a 2s. com*/
 * @param collName the name of the collection
 * @param json the json to put there
 * @return the server response
 */
@Override
public String addToDb(String collName, String json) throws DbException {
    try {
        DBObject doc = (DBObject) JSON.parse(json);
        connect();
        DBCollection coll = getCollectionFromName(collName);
        if (doc.containsField(JSONKeys._ID)) {
            Object id = doc.get(JSONKeys._ID);
            DBObject query = new BasicDBObject(JSONKeys._ID, id);
            if (query != null) {
                WriteResult result = coll.update(query, doc, true, false);
                return result.toString();
            } else
                throw new Exception("Failed to update object " + id);
        } else {
            WriteResult result = coll.insert(doc, WriteConcern.ACKNOWLEDGED);
            // return the new document's id
            ObjectId id = (ObjectId) doc.get("_id");
            JSONObject jDoc = (JSONObject) JSONValue.parse(result.toString());
            jDoc.put("_id", id.toString());
            return jDoc.toJSONString();
        }
    } catch (Exception e) {
        throw new DbException(e);
    }
}

From source file:com.arquivolivre.mongocom.management.CollectionManager.java

License:Apache License

public void update(MongoQuery query, Object document, boolean upsert, boolean multi) {
    update(query, document, upsert, multi, WriteConcern.ACKNOWLEDGED);
}

From source file:com.dawsonsystems.session.MongoManager.java

License:Apache License

private void initDbConnection(String path) throws LifecycleException {
    try {//from  w  w w  .jav a2  s  .  com
        String[] hosts = getHost().split(",");

        List<ServerAddress> addrs = new ArrayList<>();

        for (String host : hosts) {
            addrs.add(new ServerAddress(host, getPort()));
        }

        mongo = new MongoClient(addrs,
                MongoClientOptions.builder().description("TomcatMongoSession[path=" + path + "]")
                        .alwaysUseMBeans(true).connectionsPerHost(connectionsPerHost).build());

        db = mongo.getDatabase(getDatabase());
        if (slaveOk) {
            db.withReadPreference(ReadPreference.secondaryPreferred());
        }
        db.withWriteConcern(WriteConcern.ACKNOWLEDGED);
        getCollection().createIndex(new BasicDBObject("lastmodified", 1));
        log.info("Connected to Mongo " + host + "/" + database + " for session storage, slaveOk=" + slaveOk
                + ", " + (getMaxInactiveInterval() * 1000) + " session live time");
    } catch (RuntimeException e) {
        e.printStackTrace();
        throw new LifecycleException("Error Connecting to Mongo", e);
    }
}

From source file:com.deftlabs.lock.mongo.impl.LockDao.java

License:Apache License

/**
 * Increment the lock heartbeat time.//from  w  ww.j  ava 2s  . co m
 */
static void heartbeat(final MongoClient pMongo, final String pLockName, final ObjectId pLockId,
        final DistributedLockOptions pLockOptions, final DistributedLockSvcOptions pSvcOptions)

{
    try {
        final long serverTime = getServerTime(pMongo, pSvcOptions);

        final BasicDBObject query = new BasicDBObject(LockDef.ID.field, pLockName);
        query.put(LockDef.LOCK_ID.field, pLockId);
        query.put(LockDef.STATE.field, LockState.LOCKED.code());

        final BasicDBObject toSet = new BasicDBObject(LockDef.LAST_HEARTBEAT.field, new Date(serverTime));
        toSet.put(LockDef.LOCK_TIMEOUT_TIME.field,
                new Date(serverTime + pLockOptions.getInactiveLockTimeout()));
        getDbCollection(pMongo, pSvcOptions).update(query, new BasicDBObject(SET, toSet), false, false,
                WriteConcern.ACKNOWLEDGED);

    } finally {
    }
}

From source file:com.deftlabs.lock.mongo.impl.LockDao.java

License:Apache License

/**
 * This will try and create the object. If successful, it will return the lock id.
 * Otherwise, it will return null (i.e., no lock).
 *//*from www  . jav  a  2  s .c o  m*/
private static ObjectId tryInsertNew(final MongoClient pMongo, final String pLockName,
        final DistributedLockSvcOptions pSvcOptions, final DistributedLockOptions pLockOptions,
        final long pServerTime, final long pStartTime) {
    final long adjustTime = System.currentTimeMillis() - pStartTime;

    final long serverTime = pServerTime + adjustTime;
    final Date now = new Date(serverTime);
    final ObjectId lockId = ObjectId.get();

    final Thread currentThread = Thread.currentThread();

    final BasicDBObject lockDoc = new BasicDBObject(LockDef.ID.field, pLockName);
    lockDoc.put(LockDef.LIBRARY_VERSION.field, pSvcOptions.getLibVersion());
    lockDoc.put(LockDef.UPDATED.field, now);
    lockDoc.put(LockDef.LAST_HEARTBEAT.field, now);
    lockDoc.put(LockDef.LOCK_ACQUIRED_TIME.field, now);
    lockDoc.put(LockDef.LOCK_ID.field, lockId);
    lockDoc.put(LockDef.STATE.field, LockState.LOCKED.code());
    lockDoc.put(LockDef.LOCK_TIMEOUT_TIME.field,
            new Date((serverTime + pLockOptions.getInactiveLockTimeout())));
    lockDoc.put(LockDef.OWNER_APP_NAME.field, pSvcOptions.getAppName());
    lockDoc.put(LockDef.OWNER_ADDRESS.field, pSvcOptions.getHostAddress());
    lockDoc.put(LockDef.OWNER_HOSTNAME.field, pSvcOptions.getHostname());
    lockDoc.put(LockDef.OWNER_THREAD_ID.field, currentThread.getId());
    lockDoc.put(LockDef.OWNER_THREAD_NAME.field, currentThread.getName());
    lockDoc.put(LockDef.OWNER_THREAD_GROUP_NAME.field, currentThread.getThreadGroup().getName());
    lockDoc.put(LockDef.LOCK_ATTEMPT_COUNT.field, 0);
    lockDoc.put(LockDef.INACTIVE_LOCK_TIMEOUT.field, pLockOptions.getInactiveLockTimeout());

    // Insert, if successful then get out of here.
    try {
        getDbCollection(pMongo, pSvcOptions).insert(lockDoc, WriteConcern.ACKNOWLEDGED);
    } catch (MongoException e) {
        return null;
    }

    if (pSvcOptions.getEnableHistory()) {
        LockHistoryDao.insert(pMongo, pLockName, pSvcOptions, pLockOptions, serverTime, LockState.LOCKED,
                lockId, false);
    }

    return lockId;
}

From source file:com.deftlabs.lock.mongo.impl.LockDao.java

License:Apache License

/**
 * Increment the waiting request count. This can be used by application developers
 * to diagnose problems with their applications.
 */// w  w w . j a  v  a 2s .  c o  m
static void incrementLockAttemptCount(final MongoClient pMongo, final String pLockName, final ObjectId pLockId,
        final DistributedLockSvcOptions pSvcOptions) {

    final BasicDBObject query = new BasicDBObject(LockDef.ID.field, pLockName);
    query.put(LockDef.LOCK_ID.field, pLockId);

    getDbCollection(pMongo, pSvcOptions).update(query,
            new BasicDBObject(INC, new BasicDBObject(LockDef.LOCK_ATTEMPT_COUNT.field, 1)), false, false,
            WriteConcern.ACKNOWLEDGED);
}

From source file:com.dilmus.dilshad.scabi.db.DDB.java

License:Open Source License

public DDB(String dbHost, String dbPort, String dbName) {
    m_mongo = new MongoClient(dbHost, Integer.parseInt(dbPort));
    m_mongodb = m_mongo.getDatabase(dbName);

    m_dbHost = dbHost;//from w  w w  .  j  ava  2s  .  c om
    m_dbPort = dbPort;
    m_dbName = dbName;

    m_mongo.setWriteConcern(WriteConcern.ACKNOWLEDGED);
    // ?? m_mongo.setReadPreference(ReadPreference.primaryPreferred());
}

From source file:com.dilmus.dilshad.scabi.deprecated.DDBOld.java

License:Open Source License

public DDBOld(String dbHost, String dbPort, String dbName) {
    m_mongo = new MongoClient(dbHost, Integer.parseInt(dbPort));
    m_mongodb = m_mongo.getDatabase(dbName);
    m_db = new DB(m_mongo, dbName);

    m_dbHost = dbHost;//w  w  w  .ja v  a 2 s. c  om
    m_dbPort = dbPort;
    m_dbName = dbName;

    m_mongo.setWriteConcern(WriteConcern.ACKNOWLEDGED);
    // ?? m_mongo.setReadPreference(ReadPreference.primaryPreferred());
}