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.dalapi.persistence.impl.embed.AbstractEmbedCommand.java

License:Apache License

protected void buildRootUpdateObject(BsonEntity entity, Integer newVersion, DBObject updateBody,
        MetaClass rootMetaClass) {//  w  w w  .  j a  v a 2 s  .  co m
    BasicDBObject setObject = (BasicDBObject) updateBody.get("$set");
    if (setObject == null) {
        setObject = new BasicDBObject();
    }

    // populate the data to the root entity for the internal fields
    if (newVersion != null) {
        setObject.put(InternalFieldEnum.VERSION.getDbName(), newVersion);
    }
    setObject.put(InternalFieldEnum.MODIFIER.getDbName(), entity.getModifier());
    setObject.put(InternalFieldEnum.LASTMODIFIED.getDbName(), entity.getLastModified());
    setObject.put(InternalFieldEnum.STATUS.getDbName(), StatusEnum.ACTIVE.toString());
    setObject.put(InternalFieldEnum.BRANCH.getDbName(), entity.getBranchId());
    setObject.put(InternalFieldEnum.TYPE.getDbName(), rootMetaClass.getName());
    String rootId = helper.getRootId(entity.getId());
    setObject.put(InternalFieldEnum.ID.getDbName(), rootId);

    setInternalField(entity, setObject, InternalFieldEnum.COMMENT);
    setInternalField(entity, setObject, InternalFieldEnum.USER);

    updateBody.put("$set", setObject);
}

From source file:com.ebay.cloud.cms.dalapi.persistence.impl.IndexBuildCommand.java

License:Apache License

private DBObject buildIndexOptionObject(IndexInfo index) {
    DBObject optionsObject = new BasicDBObject();
    for (IndexOptionEnum option : index.getIndexOptions()) {
        optionsObject.put(option.name(), true);
    }//from   ww  w . j  av a  2s  .  com
    optionsObject.put("name", index.getIndexName());
    return optionsObject;
}

From source file:com.ebay.cloud.cms.dalapi.persistence.impl.IndexBuildCommand.java

License:Apache License

private DBObject buildIndexKeyObject(MetaClass metadata, IndexInfo index, boolean onMainBranch) {
    DBObject keyObject = new BasicDBObject();
    // in sharded case. sharding key must be prefix of the unique key
    boolean unique = index.getIndexOptions().contains(IndexOptionEnum.unique);
    boolean hashed = index.getIndexOptions().contains(IndexOptionEnum.hashed);
    if (unique && metadata.isMetaSharded()) {
        keyObject.put(InternalFieldEnum.SHARD_KEY.getDbName(), 1);
    }/*from   w  ww  . ja  va2 s. c o m*/
    for (String key : index.getKeyList()) {
        String[] keySeg = key.split("\\.");
        StringBuilder sb = new StringBuilder();
        getKeyName(metadata, keySeg, 0, sb);
        keyObject.put(sb.toString(), hashed ? "hashed" : 1);
    }

    //since objects in different sub branches are in the same collection, 
    // need to add the branch id into the index.
    // so the objects on different sub branches will not conflict on "unique index"  
    if (!onMainBranch) {
        keyObject.put(InternalFieldEnum.BRANCH.getDbName(), 1);
    }

    return keyObject;
}

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

License:Apache License

private void buildArrayBody(DBObject modifyBody) {
    MetaField field = getField();//from   w  w  w  .j  a v  a2  s . co  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("$set");
            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.dalapi.persistence.impl.root.RootGetCommand.java

License:Apache License

private static DBObject buildGetRootQuery(String entityId, String branchId, boolean needActive) {
    DBObject rootQueryObject = new BasicDBObject();
    rootQueryObject.put(InternalFieldEnum.ID.getDbName(), entityId);
    if (needActive) {
        rootQueryObject.put(InternalFieldEnum.STATUS.getDbName(), StatusEnum.ACTIVE.toString());
    }// w  ww  .j ava  2s .  c om
    rootQueryObject.put(InternalFieldEnum.BRANCH.getDbName(), branchId);
    return rootQueryObject;
}

From source file:com.ebay.cloud.cms.dalapi.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);
        }//from   w w  w .jav a 2 s  .  c o  m

        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.metadata.mongo.MongoMetadataServiceImpl.java

License:Apache License

private void innerDeleteMetaClass(MetaClass metaClass) {
    DBObject obj = new BasicDBObject();
    obj.put(MetaClass.NAME, metaClass.getName());

    collection.remove(obj);/*w  w w.  j a  va 2 s  .  c  om*/

    cacheManager.deleteMetaClassFromCache(metaClass);
    graph.deleteMetaClass(metaClass);
}

From source file:com.ebay.cloud.cms.metadata.mongo.MongoMetadataServiceImpl.java

License:Apache License

private MetaClass innerDropMetaField(MetaClass metaClass, String fieldName) {
    DBObject queryObj = new BasicDBObject();
    queryObj.put(MetaClass.NAME, metaClass.getName());

    // delete the field with given field name
    DBObject updateObj = new BasicDBObject();
    BasicDBObject ups = new BasicDBObject();
    ups.put("fields." + fieldName, "");
    updateObj.put(MongoOperand.unset, ups);

    BasicDBObject versionObject = new BasicDBObject();
    versionObject.put("version", 1);
    updateObj.put(MongoOperand.inc, versionObject);

    collection.update(queryObj, updateObj);

    cacheManager.deleteMetaClassFromCache(metaClass);
    MetaClass result = getMetaClass(metaClass.getName());
    graph.updateMetaClass(result);/*from w w w  . ja  v a2 s  . c  om*/
    return result;
}

From source file:com.ebay.cloud.cms.metadata.mongo.MongoRepositoryServiceImpl.java

License:Apache License

@Override
public void updateRepository(Repository repo) {
    CheckConditions.checkNotNull(repo, "repository can not be null");
    CheckConditions.checkNotNull(repo.getRepositoryName(), "repository name can not be null");
    String repositoryName = repo.getRepositoryName();
    try {/*  ww  w. j  a v a  2  s .c  o m*/
        metadataLock.lock();
        DBObject qryDbo = new BasicDBObject();
        qryDbo.put(Repository.REPOSITORY_FIELD_NAME, repositoryName);
        // only support admin change now
        DBObject updateDbo = new BasicDBObject();
        DBObject setDbo = new BasicDBObject();
        if (repo.getRepositoryAdmin() != null) {
            setDbo.put(Repository.REPOSITORY_FIELD_ADMIN_NAME, repo.getRepositoryAdmin());
            setDbo.put(Repository.REPOSITORY_FIELD_TYPE_NAME, repo.getAccessType().name());
        }
        if (repo.getOptions() != null) {
            setDbo.put(Repository.REPOSITORY_FIELD_OPTIONS_NAME,
                    repositoryOptionConverter.toBson(repo.getOptions()));
        }
        if (!setDbo.keySet().isEmpty()) {
            updateDbo.put("$set", setDbo);
            WriteResult result = repoCollection.update(qryDbo, updateDbo);
            if (result.getN() != 1) {
                throw new RepositoryNotExistsException(repositoryName);
            }
        }
        refreshRepositoryCache();
    } catch (InterruptedException e) {
        logger.info("lock interrupted for createRepository " + repositoryName);
        throw new MetaDataException(MetaErrCodeEnum.LOCK_INTERRUPTED,
                "lock interrupted for createRepository " + repositoryName, e);
    } finally {
        metadataLock.unlock();
    }
}

From source file:com.ebay.oss.bark.service.DqModelServiceImpl.java

License:Apache License

@Override
public int deleteModel(String name) throws BarkDbOperationException {
    try {/*from   w  w  w .j  a v  a  2 s  .  c  om*/
        DqModel dqModel = dqModelRepo.findByName(name);

        // TODO need to mark related metrics as deleted, instead of real deletion
        // markMetricsDeleted(dqModel);

        dqModelRepo.delete(dqModel.get_id());

        if (dqModel.getModelType() == ModelType.ACCURACY) {
            scheduleRepo.deleteByModelList(name);
        } else if (dqModel.getModelType() == ModelType.VALIDITY) {
            DBObject currentSchedule = scheduleRepo.getValiditySchedule(dqModel.getAssetId());
            if (currentSchedule == null || currentSchedule.get("modelList") == null) {
                return -1;
            }

            String rawModelList = currentSchedule.get("modelList").toString();
            String newModelList = "";
            if (rawModelList.contains(ScheduleModelSeperator.SEPERATOR)) {
                String[] rawModelArray = rawModelList.split(ScheduleModelSeperator.SPLIT_SEPERATOR);
                for (int i = 0; i < rawModelArray.length; i++) {
                    if (!rawModelArray[i].equals(name))
                        newModelList = newModelList + ScheduleModelSeperator.SEPERATOR + rawModelArray[i];
                }
                newModelList = newModelList.substring(ScheduleModelSeperator.SEPERATOR.length());
                currentSchedule.put("modelList", newModelList);
                scheduleRepo.updateModelType(currentSchedule, dqModel.getModelType());

            } else if (rawModelList.equals(name)) {
                scheduleRepo.deleteByModelList(name);
            }
        }

        return 0;
    } catch (Exception e) {
        logger.warn(e.toString());
        throw new BarkDbOperationException("Failed to delete model of '" + name + "'", e);
    }
}