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.github.rutledgepaulv.testsupport.CriteriaSerializer.java

License:Open Source License

private DBObject applyInternal(DBObject object) {
    object.keySet().stream()/*from w  w w. jav  a2  s .co m*/
            .forEach(key -> object.put(key,
                    object.get(key) instanceof Enum<?> ? object.get(key).toString()
                            : object.get(key) instanceof DBObject ? applyInternal((DBObject) object.get(key))
                                    : object.get(key) instanceof Collection<?>
                                            ? applyList((Collection<?>) object.get(key))
                                            : object.get(key)));

    return object;
}

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

License:Open Source License

DBObject toDBObject(Object entity, Map<Object, DBObject> involvedObjects, boolean lifecycle) {

    DBObject dbObject = new BasicDBObject();
    MappedClass mc = getMappedClass(entity);

    if (mc.getEntityAnnotation() == null || mc.isClassNameStored())
        dbObject.put(CLASS_NAME_FIELDNAME, entity.getClass().getName());

    if (lifecycle)
        dbObject = (DBObject) mc.callLifecycleMethods(PrePersist.class, entity, dbObject, this);

    for (MappedField mf : mc.getMappedFields()) {
        try {/*w  w  w  . j  a va  2 s.co  m*/
            writeMappedField(dbObject, mf, entity, involvedObjects);
        } catch (Exception e) {
            throw new MappingException("Error mapping field:" + mf.getFullName(), e);
        }
    }
    if (involvedObjects != null)
        involvedObjects.put(entity, dbObject);

    if (lifecycle)
        mc.callLifecycleMethods(PreSave.class, entity, dbObject, this);

    return dbObject;
}

From source file:com.glaf.core.test.MongoDBGridFSThread.java

License:Apache License

public void run() {
    if (file.exists() && file.isFile()) {
        String path = file.getAbsolutePath();
        path = path.replace('\\', '/');
        if (StringUtils.contains(path, "/temp/") || StringUtils.contains(path, "/tmp/")
                || StringUtils.contains(path, "/logs/") || StringUtils.contains(path, "/work/")
                || StringUtils.endsWith(path, ".log") || StringUtils.endsWith(path, ".class")) {
            return;
        }//from  ww w  . j av  a 2 s.c om
        int retry = 0;
        boolean success = false;
        byte[] bytes = null;
        GridFSInputFile inputFile = null;
        while (retry < 1 && !success) {
            try {
                retry++;
                bytes = FileUtils.getBytes(file);
                if (bytes != null) {
                    inputFile = gridFS.createFile(bytes);
                    DBObject metadata = new BasicDBObject();
                    metadata.put("path", path);
                    metadata.put("filename", file.getName());
                    metadata.put("size", bytes.length);
                    inputFile.setMetaData(metadata);
                    inputFile.setId(path);
                    inputFile.setFilename(file.getName());// ??
                    inputFile.save();// ?
                    bytes = null;
                    success = true;
                    logger.debug(file.getAbsolutePath() + " save ok.");
                }
            } catch (Exception ex) {
                logger.error(ex);
                ex.printStackTrace();
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } finally {
                bytes = null;
                inputFile = null;
            }
        }
    }
}

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

License:Apache License

protected void fillQueryCondition(DBObject q, WxLogQuery query) {
    if (query.getCreateTimeLessThanOrEqual() != null) {
        q.put("createTime", new BasicDBObject("&lte", query.getCreateTimeLessThanOrEqual().getTime()));
    }/*w ww. j  a  v  a2 s. co  m*/

    if (query.getCreateTimeGreaterThanOrEqual() != null) {
        q.put("createTime", new BasicDBObject("&gte", query.getCreateTimeGreaterThanOrEqual().getTime()));
    }

    if (query.getAccountId() != null && query.getAccountId() != 0) {
        q.put("accountId", query.getAccountId());
    }

    if (query.getActorId() != null) {
        q.put("actorId", query.getActorId());
    }

    if (query.getOpenId() != null) {
        q.put("openId", query.getOpenId());
    }

    if (query.getIp() != null) {
        q.put("ip", query.getIp());
    }

    if (query.getOperate() != null) {
        q.put("operate", query.getOperate());
    }

    if (query.getFlag() != null && query.getFlag() != 0) {
        q.put("flag", query.getFlag());
    }

}

From source file:com.google.api.ads.adwords.awreporting.model.persistence.mongodb.MongoEntityPersister.java

License:Open Source License

@Override
public void persistReportEntities(List<? extends Report> reportEntities) {
    if (reportEntities != null && reportEntities.size() > 0) {
        for (Report report : reportEntities) {
            String jsonObject = gson.toJson(report);
            DBObject dbObject = (DBObject) com.mongodb.util.JSON.parse(jsonObject.toString());

            // Set the proper _id from the MongoEntity RowID
            dbObject.put("_id", ((MongoEntity) report).getRowId());

            getCollection(report.getClass()).save(dbObject);
        }// w  ww  . j  av a 2s  .c  om
    }
}

From source file:com.google.api.ads.adwords.awreporting.model.persistence.mongodb.MongoEntityPersister.java

License:Open Source License

@Override
public <T> T save(T t) {
    T newT = null;/*from   w w w .  j  a  va  2 s .c  om*/
    if (t != null) {
        String jsonObject = gson.toJson(t);
        DBObject dbObject = (DBObject) com.mongodb.util.JSON.parse(jsonObject.toString());
        dbObject.put("safe", "true");

        // Set the proper _id from the MongoEntity RowID
        if (t instanceof MongoEntity) {
            dbObject.put("_id", ((MongoEntity) t).getRowId());
        }

        getCollection(t.getClass()).save(dbObject, WriteConcern.SAFE);
    }
    return newT;
}

From source file:com.google.api.ads.adwords.jaxws.extensions.report.model.persistence.mongodb.MongoEntityPersister.java

License:Open Source License

/**
 * @see com.google.api.ads.adwords.jaxws.extensions.report.model.persistence.EntityPersister
 *      #save(java.lang.Object)//from www .j  av  a  2 s  .  c om
 */
@Override
public <T> T save(T t) {
    T newT = null;
    if (t != null) {

        DBCollection dbcollection = getDBCollection(t.getClass(), true);

        String jsonObject;
        jsonObject = gson.toJson(t);
        DBObject dbObject = (DBObject) com.mongodb.util.JSON.parse(jsonObject.toString());
        dbObject.put("safe", "true");
        dbcollection.save(dbObject, WriteConcern.SAFE);
    }
    return newT;
}

From source file:com.google.api.services.samples.analytics.cmdline.CoreReportingApiReferenceSample.java

License:Apache License

/**
 * Prints all the rows of data returned by the API.
 *  @param gaData     the data returned from the API.
 * @param collection/*from   ww w.jav  a2 s .  c o m*/
 * @param d
 */
private static void insertVisitedCompaniesData(GaData gaData, DBCollection collection, Date d)
        throws JSONException {
    if (gaData.getTotalResults() > 0) {
        System.out.println("Data Table: " + collection);

        for (List<String> rowValues : gaData.getRows()) {
            Map jsonMap = (Map) JSON.parse(rowValues.get(0));
            if (jsonMap.get("demandbase_sid") == null) {
                continue;
            }
            DBObject dbObject = new BasicDBObject(jsonMap);
            dbObject.removeField("ip");
            HashMap<Object, Object> map = new HashMap<Object, Object>();
            map.put("demandbase_sid", dbObject.get("demandbase_sid"));
            BasicDBObject objectToRemove = new BasicDBObject(map);
            DBObject andRemove = collection.findAndRemove(objectToRemove);
            if (andRemove == null) {
                dbObject.put("firstVisitDate", new SimpleDateFormat("yyyy/MM/dd").format(d));
            } else {
                dbObject.put("firstVisitDate", andRemove.get("firstVisitDate"));
            }
            collection.insert(dbObject);
        }
    } else {
        System.out.println("No data");
    }
}

From source file:com.grallandco.impl.MongoCAPIBehavior.java

License:Apache License

/**
 * Load the documents into MongoDB//w w  w.j  a v a 2  s. c o m
 * @param database
 * @param docs
 * @return
 */
@Override
public List<Object> bulkDocs(String database, List<Map<String, Object>> docs) {

    DB db = MongoConnectionManager.getMongoClient().getDB(getDatabaseName(database));
    List<Object> result = new ArrayList<Object>();

    logger.log(Level.INFO, String.format("Replicating %d document(s)", docs.size()));

    for (Map<String, Object> doc : docs) {
        Map<String, Object> meta = (Map<String, Object>) doc.get("meta");
        Map<String, Object> json = (Map<String, Object>) doc.get("json");
        String base64 = (String) doc.get("base64");

        if (meta == null) {
            // if there is no meta-data section, there is nothing we can do
            logger.log(Level.WARNING, "Document without meta in bulk_docs, ignoring....");
            continue;
        } else if ("non-JSON mode".equals(meta.get("att_reason"))
                || "invalid_json".equals(meta.get("att_reason"))) {
            // optimization, this tells us the body isn't json
            json = new HashMap<String, Object>();
        } else if (json == null && base64 != null) {

            // use Java 6/7 XML Base64 library
            // TODO : see if it makes sense to use Java8 Library java.util.Base64
            String jsonValue = new String(DatatypeConverter.parseBase64Binary(base64));
            DBObject o = (DBObject) JSON.parse(jsonValue);
            DBObject mongoJson = BasicDBObjectBuilder.start("_id", meta.get("id")).get();

            // need to check if json keys do not contains . or $ and replace them with other char
            // TODO : Copy the doc, put _id at the top and clean key names
            Set<String> keys = o.keySet();
            for (String key : keys) {
                String newKey = key;
                newKey = newKey.replace(".", MongoDBCouchbaseReplicator.dotReplacement);
                newKey = newKey.replace("$", MongoDBCouchbaseReplicator.dollarReplacement);
                mongoJson.put(newKey, o.get(key));
            }

            // add meta data if configured
            if (MongoDBCouchbaseReplicator.keepMeta) {
                mongoJson.put("meta", new BasicDBObject(meta));
            }

            String collectionName = MongoDBCouchbaseReplicator.defaultCollection;
            if (o.get(MongoDBCouchbaseReplicator.collectionField) != null) {
                collectionName = (String) o.get(MongoDBCouchbaseReplicator.collectionField);
            }

            try {

                if (MongoDBCouchbaseReplicator.replicationType.equalsIgnoreCase("insert_only")) {
                    // this will raise an exception
                    db.getCollection(collectionName).insert(mongoJson);
                } else { // insert & update
                    db.getCollection(collectionName).save(mongoJson);
                }

            } catch (MongoException e) {

                if (e.getCode() == 11000) {
                    logger.log(Level.INFO, "Not replicating updated document " + meta.get("id"));
                } else {
                    logger.log(Level.SEVERE, e.getMessage());
                }

            }

        }

        String id = (String) meta.get("id");
        String rev = (String) meta.get("rev");
        Map<String, Object> itemResponse = new HashMap<String, Object>();
        itemResponse.put("id", id);
        itemResponse.put("rev", rev);
        result.add(itemResponse);
    }

    return result;
}

From source file:com.groupon.jenkins.dynamic.build.DbBackedBuild.java

License:Open Source License

@PrePersist
void saveState(final DBObject dbObj) {
    dbObj.put("state", getState().toString());
    hudson.model.Items.XSTREAM.ignoreUnknownElements();
}