List of usage examples for com.mongodb DBObject put
Object put(String key, Object v);
From source file:com.bugull.mongo.utils.MapperUtil.java
License:Apache License
/** * options for ensureIndex().// w ww .j a va 2s .c o m * @param index * @return */ public static List<DBIndex> getDBIndex(String index) { List<DBIndex> list = new ArrayList<DBIndex>(); index = index.replaceAll("\\}[^{^}]+\\{", "};{"); index = index.replaceAll("[{}'']", ""); String[] items = index.split(";"); for (String item : items) { DBObject keys = new BasicDBObject(); DBObject options = new BasicDBObject("background", true); String[] arr = item.split(","); for (String s : arr) { String[] kv = s.split(":"); String k = kv[0].trim(); String v = kv[1].trim(); //note: the following check order can't be changed! if (v.equalsIgnoreCase("2d") || v.equalsIgnoreCase("text")) { keys.put(k, v); } else if (k.equalsIgnoreCase("expireAfterSeconds")) { options.put(k, Integer.parseInt(v)); } else if (v.equals("1") || v.equals("-1")) { keys.put(k, Integer.parseInt(v)); } else if (v.equalsIgnoreCase("true") || v.equalsIgnoreCase("false")) { options.put(k, Boolean.parseBoolean(v)); } else if (k.equalsIgnoreCase("name")) { options.put(k, v); } } DBIndex dbi = new DBIndex(); dbi.setKeys(keys); dbi.setOptions(options); list.add(dbi); } return list; }
From source file:com.bugull.mongo.utils.MapperUtil.java
License:Apache License
/** * Get the lazy fields/* w w w . ja v a 2s . c om*/ * @param clazz * @return */ public static DBObject getKeyFields(Class<?> clazz) { DBObject keys = new BasicDBObject(); Field[] fields = FieldsCache.getInstance().get(clazz); for (Field field : fields) { String fieldName = field.getName(); Property property = field.getAnnotation(Property.class); if (property != null && property.lazy()) { String name = property.name(); if (!name.equals(Default.NAME)) { fieldName = name; } keys.put(fieldName, 0); continue; } Embed embed = field.getAnnotation(Embed.class); if (embed != null && embed.lazy()) { String name = embed.name(); if (!name.equals(Default.NAME)) { fieldName = name; } keys.put(fieldName, 0); continue; } EmbedList embedList = field.getAnnotation(EmbedList.class); if (embedList != null && embedList.lazy()) { String name = embedList.name(); if (!name.equals(Default.NAME)) { fieldName = name; } keys.put(fieldName, 0); continue; } } return keys; }
From source file:com.buzz.buzzdata.MongoBuzz.java
private String getBuzz(BasicDBObject query, Double lat, Double lng) { String retval = ""; DBCollection buzzCollection = mongoDB.getCollection("BuzzInfo"); DBObject sort = new BasicDBObject(); sort.put("modified", -1); DBCursor cursor = buzzCollection.find(query).sort(sort); try {//ww w . ja v a 2 s .c o m while (cursor.hasNext()) { //get buzzid DBObject buzz_obj = cursor.next(); ObjectId buzz_id = (ObjectId) buzz_obj.get("_id"); //get images for buzzid GridFS gridFS = new GridFS(mongoDB); BasicDBObject check_images = new BasicDBObject("BuzzID", buzz_id); List<GridFSDBFile> dbfiles = gridFS.find(check_images); String image_links = ""; for (GridFSDBFile file : dbfiles) { String _buzz_id = buzz_id.toString(); String pic_num = file.get("PicNum").toString(); if (!image_links.equals("")) { image_links += ",http://192.168.0.11:8080/BuzzRestAPI/webresources/buzz/Image?buzzid=" + _buzz_id + "&pic_num=" + pic_num; } else { image_links += "http://192.168.0.11:8080/BuzzRestAPI/webresources/buzz/Image?buzzid=" + _buzz_id + "&pic_num=" + pic_num; } } String imgs = "\"Images\": " + "\"" + image_links + "\""; retval += buzz_obj; retval = retval.substring(0, retval.length() - 1); retval += ", " + imgs; double lat2 = (double) ((BasicDBList) buzz_obj.get("loc")).get(0); double lng2 = (double) ((BasicDBList) buzz_obj.get("loc")).get(1); double dist = this.haversine(lat, lng, lat2, lng2); retval += ", \"Distance\": " + dist; String directions_url = "https://maps.google.com/maps?saddr=" + lat + "," + lng + "&daddr=" + lat2 + "," + lng2 + "&hl=en&sll=" + lat + "," + lng + "&sspn=" + lat2 + "," + lng2 + "&t=m&mra=mift&mrsp=1&sz=5&z=18"; retval += ", \"Directions\": \"" + directions_url + "\""; retval += "},"; } } catch (Exception exc) { } finally { cursor.close(); } retval = retval.substring(0, retval.length() - 1); retval = "callback({\"Buzzes\": [" + retval + "]})"; return retval; }
From source file:com.ca.apm.mongo.test.MongoReplicaSetForTestFactory.java
License:Open Source License
private void initializeReplicaSet(Entry<String, List<IMongodConfig>> entry) throws Exception { String replicaName = entry.getKey(); List<IMongodConfig> mongoConfigList = entry.getValue(); if (mongoConfigList.size() < 3) { throw new Exception("A replica set must contain at least 3 members."); }//from w w w . j ava 2 s. c o m // Create 3 mongod processes for (IMongodConfig mongoConfig : mongoConfigList) { if (!mongoConfig.replication().getReplSetName().equals(replicaName)) { throw new Exception("Replica set name must match in mongo configuration"); } MongodStarter starter = MongodStarter.getDefaultInstance(); MongodExecutable mongodExe = starter.prepare(mongoConfig); MongodProcess process = mongodExe.start(); mongodProcessList.add(process); } Thread.sleep(1000); MongoClientOptions mo = MongoClientOptions.builder().autoConnectRetry(true).build(); MongoClient mongo = new MongoClient( new ServerAddress(mongoConfigList.get(0).net().getServerAddress().getHostName(), mongoConfigList.get(0).net().getPort()), mo); DB mongoAdminDB = mongo.getDB(ADMIN_DATABASE_NAME); CommandResult cr = mongoAdminDB.command(new BasicDBObject("isMaster", 1)); logger.info("isMaster: " + cr); // Build BSON object replica set settings DBObject replicaSetSetting = new BasicDBObject(); replicaSetSetting.put("_id", replicaName); BasicDBList members = new BasicDBList(); int i = 0; for (IMongodConfig mongoConfig : mongoConfigList) { DBObject host = new BasicDBObject(); host.put("_id", i++); host.put("host", mongoConfig.net().getServerAddress().getHostName() + ":" + mongoConfig.net().getPort()); members.add(host); } replicaSetSetting.put("members", members); logger.info(replicaSetSetting.toString()); // Initialize replica set cr = mongoAdminDB.command(new BasicDBObject("replSetInitiate", replicaSetSetting)); logger.info("replSetInitiate: " + cr); Thread.sleep(5000); cr = mongoAdminDB.command(new BasicDBObject("replSetGetStatus", 1)); logger.info("replSetGetStatus: " + cr); // Check replica set status before to proceed while (!isReplicaSetStarted(cr)) { logger.info("Waiting for 3 seconds..."); Thread.sleep(1000); cr = mongoAdminDB.command(new BasicDBObject("replSetGetStatus", 1)); logger.info("replSetGetStatus: " + cr); } mongo.close(); mongo = null; }
From source file:com.caci.dummyserver.MongoRepository.java
private DBObject makeQueryObject(Collection<Pair<String, String>> keys, Collection<Pair<String, Collection<String>>> filters) { DBObject result = new BasicDBObject(); if (keys != null) { for (Pair<String, String> key : keys) { result.put("key." + key.getKey(), key.getValue()); }/*from w ww . java 2s . c o m*/ } if (filters != null) { for (Pair<String, Collection<String>> filter : filters) { int valueCount = filter.getValue().size(); if (valueCount == 1) { String filterValue = null; for (String v : filter.getValue()) { filterValue = v; } result.put("data." + filter.getKey(), filterValue); } else if (valueCount > 1) { BasicDBList dbList = new BasicDBList(); dbList.addAll(filter.getValue()); BasicDBObject dbObj = new BasicDBObject(); dbObj.put("$in", dbList); result.put("data." + filter.getKey(), dbObj); } } } return result; }
From source file:com.caci.dummyserver.MongoRepository.java
private DBObject makeDBObject(Collection<Pair<String, String>> keys, String json) { DBObject result = new BasicDBObject(); if (keys != null) { DBObject keyObject = new BasicDBObject(); for (Pair<String, String> key : keys) { keyObject.put(key.getKey(), key.getValue()); }//from w ww . j a v a 2 s . co m result.put("key", keyObject); } if (json != null && !json.equals("")) { result.put("data", (DBObject) JSON.parse(json)); } return result; }
From source file:com.caci.dummyserver.MongoRepository.java
public GetObjectsResult getObjects(String table, Collection<Pair<String, String>> keys, Collection<String> fields, Collection<Pair<String, Collection<String>>> filters, Collection<String> sort, Integer offset, Integer limit) { DB db = mongo.getDB("Objects"); DBCollection col = db.getCollection(table); GetObjectsResult result = new GetObjectsResult(); DBObject queryObject = makeQueryObject(keys, filters); DBCursor cursor = col.find(queryObject); try {/*w w w. ja va2 s .co m*/ if (sort != null && !sort.isEmpty()) { DBObject sortObj = new BasicDBObject(); for (String fieldName : sort) { if (fieldName.startsWith("-")) { sortObj.put("data." + fieldName.substring(1), -1); } else { sortObj.put("data." + fieldName, 1); } } cursor.sort(sortObj); } result.setTotal(cursor.count()); if (offset != null && offset > 0) { cursor.skip(offset); } if (limit != null && limit > 0) { cursor.limit(limit); } while (cursor.hasNext()) { DBObject obj = cursor.next(); obj = pruneDBObject(getData(obj), fields); result.getResults().add(obj.toString()); } } finally { cursor.close(); } return result; }
From source file:com.caci.dummyserver.MongoRepository.java
public void updateObject(String table, Collection<Pair<String, String>> keys, String json) { DB db = mongo.getDB("Objects"); DBCollection col = db.getCollection(table); DBObject queryObject = makeQueryObject(keys, null); DBObject updateObject = new BasicDBObject(); updateObject.put("$set", makeDBObject(keys, json)); col.update(queryObject, updateObject); }
From source file:com.caci.dummyserver.MongoRepository.java
/** * Insert a new object into the specified collection. * @param table The name of the Mongo collection to insert into. * @param keys The list of key/value pairs. These are the path parameters. * @param json The json for the document to insert. * @return Returns the DAVE ID of the object. *//*from w ww.j ava2 s . c om*/ public String insertObject(String table, Collection<Pair<String, String>> keys, String json) throws Exception { DB db = mongo.getDB("Objects"); DBCollection col = db.getCollection(table); String daveId = generateDAVEID(); while (getObject(table, daveId, null) != null) { daveId = generateDAVEID(); } DBObject data = (DBObject) JSON.parse(json); data.put("id", daveId); json = data.toString(); if (keys == null) { keys = new ArrayList<>(); } keys.add(new Pair<>(":" + table, daveId)); DBObject obj = makeDBObject(keys, json); col.insert(obj); return daveId; }
From source file:com.callidusrobotics.droptables.model.DocumentDao.java
License:Open Source License
protected static DBObject flatten(DBObject item) { item.put(DOC_ID, item.get(DOC_ID).toString()); return item; }