Java 类com.mongodb.DBRef 实例源码

项目:restfiddle    文件:EntityDataController.java   
private void dbRefToRelation(DBObject dbObject) {
if (dbObject == null) {
    return;
}
if (dbObject.containsField("_id")) 
    dbObject.put("_id", ((ObjectId) dbObject.get("_id")).toHexString());
for (String key : dbObject.keySet()) {
    Object obj = dbObject.get(key);
    if (obj instanceof DBRef) {
    DBRef ref = (DBRef) obj;
    dbObject.put(key, dbRefToRel(ref));
    } else if (obj instanceof DBObject) {
    dbRefToRelation((DBObject) obj);
    }
}

   }
项目:restfiddle    文件:EntitySessionController.java   
private void dbRefToRelation(DBObject dbObject) {
if (dbObject == null) {
    return;
}
if (dbObject.containsField("_id")) 
    dbObject.put("_id", ((ObjectId) dbObject.get("_id")).toHexString());
for (String key : dbObject.keySet()) {
    Object obj = dbObject.get(key);
    if (obj instanceof DBRef) {
    DBRef ref = (DBRef) obj;
    dbObject.put(key, dbRefToRel(ref));
    } else if (obj instanceof DBObject) {
    dbRefToRelation((DBObject) obj);
    }
}

   }
项目:FindMe_Server    文件:UserDaoImpl2Mongo.java   
@Override
public List<Map<String, Object>> queryUserFriendList(String userId) {
    // TODO Auto-generated method stub
    BasicDBObject column = new BasicDBObject("userFriend", 1);
    Map<String, Object> user = super.findOneById(userId, column);
    BasicDBList friendList = (BasicDBList) user.get("userFriend");
    List<Map<String, Object>> friends = new ArrayList<Map<String, Object>>();
    for (int i = 0; i < friendList.size(); i++) {
        DBRef friend = (DBRef) friendList.get(i);
        DBObject friendObj = friend.fetch();
        Map<String, Object> fre = new HashMap<String, Object>();
        fre.put("_id", friendObj.get("_id"));
        fre.put("userNickName", friendObj.get("userNickName"));
        fre.put("userPhoto", friendObj.get("userPhoto"));
        fre.put("userSignature", friendObj.get("userSignature"));
        // System.out.println(fre);
        friends.add(fre);
    }

    return friends;
}
项目:FindMe_Server    文件:UserDaoImpl2Mongo.java   
@Override
public boolean insertUserFans(String girlId, String boyId) {
    // TODO Auto-generated method stub

    DB db = MongoDBUtil.getDB();
    BasicDBObject girl = new BasicDBObject();
    girl.put("_id", girlId);

    DBRef boyDbRef = new DBRef(db, "user", boyId);

    BasicDBObject update = new BasicDBObject();
    update.put("user", boyDbRef);
    update.put("isPass", 0);

    DBCollection users = db.getCollection(userCollection);

    WriteResult res = users.update(girl, new BasicDBObject("$addToSet",
            new BasicDBObject("userFans", update)), false, true);

    return res.getN() > 0 ? true : false;
}
项目:FindMe_Server    文件:UserDaoImpl2Mongo.java   
@Override
public boolean insertUserBoyMatch(String boyId, String girlId) {
    // TODO Auto-generated method stub

    DB db = MongoDBUtil.getDB();
    BasicDBObject boy = new BasicDBObject();
    boy.put("_id", boyId);
    DBRef girlDbRef = new DBRef(db, "user", girlId);

    BasicDBObject update = new BasicDBObject();
    update.put("user", girlDbRef);
    update.put("isPass", 0);

    DBCollection users = db.getCollection(userCollection);

    WriteResult res = users.update(boy, new BasicDBObject("$addToSet",
            new BasicDBObject("userMatch", update)), false, true);

    return res.getN() > 0 ? true : false;
}
项目:FindMe_Server    文件:TestMain.java   
public void query() {
    DB db = MongoDBUtil.getDB();
    DBCollection connection = db.getCollection("user");
    BasicDBObject user = new BasicDBObject();
    // ReadPreference preference = ReadPreference.valueOf("$ref");
    user.put("_id", "2014062710281828268456656");
    DBObject obj = connection.findOne(user);
    // DBRefBase base = new DBRefBase(db, "post",
    // "2014062509521826635294167");
    // DBObject a = base.fetch();
    DBRef b = (DBRef) obj.get("post");
    DBObject a = b.fetch();
    // Object b = obj.get("post");
    System.out.println(a);
    System.out.println(obj.toMap());
}
项目:liveoak    文件:RootMongoResource.java   
@Override
protected DBRef getDBRef(String uri) throws ResourceProcessingException {
    if (uri != null) {
        String rootURI = this.uri().toString();
        if (uri.startsWith(rootURI + "/")) {

            String resourcePath = uri.substring(rootURI.length());
            String[] paths = resourcePath.split("/");

            if (paths.length != 3) {
                throw new ResourceProcessingException("$DBRefs must be in the format /rootContextPath/collectionName/resourceID");
            } else {
                String collectionName = paths[1];
                String resourceID = paths[2];
                return new DBRef(this.db(), collectionName, resourceID);
            }

        } else {
            throw new ResourceProcessingException("$DBRefs are only supported under the same context root. URL specified ('" + uri + "')should start with " + rootURI
                    + ".");
        }
    } else {
        throw new ResourceProcessingException("$DBRefs must be URL, they cannot be null.");
    }
}
项目:liveoak    文件:MongoBaseObjectResource.java   
@Override
public Resource member(RequestContext ctx, String id) throws Exception {
    Object object = getDBObject().get(id);

    if (object == null) {
        return null;
    }

    if (object != null) {
        if (object instanceof BasicDBObject || object instanceof BasicDBList) {
            return null;
        } else if (object instanceof DBRef) {
            // TODO In case of exception make sure it results in InvalidRequest
            //try {
                return getResource((DBRef) object, ctx.returnFields().child(id).isEmpty());
            //} catch (ResourceProcessingException e) {
            //    responder.invalidRequest(e.getMessage());
            //}
        } else {
            throw new RuntimeException("ERROR: Object type (" + object.getClass() + ") not recognized");
        }
    }
    return null;
}
项目:liveoak    文件:MongoObjectResource.java   
@Override
public Resource member(RequestContext ctx, String id) throws Exception {
    Object object = getDBObject().get(id);
    if (object != null) {
        if (object instanceof BasicDBObject || object instanceof BasicDBList) {
            return null;
        } else if (object instanceof DBRef) {
            //try {
            // TODO throw exception that will end up as InvalidRequest
            return getResource((DBRef) object, ctx.returnFields().child(id).isEmpty());
            //} catch (ResourceProcessingException e) {
            //    responder.invalidRequest(e.getMessage());
            //}
        } else {
            // TODO throw exception that will end up as InternalError
            //responder.internalError("ERROR: Object type (" + object.getClass() + ") not recognized");
            throw new RuntimeException("ERROR: Object type (" + object.getClass() + ") not recognized");
        }
    }
    return null;
}
项目:liveoak    文件:MongoObjectResource.java   
@Override
public Map<String, ?> properties(RequestContext ctx) throws Exception {
    // TODO: only read properties specified in the return fields and not everything
    Map<String, Object> result = new HashMap<>();
    Set<String> keys = getDBObject().keySet();
    for (String key : keys) {
        if (!key.equals(MONGO_ID_FIELD) && !key.equals(LiveOak.ID)) {
            Object value = getDBObject().get(key);
            if (value instanceof BasicDBObject) {
                value = new MongoEmbeddedObjectResource(this, (DBObject) value);
            } else if (value instanceof BasicDBList) {
                value = getResourceCollection(value);
            } else if (value instanceof DBRef) {
                value = getResource((DBRef) value, ctx.returnFields().child(key).isEmpty());
            }

            if (supportedObject(value)) {
                result.put(key, value);
            } else {
                log.warn("Unsupported Property type " + value.getClass() + " cannot encode.");
            }
        }
    }
    return result;
}
项目:liveoak    文件:MongoObjectResource.java   
protected Object getResourceCollection(Object object) throws Exception {
    if (object instanceof BasicDBObject) {
        return new MongoEmbeddedObjectResource(this, (DBObject) object);
    } else if (object instanceof BasicDBList) {
        BasicDBList dbList = ((BasicDBList) object);
        ArrayList list = new ArrayList();
        for (int i = 0; i < dbList.size(); i++) {
            Object child = dbList.get(i);
            list.add(getResourceCollection(child));
        }
        return list;
    } else if (object instanceof DBRef) {
        return getResource((DBRef) object, true);
    } else {
        return object;
    }
}
项目:enviroCar-server    文件:MongoStatisticsDao.java   
private DBObject matches(StatisticsFilter request) {
    BasicDBObjectBuilder b = new BasicDBObjectBuilder();
    BasicDBObjectBuilder match = b.push(Ops.MATCH);
    if (request.hasTrack()) {
        DBRef track = mongoDB.ref(request.getTrack());
        match.add(MongoMeasurement.TRACK, track);
    }
    if (request.hasUser()) {
        DBRef user = mongoDB.ref(request.getUser());
        match.add(MongoMeasurement.USER, user);
    }
    if (request.hasSensor()) {
        MongoSensor sensor = (MongoSensor) request.getSensor();
        match.add(SENSOR_ID_PATH, sensor.getId());
    }
    return b.get();
}
项目:morphia    文件:Mapper.java   
/**
 * Converts a Key to a DBRef
 *
 * @param key the Key to convert
 * @return the DBRef
 */
public DBRef keyToDBRef(final Key key) {
    if (key == null) {
        return null;
    }
    if (key.getType() == null && key.getCollection() == null) {
        throw new IllegalStateException("How can it be missing both?");
    }
    if (key.getCollection() == null) {
        key.setCollection(getCollectionName(key.getType()));
    }

    Object id = key.getId();
    if (isMapped(id.getClass())) {
        id = toMongoObject(id, true);
    }
    return new DBRef(key.getCollection(), id);
}
项目:morphia    文件:KeyConverter.java   
@Override
public Object decode(final Class targetClass, final Object o, final MappedField optionalExtraInfo) {
    if (o == null) {
        return null;
    }
    if (!(o instanceof DBRef)) {
        throw new ConverterException(String.format("cannot convert %s to Key because it isn't a DBRef", o.toString()));
    }


    DBRef ref = (DBRef) o;

    MappedField actualType = getActualType(optionalExtraInfo);


    final Class<?> keyType = actualType != null
                             ? actualType.getConcreteType()
                             : getMapper().getClassFromCollection(ref.getCollectionName());

    final Key<?> key = new Key<Object>(keyType, ref.getCollectionName(), ref.getId());

    return key;
}
项目:teiid    文件:MergeDetails.java   
public DBRef getDBRef(DB db, boolean push) {
    if (this.id != null) {
        if (this.idReference != null) {
            return new DBRef(db, push?this.parentTable:this.embeddedTable, new DBRef(db, this.idReference, this.id.getValue()));
        }
        return new DBRef(db, push?this.parentTable:this.embeddedTable, this.id.getValue());
    }
    return null;
}
项目:teiid    文件:MongoDocument.java   
public DBObject getEmbeddedDocument(DB mongoDB, String docName) {
    for (MergeDetails ref:this.embeddedKeys) {
        if (ref.getName().equals(docName)) {
            DBRef dbRef = ref.getDBRef(mongoDB, false);
            if (dbRef != null) {
                return mongoDB.getCollection(dbRef.getRef()).findOne(new BasicDBObject("_id", dbRef.getId())); //$NON-NLS-1$
            }
        }
    }
    return null;
}
项目:teiid    文件:ExpressionEvaluator.java   
private Object getRowValue(Expression obj) throws TranslatorException {
    if (!(obj instanceof ColumnReference)) {
        throw new TranslatorException(MongoDBPlugin.Util.gs(MongoDBPlugin.Event.TEIID18017));
    }
    ColumnReference column = (ColumnReference)obj;

    Object value = null;
    if (MongoDBSelectVisitor.isPartOfPrimaryKey(column.getTable().getMetadataObject(), column.getName())) {
        // this is true one to many case
        value = this.row.get("_id"); //$NON-NLS-1$
        if (value == null) {
            value = getValueFromRowInfo(column, value);
        }
    }
       if (value == null && MongoDBSelectVisitor.isPartOfForeignKey(column.getTable().getMetadataObject(), column.getName())) {
           value = getValueFromRowInfo(column, value);          
    }
    if (value == null) {
        value = this.row.get(column.getName());
    }
    if (value instanceof DBRef) {
        value = ((DBRef)value).getId();
    }
    if (value instanceof DBObject) {
        value = ((DBObject) value).get(column.getName());
    }       
    return this.executionFactory.retrieveValue(value, column.getType(), this.mongoDB, column.getName(), column.getName());
}
项目:bugu-mongo    文件:ReferenceUtil.java   
public static String fromDbReference(Ref ref, Object value){
    String result;
    if(ref.reduced()){
        result = value.toString();
    }else{
        DBRef dbRef = (DBRef)value;
        result = dbRef.getId().toString();
    }
    return result;
}
项目:bugu-mongo    文件:ReferenceUtil.java   
public static String fromDbReference(RefList refList, Object value){
    String result;
    if(refList.reduced()){
        result = value.toString();
    }else{
        DBRef dbRef = (DBRef)value;
        result = dbRef.getId().toString();
    }
    return result;
}
项目:restfiddle    文件:EntityDataController.java   
private void relationToDBRef(DBObject dbObject, String projectId) {
for (String key : dbObject.keySet()) {
    Object obj = dbObject.get(key);
    if (obj instanceof DBObject) {
    DBObject doc = (DBObject) obj;
    if (doc.containsField("_rel")) {
        DBObject relation = (DBObject) doc.get("_rel");
        dbObject.put(key, new DBRef(projectId + "_" + (String) relation.get("entity"), new ObjectId((String) relation.get("_id"))));
    } else {
        relationToDBRef(doc, projectId);
    }
    }
}
   }
项目:restfiddle    文件:EntitySessionController.java   
@RequestMapping(value = "/api/{projectId}/entities/login", method = RequestMethod.POST, headers = "Accept=application/json", consumes = "application/json")
   public @ResponseBody
   String createEntityData(@PathVariable("projectId") String projectId,
    @RequestBody Object userDTO) {
DBObject data;
if (!(userDTO instanceof Map)) {
    return null;
} 

JSONObject response = new JSONObject();

Map map = (Map) userDTO;
JSONObject jsonObj = new JSONObject(map);
try {
    data = authService.authenticate(jsonObj, projectId);
} catch (Exception e) {
    response.put("msg", e.getMessage());
    return response.toString(4);
}
DBCollection userCollection = mongoTemplate.getCollection(projectId + "_User");

DBObject user = userCollection.findOne(((DBRef)(data.get("user"))).getId());
user.removeField("password");
data.put("user", user);

dbRefToRelation(data);
data.put("authToken", data.get("_id"));
data.removeField("_id");
data.removeField("expireAt");
String json = data.toString();

// Indentation
response = new JSONObject(json);
return response.toString(4);
   }
项目:restfiddle    文件:EntityAuthService.java   
public DBObject authenticate(JSONObject userDTO, String projectId) throws Exception{

DBCollection dbCollection = mongoTemplate.getCollection(projectId+"_User");

BasicDBObject query = new BasicDBObject();
query.append("username", userDTO.get("username"));

DBObject user = dbCollection.findOne(query);
if(user == null){
    throw new Exception("User not found");
}

BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
BasicDBObject auth;
if(encoder.matches((String)userDTO.get("password"),(String)user.get("password"))){
    auth = new BasicDBObject();
    auth.append("user", new DBRef(projectId+"_User",user.get( "_id" ))).append("expireAt", new Date(System.currentTimeMillis() + 3600 * 1000));
    auth.put("projectId", projectId);

    DBCollection dbCollectionAuth = mongoTemplate.getCollection(ENTITY_AUTH);
    dbCollectionAuth.insert(auth);
}else{
   throw new Exception("Invalid password");
}

return auth;
   }
项目:FindMe_Server    文件:UserDaoImpl2Mongo.java   
@Override
public boolean addFriend(String userId, String likeUserId) {
    // TODO Auto-generated method stub

    DB db = MongoDBUtil.getDB();
    DBCollection users = db.getCollection(userCollection);

    BasicDBObject user = new BasicDBObject("_id", userId);
    DBRef friendREF = new DBRef(db, userCollection, likeUserId);
    BasicDBObject friend = new BasicDBObject("userFriend", friendREF);

    boolean flag = false;
    // userId用户添加likeUserId用户好友
    WriteResult result = users.update(user, new BasicDBObject("$push",
            friend), false, true);
    int i = result.getN();

    if (i > 0) {
        BasicDBObject user2 = new BasicDBObject("_id", likeUserId);
        DBRef friendREF2 = new DBRef(db, userCollection, userId);
        BasicDBObject friend2 = new BasicDBObject("userFriend", friendREF2);
        // likeUserId用户添加userId用户好友
        result = users.update(user2, new BasicDBObject("$push", friend2),
                false, true);
        i = result.getN();
        if (i > 0)
            flag = true;
    }
    return flag;
}
项目:FindMe_Server    文件:UserDaoImpl2Mongo.java   
@SuppressWarnings("unchecked")
@Override
public Map<String, Object> queryPushUser(String sort) {
    // TODO Auto-generated method stub
    DB db = MongoDBUtil.getDB();
    DBCollection users = db.getCollection("puser");

    BasicDBObject user = new BasicDBObject("sort", Integer.parseInt(sort));

    DBObject u = users.findOne(user);
    DBRef puser = (DBRef) u.get("user");
    BasicDBObject obj = (BasicDBObject) puser.fetch();
    obj.remove("userLoginLog");
    obj.remove("userAuthType");
    obj.remove("userEquipment");
    obj.remove("userLastLoginIpAddress");
    obj.remove("userLastLoginTime");
    if (obj != null && obj.isEmpty() == false) {
        return obj.toMap();
    }
    return null;
}
项目:FindMe_Server    文件:UserDaoImpl2Mongo.java   
@SuppressWarnings("unchecked")
@Override
public List<Map<String, Object>> queryUserFansList(String userId) {
    // TODO Auto-generated method stub

    Map<String, Object> user = super.findOneById(userId, null);
    List<Map<String, Object>> fans = new ArrayList<Map<String, Object>>();
    if (user != null && user.isEmpty() == false) {
        BasicDBList userFans = (BasicDBList) user.get("userFans");
        for (int i = 0; i < userFans.size(); i++) {
            BasicDBObject _obj = (BasicDBObject) userFans.get(i);
            DBRef dbRef = (DBRef) _obj.get("user");
            BasicDBObject obj = (BasicDBObject) dbRef.fetch();
            obj.remove("userEquipment");
            obj.remove("userOpenId");
            obj.remove("userLastLoginIpAddress");
            obj.remove("userLoginLog");
            obj.remove("userMatch");
            obj.remove("userFans");
            obj.remove("userLike");
            obj.remove("userFriend");
            fans.add(obj.toMap());
        }
    }

    return fans;
}
项目:FindMe_Server    文件:NewsDaoImpl2Mongo.java   
@Override
public void createPostNews(Map<String, Object> postNews,
        String collectionName, String postId) {

    DB db = MongoDBUtil.getDB();
    DBRef dbRef = new DBRef(db, collectionName, postId);
    postNews.put("post", dbRef);

    DBCollection collection = db.getCollection(newsCollection);
    BasicDBObject news = new BasicDBObject(postNews);
    collection.insert(news);

    // super.insertByJson(postNews);
}
项目:FindMe_Server    文件:NewsDaoImpl2Mongo.java   
@Override
public void createPostNews(String postId, String userId) {
    // TODO Auto-generated method stub
    DB db = MongoDBUtil.getDB();

    List<Map<String, Object>> users = new ArrayList<Map<String, Object>>();

    Map<String, Object> user = new HashMap<String, Object>();

    DBRef userDbRef = new DBRef(db, "user", userId);
    user.put("user", userDbRef);
    user.put("isRead", "1");// 是否已经阅读 1:已阅读 0:未阅读
    user.put("isDel", 1);// 是否删除 1:删除 0:未删除
    user.put("_id", userId);

    users.add(user);

    Map<String, Object> postNews = new HashMap<String, Object>();
    postNews.put("_id", super.methodUtil.getUUID());
    postNews.put("users", users);
    postNews.put("updateTime", methodUtil.formatDate(new Date(), null, 0));

    // DBRef dbRef = new DBRef(db, "post", "2014062509521826635294167");

    DBRef dbRef = new DBRef(db, "post", postId);
    postNews.put("post", dbRef);

    DBCollection collection = db.getCollection(newsCollection);
    BasicDBObject news = new BasicDBObject(postNews);
    collection.insert(news);

}
项目:FindMe_Server    文件:NewsDaoImpl2Mongo.java   
@SuppressWarnings("unchecked")
@Override
public List<Map<String, Object>> queryNewsListByRefresh(String userId) {

    List<Map<String, Object>> postList = new ArrayList<Map<String, Object>>();
    BasicDBObject query = new BasicDBObject();
    query.put("users._id", userId);
    query.put("users.isDel", 0);
    BasicDBObject sort = new BasicDBObject();
    sort.put("updateTime", -1);
    List<Map<String, Object>> m = super.findByParams(query, sort,
            CommonVariables.PAGE_SIZE, null);
    for (Map<String, Object> map : m) {

        DBRef dbRef = (DBRef) map.get("post");
        BasicDBObject post = (BasicDBObject) dbRef.fetch();
        post.remove("postMessage");
        Map<String, Object> postMap = post.toMap();
        postMap.put("updateTime", map.get("updateTime"));

        BasicDBList users = (BasicDBList) map.get("users");
        for (int i = 0; i < users.size(); i++) {
            BasicDBObject user = (BasicDBObject) users.get(i);
            String _id = user.getString("_id");
            if (_id.equals(userId)) {
                postMap.put("isRead", user.getString("isRead"));
                break;
            }
        }
        postList.add(postMap);
    }
    return postList;
}
项目:FindMe_Server    文件:NewsDaoImpl2Mongo.java   
@SuppressWarnings("unchecked")
@Override
public List<Map<String, Object>> queryNewsListByLoadMore(String userId,
        String newsId) {
    List<Map<String, Object>> postList = new ArrayList<Map<String, Object>>();
    BasicDBObject query = new BasicDBObject();
    query.put("users._id", userId);
    query.put("users.isDel", 0);
    query.put("_id", new BasicDBObject("$lt",newsId));

    BasicDBObject sort = new BasicDBObject();
    sort.put("updateTime", -1);
    List<Map<String, Object>> m = super.findByParams(query, sort,
            CommonVariables.PAGE_SIZE, null);
    for (Map<String, Object> map : m) {

        DBRef dbRef = (DBRef) map.get("post");
        BasicDBObject post = (BasicDBObject) dbRef.fetch();
        post.remove("postMessage");
        Map<String, Object> postMap = post.toMap();
        postMap.put("updateTime", map.get("updateTime"));

        BasicDBList users = (BasicDBList) map.get("users");
        for (int i = 0; i < users.size(); i++) {
            BasicDBObject user = (BasicDBObject) users.get(i);
            String _id = user.getString("_id");
            if (_id.equals(userId)) {
                postMap.put("isRead", user.getString("isRead"));
                break;
            }
        }
        postList.add(postMap);
    }
    return postList;
}
项目:FindMe_Server    文件:TestMain.java   
public void insertPushFriend() {
    DB db = MongoDBUtil.getDB();
    DBCollection connection = db.getCollection("puser");
    BasicDBObject puser = new BasicDBObject();
    puser.put("_id", methodUtil.getUUID());
    DBRef dbRef = new DBRef(db, "user", "2014062909381246721829541");
    puser.put("user", dbRef);
    puser.put("sort", 3);
    connection.insert(puser);
}
项目:FindMe_Server    文件:TestMain.java   
public void testRefBasObj() {
    DB db = MongoDBUtil.getDB();
    DBCollection schoolConnection = db.getCollection("user");
    // schoolConnection.remove(new
    // BasicDBObject("_id","2014062410281828268456656"));
    DBRef dbRef = new DBRef(db, "post", "2014062509521826635294167");
    BasicDBObject user = new BasicDBObject();
    user.put("_id", "2014062710281828268456656");
    user.put("userNickName", "引用测试");
    user.put("post", dbRef);
    schoolConnection.insert(user);
}
项目:FindMe_Server    文件:TestMain.java   
public void a1() {
        DB db = MongoDBUtil.getDB();
        DBCollection users = db.getCollection("user");
        DBRef dbRef1 = new DBRef(db, "user", "2014070910341453956776344");
        BasicDBObject user1 = new BasicDBObject();
        user1.put("user", dbRef1);
        user1.put("isPass", 0);

        DBRef dbRef2 = new DBRef(db, "user", "2014070910342860714428484");
        BasicDBObject user2 = new BasicDBObject();
        user2.put("user", dbRef2);
        user2.put("isPass", 0);

        DBRef dbRef3 = new DBRef(db, "user", "2014070910343826714771967");
        BasicDBObject user3 = new BasicDBObject();
        user3.put("user", dbRef3);
        user3.put("isPass", 0);


        BasicDBObject query = new BasicDBObject();
        query.put("_id", "2014070910275727378200158");

        users.update(query, new BasicDBObject("$push", new BasicDBObject(
                "userMatch", user1)));
        users.update(query, new BasicDBObject("$push", new BasicDBObject(
                "userMatch", user2)));
        users.update(query, new BasicDBObject("$push", new BasicDBObject(
                "userMatch", user3)));
//      users.update(query, new BasicDBObject("$set", new BasicDBObject(
//              "userIsLike", 0)));
    }
项目:cherimodata    文件:_DeEncoding.java   
@Test
public void testDBRefDeEncoding()
{
    ReferencingEntity re = factory.create( ReferencingEntity.class );
    PrimitiveEntity pe = factory.create( PrimitiveEntity.class );

    pe.setString( "nestedString" );
    re.setDBRef( pe );
    re.setString( "some" );

    re.save();
    Document reRead = db.getCollection( getCollectionName( ReferencingEntity.class ) )
        .find( new Document( ID, re.get( ID ) ) ).limit( 1 ).iterator().next();
    ObjectId dbRef = (ObjectId) ( (DBRef) reRead.get( "dBRef" ) ).getId();
    assertNotNull( dbRef );
    assertNotNull( pe.get( ID ) );
    assertEquals( pe.get( ID ), dbRef );
    // make sure only available after explicit saving
    assertFalse( db.getCollection( getCollectionName( PrimitiveEntity.class ) )
        .find( new Document( ID, pe.get( ID ) ) ).limit( 1 ).iterator().hasNext() );
    pe.save();
    Document peRead = db.getCollection( getCollectionName( PrimitiveEntity.class ) )
        .find( new Document( ID, pe.get( ID ) ) ).limit( 1 ).iterator().next();

    assertEquals( pe.get( ID ), peRead.get( ID ) );
    assertEquals( pe.getString(), peRead.get( "string" ) );

    ReferencingEntity read = factory.load( ReferencingEntity.class, re.get( ID ) );
    assertEquals( re, read );
}
项目:ReflecT    文件:Reference.java   
public Reference(Reflector reflector, DBRef dbRefBase)
{
    this.reflector = reflector;
    this.dbRef = dbRefBase;

    this.collection = null;
    this.object = null;
}
项目:ReflecT    文件:Reference.java   
public DBRef getDBRef()
{
    if (this.dbRef == null)
    {
        this.dbRef = new DBRef(collection.getName(), object.get("_id"));
    }
    return this.dbRef;
}
项目:ReflecT    文件:MongoDBCodec.java   
private Node convertObjectToNode(Object value) throws ConversionException
{
    Node nodeValue;
    if (value instanceof List)
    {
        nodeValue = this.convertListToNode((List)value);
    }
    else if (value instanceof DBObject)
    {
        nodeValue = this.convertDBObjectToNode((DBObject)value);
    }
    else if (value instanceof ObjectId)
    {
        nodeValue = new ObjectIdNode((ObjectId)value);
    }
    else if (value instanceof DBRef)
    {
        nodeValue = new DBRefBaseNode((DBRef)value);
    }
    else if (value instanceof Date)
    {
        nodeValue = new DateNode((Date)value);
    }
    else
    {
        nodeValue = getConverterManager().convertToNode(value);
    }
    return nodeValue;
}
项目:liveoak    文件:RootMongoResource.java   
@Override
protected MongoObjectResource getResource(DBRef dbRef, boolean byReference) throws ResourceProcessingException {
    if (dbRef != null) {
        if (dbRef.getDB() == null) {
            throw new ResourceProcessingException("Invalid Reference. Reference Database is null.");
        }
        if (dbRef.getDB().getName() != db().getName()) {
            throw new ResourceProcessingException("LiveOak only supports MongoResource objects within the same database.");
        }

        String collectionName = dbRef.getRef();
        if (!db().collectionExists(collectionName)) {
            throw new ResourceProcessingException("Cannot find collection specified in a reference. No collection named '" + collectionName + "' found");
        }

        MongoCollectionResource mongoCollectionResource = new MongoCollectionResource(this, collectionName);

        if (byReference) {

            MongoObjectResource mongoObjectResource = new MongoBaseObjectResource(mongoCollectionResource, dbRef.getId());

            return mongoObjectResource;
        } else {
            DBObject referencedObject = dbRef.fetch();
            if (referencedObject == null) {
                throw new ResourceProcessingException("Cannot find referenced resource. No resource in collection '" + collectionName + "' with id '" + dbRef.getId()
                        + "'");
            }
            return new MongoBaseObjectResource(mongoCollectionResource, referencedObject);
        }
    } else {
        throw new ResourceProcessingException("Invalid Reference. Reference cannot be null.");
    }
}
项目:liveoak    文件:MongoBaseObjectResource.java   
@Override
public Map<String, ?> properties(RequestContext ctx) throws Exception {
    // TODO: only read properties specified in the return fields and not everything
    Map<String, Object> result = new HashMap<>();
    ReturnFields returnFields = ctx.returnFields();

    DBObject dbObject = getDBObject();

    if (dbObject == null) {
        throw new ResourceProcessingException("Could not find object with ID: " + this.id());
    }

    Set<String> keys = dbObject.keySet();
    for (String key : keys) {
        if (!key.equals(MONGO_ID_FIELD) && !key.equals(LiveOak.ID)) {
            Object value = getDBObject().get(key);
            if (value instanceof BasicDBObject) {
                value = new MongoEmbeddedObjectResource(this, (DBObject) value);
            } else if (value instanceof BasicDBList) {
                value = getResourceCollection(value);
            } else if (value instanceof DBRef) {
                value = getResource((DBRef) value, returnFields.child(key).isEmpty());
            }

            if (supportedObject(value)) {
                result.put(key, value);
            } else {
                log.warn("Unsupported Property type " + value.getClass() + " cannot encode.");
            }
        }
    }
    return result;
}
项目:liveoak    文件:MongoResource.java   
protected BasicDBObject createObject(ResourceState resourceState, boolean nested) throws Exception {
    BasicDBObject basicDBObject = new BasicDBObject();

    // if the state already has an id set, use it here. Otherwise one will be autocreated on insert
    String rid = resourceState.id();
    if (rid != null) {
        if (!nested) {
            basicDBObject.append(MONGO_ID_FIELD, getMongoID(rid));
        } else {
            basicDBObject.append(LiveOak.ID, getMongoID(rid));
        }
    }

    Set<String> keys = resourceState.getPropertyNames();

    for (String key : keys) {
        if (key.equalsIgnoreCase("$dbref")) {
            DBRef dbRef = getDBRef((String) resourceState.getProperty("$dbref"));
            basicDBObject.append(key, dbRef);
        } else if (nested || !key.equals(LiveOak.ID)) { // don't append the ID field again
            Object value = resourceState.getProperty(key);
            if (value instanceof ResourceState) {
                Object dbrefObject = ((ResourceState) value).getProperty("$dbref");
                if (dbrefObject != null) {
                    String uri = (String) dbrefObject;
                    value = getDBRef(uri);
                } else {
                    value = createObject((ResourceState) value, true);
                }
            } else if (value instanceof Collection) {
                value = createObjectList((Collection) value);
            }
            basicDBObject.append(key, value);
        }
    }

    return basicDBObject;
}
项目:liveoak    文件:MongoDBRefTest.java   
@Test
public void removingDBRef() throws Exception {
    String methodName = "testRemovingDBRef";
    assertThat(db.collectionExists(methodName)).isFalse();

    DBCollection people = db.createCollection(methodName, new BasicDBObject());

    // create some objects using the mongo driver directly
    BasicDBObject sallyObject = new BasicDBObject("_id", "Sally");
    sallyObject.append("name", "Sally");
    DBRef sallyDBRef = new DBRef(db, people.getName(), sallyObject.get("_id"));

    BasicDBObject sueObject = new BasicDBObject("_id", "Sue");
    sueObject.append("name", "Sue");
    sueObject.append("bestFriend", sallyDBRef);

    people.insert(sallyObject);
    people.insert(sueObject);

    ResourceState sueResource = client.read(new RequestContext.Builder().returnFields(new DefaultReturnFields("*(*)")).build(), "/testApp/" + BASEPATH + "/" + methodName
            + "/Sue");
    // verify the result, with Sally being Sue's best friend
    ResourceState bestFriend = (ResourceState) sueResource.getProperty("bestFriend");
    assertThat(bestFriend.getProperty("name")).isEqualTo("Sally");

    // now try and remove the bestFriend value
    sueResource.putProperty("bestFriend", null);

    ResourceState updatedState = client.update(new RequestContext.Builder().build(), "/testApp/" + BASEPATH + "/" + methodName + "/Sue", sueResource);
    assertThat(updatedState.getProperty("bestFriend")).isNull();
}