Example usage for com.mongodb DBObject containsField

List of usage examples for com.mongodb DBObject containsField

Introduction

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

Prototype

boolean containsField(String s);

Source Link

Document

Checks if this object contains a field with the given name.

Usage

From source file:com.github.jmkgreen.morphia.mapping.DefaultMapper.java

License:Open Source License

Object fromDb(DBObject dbObject, Object entity, EntityCache cache) {
    //hack to bypass things and just read the value.
    if (entity instanceof MappedField) {
        readMappedField(dbObject, (MappedField) entity, entity, cache);
        return entity;
    }//  www  .  j a v a2 s  . com

    // check the history key (a key is the namespace + id)

    if (dbObject.containsField(ID_KEY) && getMappedClass(entity).getIdField() != null
            && getMappedClass(entity).getEntityAnnotation() != null) {
        Key key = new Key(entity.getClass(), dbObject.get(ID_KEY));
        Object cachedInstance = cache.getEntity(key);
        if (cachedInstance != null)
            return cachedInstance;
        else
            cache.putEntity(key, entity); // to avoid stackOverflow in recursive refs
    }

    MappedClass mc = getMappedClass(entity);

    dbObject = (DBObject) mc.callLifecycleMethods(PreLoad.class, entity, dbObject, this);
    try {
        for (MappedField mf : mc.getPersistenceFields()) {
            readMappedField(dbObject, mf, entity, cache);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    if (dbObject.containsField(ID_KEY) && getMappedClass(entity).getIdField() != null) {
        Key key = new Key(entity.getClass(), dbObject.get(ID_KEY));
        cache.putEntity(key, entity);
    }
    mc.callLifecycleMethods(PostLoad.class, entity, dbObject, this);
    return entity;
}

From source file:com.github.torbinsky.morphia.mapping.DefaultMapper.java

License:Open Source License

public Object fromDBObject(DBObject dbObject, Object entity, EntityCache cache) {
    //hack to bypass things and just read the value.
    if (entity instanceof MappedField) {
        readMappedField(dbObject, (MappedField) entity, entity, cache);
        return entity;
    }//from w  w  w . j av  a2  s .c  om

    // check the history key (a key is the namespace + id)

    if (dbObject.containsField(ID_KEY) && getMappedClass(entity).getIdField() != null
            && getMappedClass(entity).getEntityAnnotation() != null) {
        Key key = new Key(entity.getClass(), dbObject.get(ID_KEY));
        Object cachedInstance = cache.getEntity(key);
        if (cachedInstance != null)
            return cachedInstance;
        else
            cache.putEntity(key, entity); // to avoid stackOverflow in recursive refs
    }

    MappedClass mc = getMappedClass(entity);

    dbObject = (DBObject) mc.callLifecycleMethods(PreLoad.class, entity, dbObject, this);
    try {
        for (MappedField mf : mc.getMappedFields()) {
            readMappedField(dbObject, mf, entity, cache);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    if (dbObject.containsField(ID_KEY) && getMappedClass(entity).getIdField() != null) {
        Key key = new Key(entity.getClass(), dbObject.get(ID_KEY));
        cache.putEntity(key, entity);
    }
    mc.callLifecycleMethods(PostLoad.class, entity, dbObject, this);
    return entity;
}

From source file:com.glaf.wechat.mongodb.service.impl.WxMongoDBLogServiceImpl.java

License:Apache License

protected int getInt(DBObject object, String name) {
    int ret = 0;//from  w  w  w  .jav a 2s .c om
    if (object.containsField(name)) {
        Object obj = object.get(name);
        if (obj instanceof Double) {
            Double d = (Double) obj;
            return d.intValue();
        } else if (obj instanceof Long) {
            Long d = (Long) obj;
            return d.intValue();
        } else if (obj instanceof Integer) {
            Integer d = (Integer) obj;
            return d.intValue();
        } else {
            String str = obj.toString();
            if (StringUtils.isNumeric(str)) {
                return Integer.valueOf(str);
            }
        }
    }
    return ret;
}

From source file:com.glaf.wechat.mongodb.service.impl.WxMongoDBLogServiceImpl.java

License:Apache License

public List<WxLog> getWxLogsByQueryCriteria(int start, int pageSize, WxLogQuery query) {
    DB db = mongoTemplate.getDb();/* w  w  w  . j  a  v a2  s  .  c  om*/
    String tableName = "wx_log" + query.getSuffix();
    DBCollection coll = db.getCollection(tableName);
    BasicDBObject q = new BasicDBObject();
    this.fillQueryCondition(q, query);
    DBCursor cur = coll.find(q);

    List<WxLog> logs = new java.util.concurrent.CopyOnWriteArrayList<WxLog>();

    int limit = query.getPageSize();
    if (limit <= 0) {
        limit = Paging.DEFAULT_PAGE_SIZE;
    }
    if (start < cur.count()) {
        logger.debug("start=" + start);
        logger.debug("limit=" + limit);
        List<DBObject> list = coll.find(q).skip(start).limit(limit).toArray();
        for (DBObject object : list) {
            WxLog log = new WxLog();
            log.setId((Long) object.get("id"));
            log.setIp((String) object.get("ip"));
            log.setActorId((String) object.get("actorId"));
            log.setContent((String) object.get("content"));
            log.setOperate((String) object.get("operate"));
            if (object.containsField("accountId")) {
                log.setAccountId((Long) object.get("accountId"));
            }
            if (object.containsField("openId")) {
                log.setOpenId((String) object.get("openId"));
            }
            if (object.containsField("flag")) {
                log.setFlag((Integer) object.get("flag"));
            }
            if (object.containsField("createTime")) {
                long ts = (Long) object.get("createTime");
                log.setCreateTime(new Date(ts));
            }

            logs.add(log);
        }
    }
    return logs;
}

From source file:com.glaf.wechat.mongodb.service.impl.WxMongoDBLogServiceImpl.java

License:Apache License

public List<WxLog> list(WxLogQuery query) {
    DB db = mongoTemplate.getDb();/*  w  ww .j  a  v  a2  s.c  o m*/
    String tableName = "wx_log" + query.getSuffix();
    DBCollection coll = db.getCollection(tableName);
    BasicDBObject q = new BasicDBObject();
    this.fillQueryCondition(q, query);
    List<DBObject> list = coll.find(q).toArray();
    List<WxLog> logs = new java.util.concurrent.CopyOnWriteArrayList<WxLog>();
    for (DBObject object : list) {
        WxLog log = new WxLog();
        log.setId((Long) object.get("id"));
        log.setIp((String) object.get("ip"));
        log.setActorId((String) object.get("actorId"));
        log.setOperate((String) object.get("operate"));
        log.setContent((String) object.get("content"));
        if (object.containsField("accountId")) {
            log.setAccountId((Long) object.get("accountId"));
        }
        if (object.containsField("openId")) {
            log.setOpenId((String) object.get("openId"));
        }
        if (object.containsField("flag")) {
            log.setFlag((Integer) object.get("flag"));
        }
        if (object.containsField("createTime")) {
            long ts = (Long) object.get("createTime");
            log.setCreateTime(new Date(ts));
        }

        logs.add(log);
    }
    return logs;
}

From source file:com.groupon.jenkins.mongo.JenkinsEmbeddedMapper.java

License:Open Source License

private boolean isFullySerializedObject(DBObject cachedStub, Mapper mapper) {
    return cachedStub.keySet().size() > 2 && cachedStub.containsField(mapper.ID_KEY)
            && cachedStub.containsField(mapper.CLASS_NAME_FIELDNAME);
}

From source file:com.hangum.tadpole.mongodb.core.query.MongoDBQuery.java

License:Open Source License

/**
 * list index//  w w w  .  j  av a 2s  .c  o  m
 * 
 * @param userDB
 * @throws Exception
 */
public static List<MongoDBIndexDAO> listAllIndex(UserDBDAO userDB) throws Exception {
    List<MongoDBIndexDAO> listReturnIndex = new ArrayList<MongoDBIndexDAO>();

    DB mongoDB = MongoConnectionManager.getInstance(userDB);
    for (String col : mongoDB.getCollectionNames()) {

        if (!isSystemCollection(col)) {
            List<DBObject> listIndexObj = mongoDB.getCollection(col).getIndexInfo();
            for (DBObject dbObject : listIndexObj) {
                MongoDBIndexDAO indexDao = new MongoDBIndexDAO();

                indexDao.setV(dbObject.get("v").toString());
                Map<String, Object> objMap = (Map) dbObject.get("key");
                for (String strKey : objMap.keySet()) {
                    indexDao.getListIndexField()
                            .add(new MongoDBIndexFieldDAO(strKey, objMap.get(strKey).toString()));
                }

                if (dbObject.containsField("unique")) {
                    indexDao.setUnique(Boolean.valueOf(dbObject.get("unique").toString()));
                }
                String strNs = dbObject.get("ns").toString();
                strNs = StringUtils.substringAfter(strNs, userDB.getDb() + ".");

                indexDao.setNs(strNs);
                indexDao.setName(dbObject.get("name").toString());

                listReturnIndex.add(indexDao);
            }
        }
    }

    return listReturnIndex;
}

From source file:com.health.smart.util.MongoC.java

public static String find(String collection, String document) throws Exception {
    DBCollection coll = getClient().getDB(database).getCollection(collection);
    DBObject docObj = (DBObject) JSON.parse(document);
    List<DBObject> objects;
    if (!docObj.containsField("projection")) {
        objects = coll.find((DBObject) JSON.parse((String) docObj.get("criteria"))).toArray();
    } else {/*from   w  w w . j a  v  a 2 s  .c om*/
        objects = coll.find((DBObject) JSON.parse((String) docObj.get("criteria")),
                (DBObject) JSON.parse((String) docObj.get("projection"))).toArray();
    }
    return objects.toString();
}

From source file:com.ikanow.aleph2.shared.crud.mongodb.services.MongoDbCrudService.java

License:Apache License

/** creates a new object and inserts an _id field if needed
 * @param bean the object to convert//from w ww  .j av  a2s . co m
 * @return the converted BSON (possibly with _id inserted)
 */
protected DBObject convertToBson(final O bean) {
    final DBObject dbo = Patterns.match().<DBObject>andReturn()
            .when(() -> JsonNode.class != _state.bean_clazz, () -> _state.coll.convertToDbObject(bean))
            .otherwise(() -> {
                try (BsonObjectGenerator generator = new BsonObjectGenerator()) {
                    _object_mapper.writeTree(generator, (JsonNode) bean);
                    return generator.getDBObject();
                } catch (Exception e) {
                    return new BasicDBObject();
                }
            });
    if (_state.insert_string_id_if_missing) {
        if (!dbo.containsField(_ID))
            dbo.put(_ID, new ObjectId().toString());
    }
    return dbo;
}

From source file:com.ikanow.aleph2.shared.crud.mongodb.services.MongoDbCrudService.java

License:Apache License

@Override
public CompletableFuture<Optional<O>> updateAndReturnObjectBySpec(QueryComponent<O> unique_spec,
        final Optional<Boolean> upsert, final UpdateComponent<O> update, final Optional<Boolean> before_updated,
        final List<String> field_list, final boolean include) {
    try {/*w  w  w  .  ja  va  2  s  . c  om*/
        final Tuple2<DBObject, DBObject> query_and_meta = MongoDbUtils.convertToMongoQuery(unique_spec);
        final DBObject update_object = MongoDbUtils.createUpdateObject(update);

        final BasicDBObject fields = new BasicDBObject(
                field_list.stream().collect(Collectors.toMap(f -> f, f -> include ? 1 : 0)));

        // ($unset: null removes the object, only possible via the UpdateComponent.deleteObject call) 
        final boolean do_remove = update_object.containsField("$unset")
                && (null == update_object.get("$unset"));

        final O ret_val = do_remove
                ? _state.coll.findAndModify(query_and_meta._1(), fields,
                        (DBObject) query_and_meta._2().get("$sort"), do_remove, (DBObject) null, false, false)
                : _state.coll.findAndModify(query_and_meta._1(), fields,
                        (DBObject) query_and_meta._2().get("$sort"), false, update_object,
                        !before_updated.orElse(false), upsert.orElse(false));

        return CompletableFuture.completedFuture(Optional.ofNullable(ret_val));
    } catch (Exception e) {
        return FutureUtils.<Optional<O>>returnError(e);
    }
}