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.streamreduce.core.service.SearchServiceImpl.java

License:Apache License

private SobaMessage createSobaMessageFromJson(JSONObject jsonObject) {
    DBObject dbObject = BasicDBObjectBuilder.start(jsonObject).get();

    if (dbObject.containsField("details")) {
        JSONObject detailsAsJson = (JSONObject) dbObject.get("details");
        DBObject details = BasicDBObjectBuilder.start(detailsAsJson).get();
        dbObject.put("details", details);
    }/*from   w  w  w.j a va 2s .  c o  m*/

    return (SobaMessage) new Mapper().fromDBObject(SobaMessage.class, dbObject, new DefaultEntityCache());
}

From source file:com.university.mongodb.courses.m101j.blogapplication.BlogPostDAO.java

License:Apache License

public DBObject findByPermalink(String permalink) {

    DBObject post = null;/*from ww  w  .  jav a 2  s.co  m*/
    // XXX HW 3.2, Work Here
    post = postsCollection.findOne(new BasicDBObject(POST_PERMALINK, permalink));

    // fix up if a post has no likes
    if (post != null) {
        List<DBObject> comments = (List<DBObject>) post.get(POST_COMMENTS);
        for (DBObject comment : comments) {
            if (!comment.containsField("num_likes")) {
                comment.put("num_likes", 0);
            }
        }
    }

    return post;
}

From source file:com.wenwo.platform.dao.util.WenwoQueryMapper.java

License:Apache License

/**
 * Returns the mapped value for the given source object assuming it's a value for the given
 * {@link MongoPersistentProperty}./*from  ww w . j  a v a  2  s .c om*/
 * 
 * @param source the source object to be mapped
 * @param property the property the value is a value for
 * @param newKey the key the value will be bound to eventually
 * @return
 */
private Object getMappedValue(Object source, MongoPersistentProperty property, String newKey) {

    if (property == null) {
        return convertSimpleOrDBObject(source, null);
    }

    if (property.isIdProperty() || "_id".equals(newKey)) {
        PersistentEntity<?, MongoPersistentProperty> entity = property.getOwner();

        if (source instanceof DBObject) {
            DBObject valueDbo = (DBObject) source;
            if (valueDbo.containsField("$in") || valueDbo.containsField("$nin")) {
                String inKey = valueDbo.containsField("$in") ? "$in" : "$nin";
                List<Object> ids = new ArrayList<Object>();
                if (entity instanceof BasicMongoPersistentEntity) {
                    String collectionName = ((BasicMongoPersistentEntity<?>) entity).getCollection();
                    if (collectionName.equals(QUESTIONS_COLLECTION)) {
                        for (Object id : (Iterable<?>) valueDbo.get(inKey)) {
                            ids.add(id);
                        }
                    } else {
                        for (Object id : (Iterable<?>) valueDbo.get(inKey)) {
                            ids.add(convertId(id));
                        }
                    }
                } else {
                    for (Object id : (Iterable<?>) valueDbo.get(inKey)) {
                        ids.add(convertId(id));
                    }
                }

                valueDbo.put(inKey, ids.toArray(new Object[ids.size()]));
            } else if (valueDbo.containsField("$ne")) {
                valueDbo.put("$ne", convertId(valueDbo.get("$ne")));
            } else {
                return getMappedObject((DBObject) source, null);
            }

            return valueDbo;

        } else {
            if (entity instanceof BasicMongoPersistentEntity) {
                String collectionName = ((BasicMongoPersistentEntity<?>) entity).getCollection();
                if (collectionName.equals(QUESTIONS_COLLECTION)) {
                    return source;
                }
            }

            return convertId(source);
        }
    }

    if (property.isAssociation()) {
        return Keyword.isKeyword(source) ? getMappedKeyword(new Keyword(source), property)
                : convertAssociation(source, property);
    }

    return convertSimpleOrDBObject(source, mappingContext.getPersistentEntity(property));
}

From source file:com.zte.im.util.SystemConfig.java

public static void loadConfig() {

    DBObject config = MongoDBSupport.getInstance().queryOneByParam(CONFIG_COLLECTION, null, null);
    if (config != null) {
        if (config.containsField("fdfs_http_host"))
            fdfs_http_host = config.get("fdfs_http_host").toString();

        if (config.containsField("tracker_servers"))
            tracker_servers = config.get("tracker_servers").toString();

        if (config.containsField("redis_servers"))
            redis_servers = config.get("redis_servers").toString();

        if (config.containsField("sso_server"))
            sso_server = config.get("sso_server").toString();

        if (config.containsField("mdm_server"))
            mdm_server = config.get("mdm_server").toString();

        if (config.containsField("mqtt_server"))
            mqtt_server = config.get("mqtt_server").toString();

        if (config.containsField("mqtt_params"))
            mqtt_params = config.get("mqtt_params").toString();

        if (config.containsField("voip_id_conf"))
            voip_id_conf = config.get("voip_id_conf").toString();

        if (config.containsField("licenseStartDate"))
            licenseStartDate = config.get("licenseStartDate").toString();

        if (config.containsField("mqtt_broker"))
            mqtt_broker = config.get("mqtt_broker").toString();

    }/*from   w  w  w.  j  a v a  2s  .co  m*/
    logger.info("loading sysconfig...");
    logger.info("fdfs_http_host:{}", fdfs_http_host);
    logger.info("tracker_servers:{}", tracker_servers);
    logger.info("redis_servers:{}", redis_servers);
    logger.info("sso_server:{}", sso_server);
    logger.info("mdm_server:{}", mdm_server);
    logger.info("mqtt_server:{}", mqtt_server);
    logger.info("mqtt_params:{}", mqtt_params);
    logger.info("voip_id_conf:{}", voip_id_conf);
    logger.info("licenseStartDate:{}", licenseStartDate);
    logger.info("mqtt_broker:{}", mqtt_broker);

}

From source file:de.flapdoodle.mongoom.datastore.Caps.java

License:Apache License

public static void ensureCaps(DB db, String collectionName, ICollectionCap capCollection) {

    if (capCollection != null) {
        long count = capCollection.count();
        long size = capCollection.size();

        if (size == 0)
            throw new ObjectMapperException("Size == 0");
        if ((size < Long.MAX_VALUE) && (count < Long.MAX_VALUE)) {
            try {
                db.requestStart();/*from  w  w w .  j a va 2 s.  c  o m*/
                BasicDBObjectBuilder dbCapOpts = BasicDBObjectBuilder.start("capped", true);
                dbCapOpts.add("size", size);
                if (count > 0)
                    dbCapOpts.add("max", count);
                DBCollection dbColl = db.getCollection(collectionName);

                if (db.getCollectionNames().contains(collectionName)) {
                    DBObject dbResult = db
                            .command(BasicDBObjectBuilder.start("collstats", collectionName).get());
                    if (dbResult.containsField("capped")) {
                        // TODO: check the cap options.
                        _logger.warning(
                                "DBCollection already exists is cap'd already; doing nothing. " + dbResult);
                    } else {
                        _logger.warning("DBCollection already exists with same name(" + collectionName
                                + ") and is not cap'd; not creating cap'd version!");
                    }
                } else {
                    db.createCollection(collectionName, dbCapOpts.get());
                    _logger.info(
                            "Created cap'd DBCollection (" + collectionName + ") with opts " + capCollection);
                }
            } finally {
                Errors.checkError(db, Operation.Insert);
                db.requestDone();
            }
        }
    }
}

From source file:de.otto.mongodb.profiler.op.analyze.AggregateCommandAnalyzer.java

License:Apache License

@Override
protected boolean analyzeCommand(DBObject dbo, AnalyzerContext context) {

    final DBObject command = require("command", DBObject.class, dbo);

    if (!command.containsField(COMMAND)) {
        return false;
    }//w  w  w. ja va2 s .  c o  m

    final String ns = require("ns", String.class, dbo) + "." + require(COMMAND, String.class, command);
    final List<DBObject> pipeline = require("pipeline", List.class, command);

    if (pipeline == null || pipeline.isEmpty()) {
        return false;
    }

    final String hash = context.createAggregateHash(ns, pipeline);

    DefaultAggregateProfile profile = context.findProfile(hash, DefaultAggregateProfile.class);

    if (profile == null) {
        profile = context.addProfile(hash,
                new DefaultAggregateProfile(hash, ns, context.getOutlierConfiguration(), pipeline));
    }

    profile.add(new ProfileEntry(dbo, DateTime.now()));

    return true;
}

From source file:de.otto.mongodb.profiler.op.analyze.CountCommandAnalyzer.java

License:Apache License

@Override
protected boolean analyzeCommand(DBObject dbo, AnalyzerContext context) {

    final DBObject command = require("command", DBObject.class, dbo);

    if (!command.containsField(COUNT_COMMAND)) {
        return false;
    }// w  w  w. j a va  2 s.  c  om

    final String op = require("op", String.class, dbo);
    final String ns = require("ns", String.class, dbo) + "." + require(COUNT_COMMAND, String.class, command);
    final DBObject queryData = get("query", DBObject.class, command, EMPTY_DBO);

    final String hash = context.createQueryHash(ns, op + COUNT_COMMAND, queryData);

    DefaultCountProfile profile = context.findProfile(hash, DefaultCountProfile.class);

    if (profile == null) {
        profile = context.addProfile(hash,
                new DefaultCountProfile(hash, ns, context.getOutlierConfiguration(), queryData));
    }

    if (context.shouldExplainQuery(profile)) {
        final Explanation explanation = context.explainQuery(require(COUNT_COMMAND, String.class, command),
                profile);
        if (explanation != null) {
            profile.add(explanation);
        }
    }

    profile.add(new ProfileEntry(dbo, DateTime.now()));

    return true;
}

From source file:de.otto.mongodb.profiler.op.analyze.FindAndModifyCommandAnalyzer.java

License:Apache License

@Override
protected boolean analyzeCommand(DBObject dbo, AnalyzerContext context) {

    final DBObject command = require("command", DBObject.class, dbo);

    if (!command.containsField(FIND_AND_MODIFY_COMMAND)) {
        return false;
    }//  w  w  w.  j a  v a  2  s.  c  o  m

    final String op = require("op", String.class, dbo);
    final String ns = require("ns", String.class, dbo) + "."
            + require(FIND_AND_MODIFY_COMMAND, String.class, command);
    final DBObject queryData = require("query", DBObject.class, command);
    final DefaultFindAndModifyProfile.Outcome outcome = DefaultFindAndModifyProfile.Outcome
            .fromCommand(command);

    if (outcome == null) {
        return false;
    }

    final String hash = context.createQueryHash(ns, op + FIND_AND_MODIFY_COMMAND + outcome, queryData);

    DefaultFindAndModifyProfile profile = context.findProfile(hash, DefaultFindAndModifyProfile.class);

    if (profile == null) {
        profile = context.addProfile(hash, new DefaultFindAndModifyProfile(hash, ns,
                context.getOutlierConfiguration(), queryData, outcome));
    }

    if (context.shouldExplainQuery(profile)) {
        final Explanation explanation = context
                .explainQuery(require(FIND_AND_MODIFY_COMMAND, String.class, command), profile);
        if (explanation != null) {
            profile.add(explanation);
        }
    }

    profile.add(new ProfileEntry(dbo, DateTime.now()));

    return true;
}

From source file:de.otto.mongodb.profiler.op.analyze.MapReduceCommandAnalyzer.java

License:Apache License

@Override
protected boolean analyzeCommand(DBObject dbo, AnalyzerContext context) {

    final DBObject command = require("command", DBObject.class, dbo);

    if (!command.containsField(COMMAND)) {
        return false;
    }/*  w ww. j a  va2 s.c o  m*/

    final String ns = require("ns", String.class, dbo) + "." + require(COMMAND, String.class, command);

    final String mapFunction = require("map", String.class, command);
    final String reduceFunction = require("reduce", String.class, command);

    final String hash = context.createMapReduceHash(ns, mapFunction, reduceFunction);

    DefaultMapReduceProfile profile = context.findProfile(hash, DefaultMapReduceProfile.class);

    if (profile == null) {
        profile = context.addProfile(hash, new DefaultMapReduceProfile(hash, ns,
                context.getOutlierConfiguration(), mapFunction, reduceFunction));
    }

    profile.add(new ProfileEntry(dbo, DateTime.now()));

    return true;
}

From source file:de.taimos.dvalin.mongo.links.DLinkQuery.java

License:Apache License

public List<DocumentLink<T>> find(MongoCollection collection, String query, Object... parameter) {
    ResultHandler<DocumentLink<T>> handler = new ResultHandler<DocumentLink<T>>() {

        @Override//  ww w. j av a  2 s .  c  o m
        public DocumentLink<T> map(DBObject result) {
            if (!result.containsField("_id") || !result.containsField(DLinkQuery.this.labelField)) {
                throw new RuntimeException("Fields missing to construct DocumentLink");
            }
            String id = result.get("_id").toString();
            String label = result.get(DLinkQuery.this.labelField).toString();
            return new DocumentLink<T>(DLinkQuery.this.targetClass, id, label);
        }
    };
    Iterator<DocumentLink<T>> it = collection.find(query, parameter)
            .projection(String.format("{%s:1}", this.labelField)).map(handler).iterator();

    List<DocumentLink<T>> objects = new ArrayList<>();
    while (it.hasNext()) {
        DocumentLink<T> link = it.next();
        objects.add(link);
    }
    return objects;
}