Example usage for com.mongodb.client MongoCollection findOneAndReplace

List of usage examples for com.mongodb.client MongoCollection findOneAndReplace

Introduction

In this page you can find the example usage for com.mongodb.client MongoCollection findOneAndReplace.

Prototype

@Nullable
TDocument findOneAndReplace(Bson filter, TDocument replacement);

Source Link

Document

Atomically find a document and replace it.

Usage

From source file:com.centurylink.mdw.mongo.MongoDocumentDb.java

License:Apache License

@Override
public boolean updateDocument(String ownerType, Long documentId, String content) {
    MongoCollection<org.bson.Document> collection = getMongoDb().getCollection(ownerType);
    org.bson.Document myDoc = null;
    if (content.startsWith("{")) {
        try {//from w  ww .j  a  v  a 2  s. co  m
            // Parse JSON to create BSON CONTENT Document
            org.bson.Document myJsonDoc = org.bson.Document.parse(content);
            if (!myJsonDoc.isEmpty()) {
                if (content.contains(".") || content.contains("$"))
                    myJsonDoc = encodeMongoDoc(myJsonDoc);
                // Plus append isJSON:true field
                myDoc = new org.bson.Document("CONTENT", myJsonDoc).append("document_id", documentId)
                        .append("isJSON", true);
            }
        } catch (Throwable ex) {
            myDoc = null;
        } // Assume not JSON then
    }
    if (myDoc == null) // Create BSON document with Raw content if it wasn't JSON plus append isJSON:false
        myDoc = new org.bson.Document("CONTENT", content).append("document_id", documentId).append("isJSON",
                false);
    if (collection.findOneAndReplace(eq("document_id", documentId), myDoc) != null)
        return true;
    else
        return false;
}

From source file:com.centurylink.mdw.service.data.process.EngineDataAccessDB.java

License:Apache License

public void updateDocumentContent(Long documentId, String content) throws SQLException {
    String selectQuery = "select OWNER_TYPE from DOCUMENT where DOCUMENT_ID = ?";
    String owner_type = "";
    ResultSet rs = db.runSelect(selectQuery, documentId);
    if (rs.next())
        owner_type = rs.getString("OWNER_TYPE");

    String query = "update DOCUMENT set MODIFY_DT = " + now() + " where DOCUMENT_ID = ?";
    db.runUpdate(query, documentId);//from w  w  w.  j  ava 2s .  c  o  m
    boolean inMongo = false; // not found (compatibility)
    if (hasMongo() && owner_type.length() > 0) {
        MongoCollection<org.bson.Document> collection = DatabaseAccess.getMongoDb().getCollection(owner_type);
        org.bson.Document myDoc = null;
        if (content.trim().startsWith("{") && content.trim().endsWith("}")) {
            try {
                org.bson.Document myJsonDoc = org.bson.Document.parse(content); // Parse JSON to create BSON CONTENT Document
                if (!myJsonDoc.isEmpty())
                    if (content.contains(".") || content.contains("$"))
                        myJsonDoc = DatabaseAccess.encodeMongoDoc(myJsonDoc);
                myDoc = new org.bson.Document("CONTENT", myJsonDoc).append("isJSON", true); // Plus append isJSON:true field
            } catch (Throwable ex) {
                myDoc = null;
            } // Assume not JSON then
        }
        if (myDoc == null) // Create BSON document with Raw content if it wasn't JSON plus append isJSON:false
            myDoc = new org.bson.Document("CONTENT", content).append("isJSON", false);
        if (collection.findOneAndReplace(eq("_id", documentId), myDoc) != null)
            inMongo = true;
    }

    if (!inMongo) {
        query = "update DOCUMENT_CONTENT set CONTENT = ? where DOCUMENT_ID = ?";
        Object[] args = new Object[2];
        args[0] = content;
        args[1] = documentId;
        db.runUpdate(query, args);
    }

}

From source file:com.cognitive.cds.invocation.mongo.IntentMappingDao.java

License:Apache License

public Document updateIntentMapping(IntentMapping im) throws JsonProcessingException {
    MongoClient mongo = mongoDbDao.getMongoClient();
    MongoDatabase db = mongo.getDatabase("intent");
    MongoCollection<Document> collection = db.getCollection("cdsintent");

    Document filter = new Document();
    if (im.get_id() != null) {
        filter.put("_id", im.get_id());
    } else if (im.getId() != null && !im.getId().isEmpty()) {
        filter.put("_id", new ObjectId(im.getId()));
    } else {// w w  w. java  2  s .c o  m
        return null;
    }
    Document obj = collection.find(filter).first();
    Document result = null;

    if (obj != null) {
        try {
            String objectJson = mapper.writeValueAsString(im);
            Document doc = Document.parse(objectJson);
            doc.put("_id", im.get_id());

            result = collection.findOneAndReplace(filter, doc);
            if (cache.containsKey(im.getName())) {
                cache.put(im.getName(), im);
            }

        } catch (IOException e) {
            logger.error("========> Deserialize: " + e.toString());
        }
    }
    return result;
}

From source file:org.apache.rya.indexing.entity.storage.mongo.MongoEntityStorage.java

License:Apache License

@Override
public void update(final Entity old, final Entity updated) throws StaleUpdateException, EntityStorageException {
    requireNonNull(old);/*from ww w  .  j a  va2  s .  co m*/
    requireNonNull(updated);

    // The updated entity must have the same Subject as the one it is replacing.
    if (!old.getSubject().equals(updated.getSubject())) {
        throw new EntityStorageException(
                "The old Entity and the updated Entity must have the same Subject. " + "Old Subject: "
                        + old.getSubject().getData() + ", Updated Subject: " + updated.getSubject().getData());
    }

    // Make sure the updated Entity has a higher verison.
    if (old.getVersion() >= updated.getVersion()) {
        throw new EntityStorageException(
                "The old Entity's version must be less than the updated Entity's version." + " Old version: "
                        + old.getVersion() + " Updated version: " + updated.getVersion());
    }

    final Set<Bson> filters = new HashSet<>();

    // Must match the old entity's Subject.
    filters.add(makeSubjectFilter(old.getSubject()));

    // Must match the old entity's Version.
    filters.add(makeVersionFilter(old.getVersion()));

    // Do a find and replace.
    final Bson oldEntityFilter = Filters.and(filters);
    final Document updatedDoc = ENTITY_CONVERTER.toDocument(updated);

    final MongoCollection<Document> collection = mongo.getDatabase(ryaInstanceName)
            .getCollection(COLLECTION_NAME);
    if (collection.findOneAndReplace(oldEntityFilter, updatedDoc) == null) {
        throw new StaleUpdateException(
                "Could not update the Entity with Subject '" + updated.getSubject().getData() + ".");
    }
}

From source file:org.apache.rya.indexing.geotemporal.mongo.MongoEventStorage.java

License:Apache License

@Override
public void update(final Event old, final Event updated) throws StaleUpdateException, EventStorageException {
    requireNonNull(old);/*from w w w  . j  ava2 s. co  m*/
    requireNonNull(updated);

    // The updated entity must have the same Subject as the one it is replacing.
    if (!old.getSubject().equals(updated.getSubject())) {
        throw new EventStorageException(
                "The old Event and the updated Event must have the same Subject. " + "Old Subject: "
                        + old.getSubject().getData() + ", Updated Subject: " + updated.getSubject().getData());
    }

    final Set<Bson> filters = new HashSet<>();

    // Must match the old entity's Subject.
    filters.add(makeSubjectFilter(old.getSubject()));

    // Do a find and replace.
    final Bson oldEntityFilter = Filters.and(filters);
    final Document updatedDoc = EVENT_CONVERTER.toDocument(updated);

    final MongoCollection<Document> collection = mongo.getDatabase(ryaInstanceName)
            .getCollection(COLLECTION_NAME);
    if (collection.findOneAndReplace(oldEntityFilter, updatedDoc) == null) {
        throw new StaleUpdateException(
                "Could not update the Event with Subject '" + updated.getSubject().getData() + ".");
    }
}

From source file:org.iotivity.cloud.accountserver.db.MongoDB.java

License:Open Source License

/**
 * API for inserting a record into DB table. the record will be replaced if
 * duplicated one./*from   www  .j a v  a 2  s. c o  m*/
 * 
 * @param tableName
 *            table name to be inserted
 * @param filter
 *            document filter
 * @param doc
 *            document to be inserted
 * @return returns true if the record is inserted and replaced successfully,
 *         or returns false
 */
public Boolean insertAndReplaceRecord(String tableName, Document filter, Document doc) {

    if (tableName == null || filter == null || doc == null)
        return false;

    MongoCollection<Document> collection = db.getCollection(tableName);

    try {

        if (collection.findOneAndReplace(filter, doc) == null) {

            collection.insertOne(doc);
        }

    } catch (Exception e) {

        e.printStackTrace();
        return false;
    }

    showRecord(tableName);

    return true;
}

From source file:org.iotivity.cloud.accountserver.db.MongoDB.java

License:Open Source License

/**
 * API for updating a record into DB table.
 * //from   ww w . j av a2s  .  co  m
 * @param tableName
 *            table name to be updated
 * @param filter
 *            document filter
 * @param record
 *            record to be updated
 * @return returns true if the record is updated successfully, or returns
 *         false
 */
public Boolean updateRecord(String tableName, Document filter, Document record) {

    if (tableName == null || filter == null || record == null)
        return false;

    MongoCollection<Document> collection = db.getCollection(tableName);

    if (collection.findOneAndReplace(filter, record) == null) {

        Log.w("DB updateX509CRL failed due to no matched record!");
        return false;
    }

    showRecord(tableName);

    return true;
}

From source file:org.iotivity.cloud.rdserver.db.MongoDB.java

License:Open Source License

/**
 * API for updating a record into DB table.
 * /*from  ww w.  ja  v a2  s  .co m*/
 * @param tableName
 *            table name to be updated
 * @param filter
 *            document filter
 * @param record
 *            record to be updated
 * @return returns true if the record is updated successfully, or returns
 *         false
 */
public Boolean updateRecord(String tableName, Document filter, Document record) {

    if (tableName == null || filter == null || record == null)
        return false;

    MongoCollection<Document> collection = db.getCollection(tableName);

    if (collection.findOneAndReplace(filter, record) == null) {

        Log.w("DB update failed due to no matched record!");
        return false;
    }

    showRecord(tableName);

    return true;
}

From source file:org.iotivity.cloud.rdserver.MongoDB.java

License:Open Source License

/**
 * API for storing information of published resources
 *
 * @param publishPayloadFormat//  w ww  .j a  va2 s. c o m
 *            information of published resources to store in collection
 * @param tablename
 *            collection name
 */
public void createResource(PublishPayloadFormat publishPayloadFormat, String tablename) {
    ArrayList<Document> docList = createDocuments(publishPayloadFormat);
    Iterator<Document> docIter = docList.iterator();

    MongoCollection<Document> collection = db.getCollection(tablename);

    while (docIter.hasNext()) {
        Document doc = docIter.next();

        if (collection.findOneAndReplace(
                Filters.and(Filters.eq(Constants.RS_DEVICE_ID, doc.get(Constants.RS_DEVICE_ID)),
                        Filters.eq(Constants.RS_INS, doc.get(Constants.RS_INS))),
                doc) == null) {

            collection.insertOne(doc);
        }
    }
}

From source file:org.jaqpot.core.db.entitymanager.MongoDBEntityManager.java

License:Open Source License

@Override
public <T extends JaqpotEntity> T merge(T entity) {
    MongoDatabase db = mongoClient.getDatabase(database);
    Class<T> entityClass = (Class<T>) entity.getClass();
    String entityJSON = serializer.write(entity);
    Document entityBSON = Document.parse(entityJSON);
    MongoCollection<Document> collection = db.getCollection(collectionNames.get(entity.getClass()));
    Document oldEntity = collection.findOneAndReplace(new Document("_id", entity.getId()), entityBSON);
    return serializer.parse(JSON.serialize(oldEntity), entityClass);
}