Example usage for com.mongodb DBObject put

List of usage examples for com.mongodb DBObject put

Introduction

In this page you can find the example usage for com.mongodb DBObject put.

Prototype

Object put(String key, Object v);

Source Link

Document

Sets a name/value pair in this object.

Usage

From source file:com.imaginea.mongodb.services.DocumentServiceImpl.java

License:Apache License

/**
 * Updates a document inside a collection in a database in mongo to which
 * user is connected to.// www.j  a  v a  2 s . c om
 * 
 * @param dbName
 *            Name of Database
 * @param collectionName
 *            Name of Collection from which to get all Documents
 * @param id
 *            Id of Document to be updated
 * @param newData
 *            new Document value.
 * @return Update status
 * @exception EmptyDatabaseNameException
 *                If database name is null
 * @exception EmptyCollectionNameException
 *                If Collection name is null
 * @exception EmptyDocumentDataException
 *                If Document data is null
 * @exception UndefinedDatabaseException
 *                If database is not present
 * @exception UndefinedCollectionException
 *                If Collection is not present
 * @exception UpdateDocumentException
 *                Any exception while updating document
 * @exception DatabaseException
 *                throw super type of UndefinedDatabaseException
 * @exception ValidationException
 *                throw super type of
 *                EmptyDatabaseNameException,EmptyCollectionNameException
 *                ,EmptyDocumentDataException
 * @exception CollectionException
 *                throw super type of UndefinedCollectionException
 * @exception DocumentException
 *                throw super type of UpdateDocumentException
 * @exception JSONException
 * 
 */

public String updateDocument(String dbName, String collectionName, ObjectId id, DBObject newData)
        throws DatabaseException, CollectionException, DocumentException, ValidationException {

    mongoInstance = mongoInstanceProvider.getMongoInstance();
    if (dbName == null) {
        throw new EmptyDatabaseNameException("Database name is null");

    }
    if (dbName.equals("")) {
        throw new EmptyDatabaseNameException("Database Name Empty");
    }

    if (collectionName == null) {
        throw new EmptyCollectionNameException("Collection name is null");
    }
    if (collectionName.equals("")) {
        throw new EmptyCollectionNameException("Collection Name Empty");
    }
    String result = null;
    DBObject documentData = null;
    try {
        if (!mongoInstance.getDatabaseNames().contains(dbName)) {
            throw new UndefinedDatabaseException("DB [" + dbName + "] DOES NOT EXIST");
        }

        if (!mongoInstance.getDB(dbName).getCollectionNames().contains(collectionName)) {
            throw new UndefinedCollectionException(
                    "COLLECTION [ " + collectionName + "] _DOES_NOT_EXIST in Db [ " + dbName + "]");
        }
        if (id == null) {
            throw new EmptyDocumentDataException("Document is empty");
        }

        String temp = (String) newData.get("_id");
        if (temp == null) {
            throw new DocumentException(ErrorCodes.INVALID_OBJECT_ID, "INVALID_OBJECT_ID");
        }
        if (temp.equals("")) {
            throw new DocumentException(ErrorCodes.INVALID_OBJECT_ID, "INVALID_OBJECT_ID");
        }

        ObjectId newId = new ObjectId(temp);
        if (!newId.equals(id)) {
            throw new DocumentException(ErrorCodes.INVALID_OBJECT_ID, "Cannot Change Object Id of a document");
        } else {
            // Id's equal but putting the id of old document still
            // as newData as id of string type but we need ObjectId type
            newData.put("_id", id);
        }
        DBObject query = new BasicDBObject("_id", id);

        DBCollection collection = mongoInstance.getDB(dbName).getCollection(collectionName);
        DBObject doc = collection.findOne(query);
        if (doc == null) {
            throw new UndefinedDocumentException("DOCUMENT_DOES_NOT_EXIST");
        }

        collection.update(doc, newData, true, false);
        documentData = collection.findOne(query);

    } catch (IllegalArgumentException e) {
        // When error converting object Id
        throw new DocumentException(ErrorCodes.INVALID_OBJECT_ID, "INVALID_OBJECT_ID");

    } catch (MongoException e) {
        throw new UpdateDocumentException("DOCUMENT_UPDATE_EXCEPTION");
    }
    result = "Updated Document: [" + documentData + "]";

    return result;
}

From source file:com.imaginea.mongodb.services.DocumentServiceImpl.java

License:Apache License

/**
 * Deletes a document inside a collection in a database in mongo to which
 * user is connected to./*w w  w . j ava2 s.  com*/
 * 
 * @param dbName
 *            Name of Database
 * @param collectionName
 *            Name of Collection from which to get all Documents
 * @param id
 *            Id of Document to be updated
 * @return Deletion status
 * @exception EmptyDatabaseNameException
 *                If database name is null
 * @exception EmptyCollectionNameException
 *                If Collection name is null
 * @exception EmptyDocumentDataException
 *                If Document data is null
 * @exception UndefinedDatabaseException
 *                If database is not present
 * @exception UndefinedCollectionException
 *                If Collection is not present
 * @exception DeleteDocumentException
 *                Any exception while deleting document
 * @exception DatabaseException
 *                throw super type of UndefinedDatabaseException
 * @exception ValidationException
 *                throw super type of
 *                EmptyDatabaseNameException,EmptyCollectionNameException
 *                ,EmptyDocumentDataException
 * @exception CollectionException
 *                throw super type of UndefinedCollectionException
 * @exception DocumentException
 *                throw super type of DeleteDocumentException
 * 
 */

public String deleteDocument(String dbName, String collectionName, ObjectId id)
        throws DatabaseException, CollectionException, DocumentException, ValidationException {
    mongoInstance = mongoInstanceProvider.getMongoInstance();
    if (dbName == null) {
        throw new EmptyDatabaseNameException("Database name is null");

    }
    if (dbName.equals("")) {
        throw new EmptyDatabaseNameException("Database Name Empty");
    }

    if (collectionName == null) {
        throw new EmptyCollectionNameException("Collection name is null");
    }
    if (collectionName.equals("")) {
        throw new EmptyCollectionNameException("Collection Name Empty");
    }

    String result = null;
    DBObject documentData = null;
    try {
        if (!mongoInstance.getDatabaseNames().contains(dbName)) {
            throw new UndefinedDatabaseException("DB [" + dbName + "] DOES NOT EXIST");
        }

        if (!mongoInstance.getDB(dbName).getCollectionNames().contains(collectionName)) {
            throw new UndefinedCollectionException(
                    "COLLECTION [ " + collectionName + "] _DOES_NOT_EXIST in Db [ " + dbName + "]");
        }
        DBCollection coll = mongoInstance.getDB(dbName).getCollection(collectionName);
        if (coll.isCapped()) {
            throw new DocumentException(ErrorCodes.DELETING_FROM_CAPPED_COLLECTION,
                    "Cannot Delete From a Capped Collection");
        }
        if (id == null) {
            throw new EmptyDocumentDataException("Document is empty");
        }

        DBObject query = new BasicDBObject();
        query.put("_id", id);
        DBCollection collection = this.mongoInstance.getDB(dbName).getCollection(collectionName);
        documentData = collection.findOne(query);

        if (documentData == null) {
            throw new UndefinedDocumentException("DOCUMENT_DOES_NOT_EXIST");
        }

        mongoInstance.getDB(dbName).getCollection(collectionName).remove(documentData);

    } catch (MongoException e) {
        throw new DeleteDocumentException("DOCUMENT_DELETION_EXCEPTION");
    }
    result = "Deleted Document with Data : [" + documentData + "]";
    return result;
}

From source file:com.impetus.client.mongodb.DefaultMongoDBDataHandler.java

License:Apache License

/**
 * Gets the document from entity./*from   w ww . ja  v  a2 s  . c  o m*/
 * 
 * @param m
 *            the m
 * @param entity
 *            the entity
 * @param relations
 *            the relations
 * @return the document from entity
 * @throws PropertyAccessException
 *             the property access exception
 */
public Map<String, DBObject> getDocumentFromEntity(EntityMetadata m, Object entity,
        List<RelationHolder> relations, final KunderaMetadata kunderaMetadata) throws PropertyAccessException {
    Map<String, DBObject> dbObjects = new HashMap<String, DBObject>();

    MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()
            .getMetamodel(m.getPersistenceUnit());
    EntityType entityType = metaModel.entity(m.getEntityClazz());

    // Populate Row Key
    Object id = PropertyAccessorHelper.getId(entity, m);

    DBObject dbObj = MongoDBUtils.getDBObject(m, m.getTableName(), dbObjects, metaModel, id);

    // dbObjects.put(m.getTableName(), dbObj);

    // Populate columns
    Set<Attribute> columns = entityType.getAttributes();
    for (Attribute column : columns) {
        String tableName = ((AbstractAttribute) column).getTableName() != null
                ? ((AbstractAttribute) column).getTableName()
                : m.getTableName();
        dbObj = MongoDBUtils.getDBObject(m, tableName, dbObjects, metaModel, id);

        if (!column.equals(m.getIdAttribute())) {
            try {
                Class javaType = ((AbstractAttribute) column).getBindableJavaType();
                if (metaModel.isEmbeddable(javaType)) {
                    Map<String, DBObject> embeddedObjects = onEmbeddable(column, entity, metaModel, dbObj,
                            m.getTableName());
                    for (String documentName : embeddedObjects.keySet()) {
                        DBObject db = dbObjects.get(documentName);
                        if (db == null) {
                            db = MongoDBUtils.getDBObject(m, documentName, dbObjects, metaModel, id);
                        }
                        db.put(((AbstractAttribute) column).getJPAColumnName(),
                                embeddedObjects.get(documentName));
                        dbObjects.put(documentName, db);

                    }
                } else if (!column.isAssociation()) {
                    DocumentObjectMapper.extractFieldValue(entity, dbObj, column);
                }
            } catch (PropertyAccessException paex) {
                log.error("Can't access property " + column.getName());
            }
        }
        // dbObjects.put(tableName, dbObj);
    }
    if (relations != null) {
        dbObj = dbObjects.get(m.getTableName());
        for (RelationHolder rh : relations) {
            dbObj.put(rh.getRelationName(),
                    MongoDBUtils.populateValue(rh.getRelationValue(), rh.getRelationValue().getClass()));
        }
        // dbObjects.put(m.getTableName(), dbObj);
    }

    if (((AbstractManagedType) entityType).isInherited()) {
        dbObj = dbObjects.get(m.getTableName());
        String discrColumn = ((AbstractManagedType) entityType).getDiscriminatorColumn();
        String discrValue = ((AbstractManagedType) entityType).getDiscriminatorValue();

        // No need to check for empty or blank, as considering it as valid
        // name for nosql!
        if (discrColumn != null && discrValue != null) {
            dbObj.put(discrColumn, discrValue);
        }
        // dbObjects.put(m.getTableName(), dbObj);
    }
    return dbObjects;
}

From source file:com.impetus.client.mongodb.DefaultMongoDBDataHandler.java

License:Apache License

/**
 * Gets the GFSInputFile from entity./*from   w  w  w.  j  a va  2s  .  c  o m*/
 * 
 * @param gfs
 *            the gfs
 * @param m
 *            the m
 * @param entity
 *            the entity
 * @param kunderaMetadata
 *            the kundera metadata
 * @return the GFS iuput file from entity
 */
public GridFSInputFile getGFSInputFileFromEntity(GridFS gfs, EntityMetadata m, Object entity,
        KunderaMetadata kunderaMetadata, boolean isUpdate) {
    MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()
            .getMetamodel(m.getPersistenceUnit());
    EntityType entityType = metaModel.entity(m.getEntityClazz());
    GridFSInputFile gridFSInputFile = null;

    DBObject gfsMetadata = new BasicDBObject();

    Set<Attribute> columns = entityType.getAttributes();
    for (Attribute column : columns) {
        boolean isLob = ((Field) column.getJavaMember()).getAnnotation(Lob.class) != null;
        if (isLob) {
            gridFSInputFile = createGFSInputFile(gfs, entity, (Field) column.getJavaMember());
            gridFSInputFile.setFilename(column.getName());
        } else {
            if (isUpdate && column.getName().equals(m.getIdAttribute().getName())) {
                gfsMetadata.put(((AbstractAttribute) column).getJPAColumnName(), new ObjectId());
            } else
                DocumentObjectMapper.extractFieldValue(entity, gfsMetadata, column);
        }
    }
    gridFSInputFile.setMetaData(gfsMetadata);
    return gridFSInputFile;
}

From source file:com.impetus.client.mongodb.DefaultMongoDBDataHandler.java

License:Apache License

/**
 * @param entityType//from  w  ww .ja v a  2 s .  c  o m
 * @param column
 * @param m
 * @param entity
 */
Map<String, DBObject> onEmbeddable(Attribute column, Object entity, Metamodel metaModel, DBObject dbObj,
        String tableName) {
    EmbeddableType embeddableType = metaModel.embeddable(((AbstractAttribute) column).getBindableJavaType());
    Object embeddedObject = PropertyAccessorHelper.getObject(entity, (Field) column.getJavaMember());
    Map<String, DBObject> embeddedObjects = new HashMap<String, DBObject>();

    if (embeddedObject != null) {
        if (column.isCollection()) {
            Collection embeddedCollection = (Collection) embeddedObject;
            // means it is case of element collection

            dbObj.put(((AbstractAttribute) column).getJPAColumnName(),
                    DocumentObjectMapper.getDocumentListFromCollection(metaModel, embeddedCollection,
                            embeddableType.getAttributes(), tableName));
        } else {
            embeddedObjects = DocumentObjectMapper.getDocumentFromObject(metaModel, embeddedObject,
                    embeddableType.getAttributes(), tableName);
            dbObj.put(((AbstractAttribute) column).getJPAColumnName(), embeddedObjects.get(tableName));
        }
    }
    return embeddedObjects;
}

From source file:com.impetus.client.mongodb.DocumentObjectMapper.java

License:Apache License

/**
 * Extract entity field./*ww  w  .j  a v a  2  s .co  m*/
 * 
 * @param entity
 *            the entity
 * @param dbObj
 *            the db obj
 * @param column
 *            the column
 * @throws PropertyAccessException
 *             the property access exception
 */
static void extractFieldValue(Object entity, DBObject dbObj, Attribute column) throws PropertyAccessException {
    try {
        Object valueObject = PropertyAccessorHelper.getObject(entity, (Field) column.getJavaMember());

        if (valueObject != null) {
            Class javaType = column.getJavaType();
            switch (AttributeType.getType(javaType)) {
            case MAP:
                Map mapObj = (Map) valueObject;
                // BasicDBObjectBuilder builder =
                // BasicDBObjectBuilder.start(mapObj);
                BasicDBObjectBuilder b = new BasicDBObjectBuilder();
                Iterator i = mapObj.entrySet().iterator();
                while (i.hasNext()) {
                    Map.Entry entry = (Map.Entry) i.next();
                    b.add(entry.getKey().toString(),
                            MongoDBUtils.populateValue(entry.getValue(), entry.getValue().getClass()));
                }
                dbObj.put(((AbstractAttribute) column).getJPAColumnName(), b.get());
                break;
            case SET:
            case LIST:
                Collection collection = (Collection) valueObject;
                BasicDBList basicDBList = new BasicDBList();
                for (Object o : collection) {
                    basicDBList.add(o);
                }
                dbObj.put(((AbstractAttribute) column).getJPAColumnName(), basicDBList);
                break;
            case POINT:

                Point p = (Point) valueObject;
                double[] coordinate = new double[] { p.getX(), p.getY() };
                dbObj.put(((AbstractAttribute) column).getJPAColumnName(), coordinate);
                break;
            case ENUM:
            case PRIMITIVE:
                dbObj.put(((AbstractAttribute) column).getJPAColumnName(),
                        MongoDBUtils.populateValue(valueObject, javaType));
                break;
            }
        }
    } catch (PropertyAccessException paex) {
        log.error("Error while getting column {} value, caused by : .",
                ((AbstractAttribute) column).getJPAColumnName(), paex);
        throw new PersistenceException(paex);
    }
}

From source file:com.impetus.client.mongodb.MongoDBClient.java

License:Apache License

@Override
public void persistJoinTable(JoinTableData joinTableData) {
    String joinTableName = joinTableData.getJoinTableName();
    String joinColumnName = joinTableData.getJoinColumnName();
    String invJoinColumnName = joinTableData.getInverseJoinColumnName();
    Map<Object, Set<Object>> joinTableRecords = joinTableData.getJoinTableRecords();

    DBCollection dbCollection = mongoDb.getCollection(joinTableName);
    KunderaCoreUtils.printQuery("Persist join table:" + joinTableName, showQuery);

    for (Object key : joinTableRecords.keySet()) {
        Set<Object> values = joinTableRecords.get(key);
        Object joinColumnValue = key;

        for (Object childId : values) {
            DBObject dbObj = new BasicDBObject();
            dbObj.put("_id", joinColumnValue.toString() + childId);
            dbObj.put(joinColumnName, MongoDBUtils.populateValue(joinColumnValue, joinColumnValue.getClass()));
            dbObj.put(invJoinColumnName, MongoDBUtils.populateValue(childId, childId.getClass()));
            KunderaCoreUtils.printQuery("id:" + joinColumnValue.toString() + childId + "   " + joinColumnName
                    + ":" + joinColumnValue + "   " + invJoinColumnName + ":" + childId, showQuery);

            dbCollection.save(dbObj, getWriteConcern());
        }//  w ww .ja  v a2s .c  om
    }
}

From source file:com.impetus.client.mongodb.MongoDBClient.java

License:Apache License

@Override
public void delete(Object entity, Object pKey) {
    EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,
            entity.getClass());//from  w w w . jav a2s .co  m
    MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()
            .getMetamodel(entityMetadata.getPersistenceUnit());
    AbstractManagedType managedType = (AbstractManagedType) metaModel.entity(entityMetadata.getEntityClazz());

    DBObject query = new BasicDBObject();

    if (managedType.hasLobAttribute()) {
        KunderaGridFS gfs = new KunderaGridFS(mongoDb, entityMetadata.getTableName());
        String id = ((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName();
        query.put("metadata." + id, pKey);
        gfs.remove(query);
    }

    else {
        if (metaModel.isEmbeddable(entityMetadata.getIdAttribute().getBindableJavaType())) {
            MongoDBUtils.populateCompoundKey(query, entityMetadata, metaModel, pKey);
        } else {
            query.put("_id", MongoDBUtils.populateValue(pKey, pKey.getClass()));
        }
        // For secondary tables.
        List<String> secondaryTables = ((DefaultEntityAnnotationProcessor) managedType.getEntityAnnotation())
                .getSecondaryTablesName();
        secondaryTables.add(entityMetadata.getTableName());

        for (String collectionName : secondaryTables) {
            KunderaCoreUtils.printQuery("Drop existing collection:" + query, showQuery);
            DBCollection dbCollection = mongoDb.getCollection(collectionName);
            dbCollection.remove(query, getWriteConcern(), encoder);
        }

        getIndexManager().remove(entityMetadata, entity, pKey);
    }
}

From source file:com.impetus.client.mongodb.MongoDBClient.java

License:Apache License

/**
 * On persist GFS.//from www  .  ja va2 s. c  om
 * 
 * @param entity
 *            the entity
 * @param entityId
 *            the entityId
 * @param entityMetadata
 *            the entity metadata
 * @param isUpdate
 *            the is update
 */
private void onPersistGFS(Object entity, Object entityId, EntityMetadata entityMetadata, boolean isUpdate) {
    KunderaGridFS gfs = new KunderaGridFS(mongoDb, entityMetadata.getTableName());
    if (!isUpdate) {
        GridFSInputFile gfsInputFile = handler.getGFSInputFileFromEntity(gfs, entityMetadata, entity,
                kunderaMetadata, isUpdate);
        saveGridFSFile(gfsInputFile, entityMetadata);
    } else {
        Object val = handler.getLobFromGFSEntity(gfs, entityMetadata, entity, kunderaMetadata);
        String md5 = MongoDBUtils.calculateMD5(val);
        GridFSDBFile outputFile = findGridFSDBFile(entityMetadata, entityId);

        // checking MD5 of the file to be updated with the file saved in DB
        if (md5.equals(outputFile.getMD5())) {
            DBObject metadata = handler.getMetadataFromGFSEntity(gfs, entityMetadata, entity, kunderaMetadata);
            outputFile.setMetaData(metadata);
            outputFile.save();
        } else {
            // GFSInput file is created corresponding to the entity to be
            // merged with a new ObjectID()
            GridFSInputFile gfsInputFile = handler.getGFSInputFileFromEntity(gfs, entityMetadata, entity,
                    kunderaMetadata, isUpdate);
            ObjectId updatedId = (ObjectId) gfsInputFile.getId();
            DBObject metadata = gfsInputFile.getMetaData();

            // updated file is saved in DB
            saveGridFSFile(gfsInputFile, entityMetadata);

            // last version of file is deleted
            DBObject query = new BasicDBObject("_id", outputFile.getId());
            gfs.remove(query);

            // newly added file is found using its _id
            outputFile = gfs.findOne(updatedId);

            // Id of entity (which is saved in metadata) is updated to its
            // actual Id
            metadata.put(((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName(), entityId);
            outputFile.setMetaData(metadata);

            // output file is updated
            outputFile.save();
        }
    }
}

From source file:com.impetus.client.mongodb.schemamanager.MongoDBSchemaManager.java

License:Apache License

/**
 * @param tableInfo//  www .j av  a2  s.c  o m
 * @return
 */
private DBObject setCollectionProperties(TableInfo tableInfo) {
    boolean isCappedCollection = isCappedCollection(tableInfo);
    DBObject options = new BasicDBObject();
    if ((tableInfo.getLobColumnInfo().isEmpty() || tableInfo.getLobColumnInfo() == null)
            && isCappedCollection) {
        int collectionSize = MongoDBPropertyReader.msmd != null
                ? MongoDBPropertyReader.msmd.getCollectionSize(databaseName, tableInfo.getTableName())
                : 100000;
        int max = MongoDBPropertyReader.msmd != null
                ? MongoDBPropertyReader.msmd.getMaxSize(databaseName, tableInfo.getTableName())
                : 100;
        options.put(MongoDBConstants.CAPPED, isCappedCollection);
        options.put(MongoDBConstants.SIZE, collectionSize);
        options.put(MongoDBConstants.MAX, max);
    }
    return options;
}