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.ebay.cloud.cms.dal.persistence.impl.embed.EmbedCreateCommand.java

License:Apache License

public DBObject buildCreateBody(MetaRelationship lastField, String parentPath, BsonEntity entity,
        int newVersion, MetaClass rootMetaClass, DBObject rootObject, String parentId) {
    BasicDBObject embedParentObject = (BasicDBObject) EmbedDBObjectFilter.filter(parentId, rootObject,
            rootMetaClass, null, helper);
    if (embedParentObject == null) {
        throw new CmsDalException(DalErrCodeEnum.ENTITY_NOT_FOUND,
                "Create, can not find embed field with Id: " + parentId);
    }//from ww  w  .j a  v  a2 s.c  o m

    embedParentObject.remove("_id");

    if (lastField.getCardinality() == CardinalityEnum.Many) {
        BasicDBObject obj = (BasicDBObject) embedParentObject.get(lastField.getDbName());
        BasicDBList valueList = null;
        if (obj != null) {
            valueList = (BasicDBList) obj.get(MetaField.VALUE_KEY);
        }

        if (valueList == null) {
            if (obj == null) {
                obj = new BasicDBObject();
                embedParentObject.put(lastField.getDbName(), obj);
            }
            valueList = new BasicDBList();
            valueList.add(entity.getNode());
            obj.put(FieldProperty.LENGTH.getDbName(), 1);
            obj.put(FieldProperty.TIMESTAMP.getDbName(), new Date());
            obj.put(MetaField.VALUE_KEY, valueList);
        } else {
            int size = valueList.size();
            valueList.add(entity.getNode());
            obj.put(FieldProperty.LENGTH.getDbName(), size + 1);
            obj.put(FieldProperty.TIMESTAMP.getDbName(), new Date());
            obj.put(MetaField.VALUE_KEY, valueList);
        }
    } else {
        DBObject vObj = new BasicDBObject();
        vObj.put(MetaField.VALUE_KEY, entity.getNode());
        embedParentObject.put(lastField.getDbName(), vObj);
    }

    BasicDBObject setModifyObject = new BasicDBObject();
    BasicDBObject obj = (BasicDBObject) rootObject.get(embedFieldName);
    if (obj == null) {
        throw new CmsDalException(DalErrCodeEnum.ENTITY_NOT_FOUND,
                "Create, can not find embed field with Id: " + this.entity.getId());
    }

    setModifyObject.put(embedFieldName, obj);
    BasicDBObject modifyBody = new BasicDBObject();
    modifyBody.put("$set", setModifyObject);

    // increase version on root document
    BasicDBObject versionObject = new BasicDBObject();
    versionObject.put(InternalFieldEnum.VERSION.getDbName(), 1);
    modifyBody.put("$inc", versionObject);

    buildRootUpdateObject(entity, null, modifyBody, rootMetaClass);

    return modifyBody;
}

From source file:com.ebay.cloud.cms.dal.persistence.impl.embed.EmbedDeleteCommand.java

License:Apache License

public DBObject buildDeleteBody(MetaRelationship metaField, String parentPath, String entityId, int newVersion,
        MetaClass rootMetaClass) {//from   ww w. ja v  a  2 s. c  om
    String embedPath = metaField.getValueDbName();
    String embedLengthPath = metaField.getDbName() + EntityIDHelper.DOT + FieldProperty.LENGTH.getDbName();
    if (!StringUtils.isNullOrEmpty(parentPath)) {
        embedPath = parentPath + EntityIDHelper.DOT + embedPath;
        embedLengthPath = parentPath + EntityIDHelper.DOT + embedLengthPath;
    }

    DBObject deleteBody = new BasicDBObject();
    if (metaField.getCardinality() == CardinalityEnum.Many) {
        // $pull this from array
        BasicDBObject idObject = new BasicDBObject();
        idObject.put(InternalFieldEnum.ID.getDbName(), entityId);
        BasicDBObject pullObject = new BasicDBObject();
        pullObject.put(embedPath, idObject);
        deleteBody.put("$pull", pullObject);

        DBObject decObject = new BasicDBObject();
        // maintain the _length value.
        decObject.put(embedLengthPath, -1);
        deleteBody.put("$inc", decObject);

        // root update object. 
        buildRootUpdateObject(entity, newVersion, deleteBody, rootMetaClass);
    } else {
        // $unset to remove this
        BasicDBObject unsetObject = new BasicDBObject();
        unsetObject.put(embedPath, 1);
        deleteBody.put("$unset", unsetObject);
        buildRootUpdateObject(entity, newVersion, deleteBody, rootMetaClass);
    }
    return deleteBody;
}

From source file:com.ebay.cloud.cms.dal.persistence.impl.embed.EmbedFieldModifyCommand.java

License:Apache License

@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
protected DBObject buildModifyBody(BitSet arrayBits, DBObject rootObject, MetaClass rootMetaClass) {
    BasicDBObject embedObject = (BasicDBObject) EmbedDBObjectFilter.filter(entity.getId(), rootObject,
            rootMetaClass, null, helper);

    MetaField field = getField();/*from   w  w w  .j a  v a  2 s .c o  m*/
    if (field.getCardinality() == CardinalityEnum.Many) {
        BasicDBObject enityObject = (BasicDBObject) getEntity().getNode();
        BasicDBObject fieldObject = (BasicDBObject) enityObject.get(field.getDbName());

        if (fieldObject != null) {
            List givenValue = (List) fieldObject.get(V);
            if (givenValue != null) {
                // merge with exsiting fields FIXME:: keep the same with RootFieldModifyCommand of using delta
                List targetFilterList = new ArrayList();
                BasicDBObject existingFieldObject = (BasicDBObject) embedObject.get(field.getDbName());
                if (existingFieldObject != null) {
                    BasicDBList list = (BasicDBList) existingFieldObject.get(V);
                    if (list != null) {
                        targetFilterList.addAll(list);
                    }
                }
                targetFilterList.addAll(givenValue);

                BasicDBList valueList = new BasicDBList();
                valueList.addAll(targetFilterList);

                DBObject obj = (DBObject) embedObject.get(field.getDbName());
                if (obj == null) {
                    obj = new BasicDBObject();
                    embedObject.put(field.getDbName(), obj);
                }

                obj.put(V, valueList);
                obj.put(FieldProperty.LENGTH.getDbName(), targetFilterList.size());
                obj.put(FieldProperty.TIMESTAMP.getDbName(), new Date());
            }
        }
    } else if (field.getDataType().equals(DataTypeEnum.JSON)) {
        // incremental $set
        // buildJsonBody(parentPath, modifyBody);
        BasicDBObject enityObject = (BasicDBObject) getEntity().getNode();
        BasicDBObject fieldObject = (BasicDBObject) enityObject.get(field.getDbName());
        if (fieldObject != null) {
            DBObject obj = (DBObject) embedObject.get(field.getDbName());
            if (obj == null) {
                obj = new BasicDBObject();
                embedObject.put(field.getDbName(), obj);
            }
            DBObject valueObj = (DBObject) obj.get(V);
            if (valueObj == null) {
                valueObj = new BasicDBObject();
                obj.put(V, valueObj);
            }

            BasicDBObject givenValue = (BasicDBObject) (fieldObject).get(V);
            if (givenValue != null) {
                for (String key : givenValue.keySet()) {
                    valueObj.put(key, givenValue.get(key));
                }
                valueObj.put(FieldProperty.TIMESTAMP.getDbName(),
                        getEntity().getFieldTimestamp(field.getName()));
            }
        }

    } else {
        // non-array: replace the whole field
        BasicDBObject enityObject = (BasicDBObject) getEntity().getNode();
        BasicDBObject fieldObject = (BasicDBObject) enityObject.get(field.getDbName());
        embedObject.put(field.getDbName(), fieldObject);
        // buildSetFieldBody(parentPath, modifyBody);
    }

    embedObject.put(InternalFieldEnum.MODIFIER.getDbName(), entity.getModifier());
    embedObject.put(InternalFieldEnum.LASTMODIFIED.getDbName(), entity.getLastModified());

    return buildSetBody(rootObject);
}

From source file:com.ebay.cloud.cms.dal.persistence.impl.root.RootFieldModifyCommand.java

License:Apache License

private void buildArrayBody(DBObject modifyBody) {
    MetaField field = getField();//from   w w  w.  j a  v  a  2s .c  o m
    BasicDBObject enityObject = (BasicDBObject) getEntity().getNode();
    BasicDBObject fieldObject = (BasicDBObject) enityObject.get(field.getDbName());

    if (fieldObject != null) {
        Object givenValue = (fieldObject).get(V);
        if (givenValue != null) {
            BasicDBObject eachDbo = new BasicDBObject();
            eachDbo.put("$each", givenValue);

            BasicDBObject addToSetDbo = new BasicDBObject();
            addToSetDbo.put(field.getValueDbName(), eachDbo);

            modifyBody.put("$addToSet", addToSetDbo);

            // field length, only update when we do have updates
            BasicDBObject inc = (BasicDBObject) modifyBody.get("$inc");
            inc.put(field.getDbName() + DOT + FieldProperty.LENGTH.getDbName(),
                    getEntity().getFieldLength(fieldName));
            // field time stamp
            BasicDBObject set = (BasicDBObject) modifyBody.get("$set");
            set.put(field.getDbName() + DOT + FieldProperty.TIMESTAMP.getDbName(),
                    getEntity().getFieldTimestamp(fieldName));
        }
    }

}

From source file:com.ebay.cloud.cms.dal.persistence.impl.root.RootGetCommand.java

License:Apache License

private static DBObject buildGetRootQuery(String entityId, String branchId, MetaClass metadata,
        boolean needActive, PersistenceContext context) {
    DBObject rootQueryObject = new BasicDBObject();
    rootQueryObject.put(InternalFieldEnum.ID.getDbName(), entityId);
    if (needActive) {
        rootQueryObject.put(InternalFieldEnum.STATUS.getDbName(), StatusEnum.ACTIVE.toString());
    }//from   ww w .  j  av a  2  s .  co m
    rootQueryObject.put(InternalFieldEnum.BRANCH.getDbName(), branchId);

    // add read filter
    return addContextCriteria(metadata, context, rootQueryObject);
}

From source file:com.ebay.cloud.cms.dal.persistence.impl.root.RootReplaceCommand.java

License:Apache License

@Override
public void execute(PersistenceContext context) {
    DBObject getResult = RootGetCommand.findDBObject(entity.getId(), entity.getBranchId(), context,
            entity.getMetaClass(), ROOT_FIELDS, false);
    if (getResult != null) {
        // check version
        int currentVersion = (Integer) getResult.get(InternalFieldEnum.VERSION.getDbName());
        int version = entity.getVersion();
        if ((version != IEntity.NO_VERSION) && (currentVersion != version)) {
            throw new CmsDalException(DalErrCodeEnum.VERSION_CONFLICT, "current version is " + currentVersion
                    + ", but version in repalce body is " + version + "! entity is " + entity.toString());
        }/*from   ww  w  .  j a va2  s.com*/

        Date createTime = (Date) getResult.get(InternalFieldEnum.CREATETIME.getDbName());

        DBObject queryObject = buildReplaceRootQuery(currentVersion);
        DBObject updateObject = buildReplaceRootUpdate(currentVersion, createTime);
        try {
            WriteResult result = MongoExecutor.update(context, entity.getMetaClass(), queryObject,
                    updateObject);
            if (result.getN() == 0) {
                throw new CmsDalException(DalErrCodeEnum.VERSION_CONFLICT,
                        "current version is not " + currentVersion);
            }
            //set version for response
            entity.setVersion(currentVersion + 1);
        } catch (RuntimeException e) {
            entity.setVersion(currentVersion);
            throw e;
        } catch (Throwable t) {
            //if anything bad happens, need to set version back
            entity.setVersion(currentVersion);
        } finally {
            //in update scenario, have to set id value back into entity object because we
            //removed id field before
            entity.setId(entity.getId());
        }
    } else {
        // insert

        //2012/7/13 jianxu1 multi threading issue, if client A and client B send replace at same time
        //at T1, none of A and B find existing entity, so at T2, both A and B call insert, of we do not have 
        //unique index for combination of _branchId and _oid, we end up with duplicated entities.
        //FIX is: http://www.mongodb.org/display/DOCS/Indexes,  composite unique index
        //db.branches.ensureIndex({_branchId: 1, _oid: 1}, {unique: true});
        //TODO: change create repository to add composite unique index for branches, for main branch, we just need unique index on _oid

        DBObject insertObject = entity.getNode();
        insertObject.removeField("_id");
        insertObject.put(InternalFieldEnum.VERSION.getDbName(), IEntity.START_VERSION);
        MongoExecutor.insert(context, entity.getMetaClass(), insertObject);
    }
}

From source file:com.ebay.cloud.cms.dal.persistence.MongoExecutor.java

License:Apache License

public static void dropIndex(PersistenceContext context, MetaClass metadata, String indexName) {
    long start = System.currentTimeMillis();
    String msg = "success";
    DBCollection dbCollection = context.getDBCollection(metadata);
    try {//from  w  w w  . j  a va  2 s  .c o m
        dbCollection.dropIndex(indexName);
    } catch (Throwable t) {
        msg = t.getMessage();
        handleMongoException(t);
    } finally {
        DBObject dropDbo = new BasicDBObject();
        dropDbo.put("indexname", indexName);
        logMongoAction(context, "dropIndex", start, dbCollection, dropDbo, null, null, null, msg);
    }
}

From source file:com.ebay.cloud.cms.dal.persistence.MongoExecutor.java

License:Apache License

public static AggregationOutput aggregate(PersistenceContext context, MetaClass metadata, DBObject firstObject,
        DBObject... aggrObjects) {/*from   w ww.j a  v  a 2s  .  c o  m*/
    long start = System.currentTimeMillis();
    String msg = "success";
    DBCollection dbCollection = context.getDBCollection(metadata);
    AggregationOutput output = null;
    try {
        output = dbCollection.aggregate(firstObject, aggrObjects);
        if (!output.getCommandResult().ok()) {
            throw new CmsDalException(DalErrCodeEnum.AGGREGATION_FAILED,
                    output.getCommandResult().getErrorMessage());
        }
    } catch (Throwable t) {
        msg = t.getMessage();
        handleMongoException(t);
    } finally {
        DBObject followingOjbect = new BasicDBObject();
        followingOjbect.put("following aggreate operations: ", aggrObjects);
        logMongoAction(context, "aggregate", start, dbCollection, firstObject, followingOjbect, null, null,
                msg);
    }
    return output;
}

From source file:com.ebay.cloud.cms.dal.search.impl.criteria.AbstractFieldCriteriaHandler.java

License:Apache License

/**
 * Build query objects//from   w w  w .j a  va  2 s . c  om
 * 
 * @param criteria
 * @param query
 * @param atomQueryObject
 * @param checkFieldArray -- when the field on the criteria, decide to use $elemMatch or not. A couple of 
 */
protected void buildCriteria(FieldSearchCriteria criteria, DBObject query, DBObject atomQueryObject) {
    String fullDbName = criteria.getFullDbName();
    ISearchField searchField = criteria.getSearchField();
    if (!(searchField instanceof AbstractSearchField)) {
        // GroupField : won't be array
        // AggregationField : won't be array
        query.put(fullDbName, atomQueryObject);
        return;
    }

    // AbstractSearchField
    AbstractSearchField asf = (AbstractSearchField) criteria.getSearchField();
    MetaField metaField = asf.getRootField();
    // inner property is an primitive type
    // embed handling : FIXME:: what about multiple layer of embedded(MANY)? We support only one layer of array for now
    String eleMatchName = asf.getRootFieldDbName();
    String innerField = asf.getInnerField();
    // 1. embed many
    if (criteria.isEmbeddedCardinalityMany() && criteria.isEmbeddedObject() && asf.getInnerProperty() == null) {
        // embed array
        String embedPath = asf.getEmbedPath();
        String parentPath = embedPath.substring(0, embedPath.length() - 1);
        String key = asf.getRootFieldDbName();
        if (useElemMatchName()) {
            key = asf.getRootFieldElemMatchDbName();
        }
        query.put(parentPath, new BasicDBObject("$elemMatch", new BasicDBObject(key, atomQueryObject)));
        return;
    }

    // 2. for cardinality=MANY case
    if (useArrayElemMatch() && asf.getInnerProperty() == null
            && metaField.getCardinality() == CardinalityEnum.Many) {
        if (criteria.isEmbeddedObject()) {
            String embedPath = asf.getEmbedPath();
            eleMatchName = embedPath + asf.getRootFieldDbName();
        }
        // add $elemMatch query object
        if (innerField == null) {
            query.put(eleMatchName, new BasicDBObject("$elemMatch", atomQueryObject));
        } else {
            query.put(eleMatchName,
                    new BasicDBObject("$elemMatch", new BasicDBObject(innerField, atomQueryObject)));
        }
        return;
    }

    // 3. if not array handling, this is the default behavior
    query.put(fullDbName, atomQueryObject);
}

From source file:com.ebay.cloud.cms.dal.search.impl.criteria.EqualityCriteriaHandler.java

License:Apache License

@Override
public DBObject translate(final FieldSearchCriteria criteria) {
    DBObject query = new BasicDBObject();
    FieldOperatorEnum op = criteria.getOperator();
    switch (op) {
    case EQ:/*  w  w  w.j a v  a2  s .co  m*/
        //                // FIXME:: Wrapp the dbo, since there might be $elemMatch outside. There no $eq operator, use $in instead.
        //                DBObject dbo = new BasicDBObject("$in", Arrays.asList(criteria.getValue()));
        //                buildCriteria(criteria, query, dbo);
        query.put(criteria.getFullDbName(), criteria.getValue());
        break;
    case NE:
        // wrapper elemMatch if any
        buildCriteria(criteria, query, new BasicDBObject("$ne", criteria.getValue()));
        // add exists=false for array
        query = buildNegativeArrayCriteria(criteria, query);
        break;
    default:
        throw new IllegalArgumentException("Unsupport comparision operator: " + op);
    }
    return query;
}