@org.testng.annotations.Test public void testEscape1() { String raw = "a\nb"; DBObject x = new BasicDBObject("x", raw); assertEquals("\"a\\nb\"", JSON.serialize(raw)); assertEquals(x, JSON.parse(x.toString())); assertEquals(raw, ((DBObject) JSON.parse(x.toString())).get("x")); x = new BasicDBObject("x", "a\nb\bc\td\re"); assertEquals(x, JSON.parse(x.toString())); String thingy = "va\"lue"; x = new BasicDBObject("name", thingy); x = (DBObject) JSON.parse(x.toString()); assertEquals(thingy, x.get("name")); thingy = "va\\lue"; x = new BasicDBObject("name", thingy); x = (DBObject) JSON.parse(x.toString()); assertEquals(thingy, x.get("name")); assertEquals("va/lue", (String) JSON.parse("\"va\\/lue\"")); assertEquals("value", (String) JSON.parse("\"va\\lue\"")); assertEquals("va\\lue", (String) JSON.parse("\"va\\\\lue\"")); _escapeChar("\t"); _escapeChar("\b"); _escapeChar("\n"); _escapeChar("\r"); _escapeChar("\'"); _escapeChar("\""); _escapeChar("\\"); }
public void remove(String collection, DBObject query) { DBCollection dbCollection = getCollection(collection); dbCollection.remove(query); Jedis jedis = JedisManager.getJedis(); jedis.zrem("expire", query.toString()); jedis.hdel(collection, query.toString()); JedisManager.returnJedis(jedis); }
/** * Returns the String representation of the MongoDB object with the given id * * @param id objectId to find the object of * @return JSON String representation of the MongoDB object */ public String get(ObjectId id) { DBObject object = coll.findOne(id); System.out.println(1 + object.toString()); if (object == null) { return null; } return object.toString(); }
public void updateDocument(String collection, DBObject query, DBObject document) { DBCollection dbCollection = getCollection(collection); dbCollection.update(query, document); Jedis jedis = JedisManager.getJedis(); if (jedis.hexists(collection, query.toString())) { jedis.hset(collection, query.toString(), findOneNoCache(collection, query).toString()); jedis.zadd("expire", System.currentTimeMillis() + 300000, collection + "_" + query); } JedisManager.returnJedis(jedis); }
public void delete(String collection, DBObject query) { DBCollection dbCollection = getCollection(collection); dbCollection.remove(query); Jedis jedis = JedisManager.getJedis(); if (jedis.hexists(collection, query.toString())) { jedis.hdel(collection, query.toString(), findOneNoCache(collection, query).toString()); jedis.zrem("expire", collection + "_" + query); } JedisManager.returnJedis(jedis); }
@org.testng.annotations.Test public void testNumbers2() { DBObject x = new BasicDBObject("x", 123); assertEquals(x, JSON.parse(x.toString())); x = new BasicDBObject("x", 123123123123L); assertEquals(x, JSON.parse(x.toString())); x = new BasicDBObject("x", 123123123); assertEquals(x, JSON.parse(x.toString())); }
void _escapeChar(String s) { String thingy = "va" + s + "lue"; DBObject x = new BasicDBObject("name", thingy); x = (DBObject) JSON.parse(x.toString()); assertEquals(thingy, x.get("name")); thingy = "va" + s + s + s + "lue" + s; x = new BasicDBObject("name", thingy); x = (DBObject) JSON.parse(x.toString()); assertEquals(thingy, x.get("name")); }
@Test public void shouldCorrectlySerialisePointsInGeometryCollection() { // given Point point = point(3.0, 7.0); GeometryCollection geometryCollection = GeoJson.geometryCollection(point); // when DBObject dbObject = getMorphia().toDBObject(geometryCollection); // then use the underlying driver to ensure it was persisted correctly to the database assertThat(dbObject, is(notNullValue())); assertThat( dbObject.toString(), JSONMatcher.jsonEqual( " {" + " type: 'GeometryCollection', " + " geometries: " + " [" + " {" + " type: 'Point', " + " coordinates: [7.0, 3.0]" + " }, " + " ]" + "}")); }
@Test public void shouldCorrectlySerialiseLineStringsInGeometryCollection() { // given LineString lineString = lineString(point(1, 2), point(3, 5), point(19, 13)); GeometryCollection geometryCollection = GeoJson.geometryCollection(lineString); getMorphia().getMapper().addMappedClass(Point.class); // when DBObject dbObject = getMorphia().toDBObject(geometryCollection); assertThat(dbObject, is(notNullValue())); assertThat( dbObject.toString(), JSONMatcher.jsonEqual( " {" + " type: 'GeometryCollection', " + " geometries: " + " [" + " {" + " type: 'LineString', " + " coordinates: [ [ 2.0, 1.0]," + " [ 5.0, 3.0]," + " [13.0, 19.0] ]" + " }," + " ]" + "}")); }
@Test public void shouldCorrectlySerialiseMultiPointsInGeometryCollection() { // given MultiPoint multiPoint = GeoJson.multiPoint(point(1, 2), point(3, 5), point(19, 13)); GeometryCollection geometryCollection = GeoJson.geometryCollection(multiPoint); // when DBObject dbObject = getMorphia().toDBObject(geometryCollection); assertThat(dbObject, is(notNullValue())); assertThat( dbObject.toString(), JSONMatcher.jsonEqual( " {" + " type: 'GeometryCollection', " + " geometries: " + " [" + " {" + " type: 'MultiPoint', " + " coordinates: [ [ 2.0, 1.0]," + " [ 5.0, 3.0]," + " [13.0, 19.0] ]" + " }," + " ]" + " }" + "}")); }
@Override public String Json(String nombreDB, int clienteId) throws UnknownHostException, JSONException { // TODO Auto-generated method stub MongoClient mongoClient = new MongoClient("localhost", 27017); DB base = mongoClient.getDB(nombreDB); DBCollection collection = base.getCollection("Json"); BasicDBObject query = new BasicDBObject(); query.put("id", clienteId); DBCursor cursor = collection.find(query); if (cursor.size() == 0) { // System.out.println("********************\n"); // System.out.println("No existe el cliente, no se puede ingresar json"); // System.out.println("********************\n"); return "No existe el cliente, no se puede ingresar json"; } // Existe el cliente DBObject objeto = (DBObject) cursor.next(); DBObject json = (DBObject) objeto.get("json"); // DBObject j = JSON.parse(json.toString()); JSONObject aj = new JSONObject(json.toString()); return aj.toString(); }
@Test public void groupFile() { long startTiem = System.currentTimeMillis(); String map = "function() { " + "var category; " + "if ( this.secretStatus = 2 ) " + "category = '标密状态位2'; " + "else " + "category = '标密状态位其它'; " + "emit(category, {secretPerson: this.secretPerson});}"; String reduce = "function(key, values) { " + "var sum = 0; " + "values.forEach(function(doc) { " + "sum += 1; " + "}); " + "return {副本总数: sum};} "; MapReduceCommand cmd = new MapReduceCommand(bakFiles, map, reduce, null, MapReduceCommand.OutputType.INLINE, null); MapReduceOutput out = bakFiles.mapReduce(cmd); long endTime = System.currentTimeMillis(); System.out.println("本次操作消费 " + (endTime - startTiem) + " 毫秒"); for (DBObject o : out.results()) { System.out.println(o.toString()); } }
public String parseJSONFind(String workspaceID, String jsonString) { StringBuffer ret = new StringBuffer(); ret.append("{\n"); System.out.println(workspaceID); System.out.println(jsonString); int counter = 0; DB db = m.getDB(Tokens.WORKSPACE_DATABASE); DBCollection coll = db.getCollection(workspaceID); BasicDBObject query = (BasicDBObject) JSON.parse(jsonString); // FixStrings.usr2mongo(jsonString) System.out.println("query: " + query.toString()); DBCursor find = coll.find(query); Iterator<DBObject> iter = find.iterator(); while (iter.hasNext()) { counter++; if (counter > 1) ret.append(",\n"); DBObject next = iter.next(); Map toMap = next.toMap(); ret.append("\"" + toMap.get("_id").toString() + "\" : "); // remove the redundant id next.removeField("_id"); // ret+= "\"kbid" + counter + "\" : "; String rec = FixStrings.mongo2usr(next.toString()); ret.append(rec); } ret.append("\n}\n"); // System.out.println(workspaceID); return ret.toString(); }
@Test public void testBasicQuery() { BasicDBObject query = new BasicDBObject(); query.put(EmployeeProperties.EMPLOYEE_ID, "28241"); BasicDBObject fields = new BasicDBObject(); fields.put(EmployeeProperties.ID, 0); fields.put(EmployeeProperties.LAST_NAME, 1); fields.put(EmployeeProperties.EMPLOYEE_ID, 1); DBCollection collection = mongoOps.getCollection(EmployeeProperties.COLLECTION); log.info( "MongoDB Query Explain Plan: " + collection .find(query, fields) .hint(new BasicDBObject(EmployeeProperties.EMPLOYEE_ID, 1)) .explain()); DBCursor cursor = collection.find(query, fields).hint(new BasicDBObject(EmployeeProperties.EMPLOYEE_ID, 1)); log.info(cursor.count() + ""); assertNotNull("cursor was null.", cursor); assertEquals("cursor count was not 1.", 1, cursor.count()); log.info("Query (" + query.toString() + ")"); while (cursor.hasNext()) { DBObject dbo = cursor.next(); log.info(dbo.toString()); assertEquals("Keyset size not equal to 2.", 2, dbo.keySet().size()); } log.info(cursor.explain().toString()); }
@Override public void dropIndex(final DB db, final DBObject spec, final String collectionName) { List<DBObject> indexes = db.getCollection(collectionName).getIndexInfo(); DBObject indexObj = (DBObject) spec.get("index"); toMongoFormat(indexObj); if (doesNotExist(indexes, indexObj)) { throw new DropIndexFailed( "Cannot drop index : " + indexObj.toString() + " Index doesn't exist."); } db.getCollection(collectionName).dropIndex(indexObj); }
public Trigger getTrigger(String name) { DBCollection coll = db.getCollection("trigger"); BasicDBObject whereQuery = new BasicDBObject(); whereQuery.put("name", name); DBCursor cursor = coll.find(whereQuery); Trigger trigger = null; while (cursor.hasNext()) { DBObject o = cursor.next(); trigger = gson.fromJson(o.toString(), Trigger.class); } return trigger; }
public List<Trigger> getAllTriggers() { DBCollection coll = db.getCollection("trigger"); DBCursor cursor = coll.find(); List<Trigger> list = new ArrayList<Trigger>(); while (cursor.hasNext()) { DBObject o = cursor.next(); Trigger drug = gson.fromJson(o.toString(), Trigger.class); list.add(drug); } return list; }
@Test public void shouldCorrectlySerialisePolygonsInGeometryCollection() { // given Polygon polygonWithHoles = polygon( lineString(point(1.1, 2.0), point(2.3, 3.5), point(3.7, 1.0), point(1.1, 2.0)), lineString(point(1.5, 2.0), point(1.9, 2.0), point(1.9, 1.8), point(1.5, 2.0)), lineString( point(2.2, 2.1), point(2.4, 1.9), point(2.4, 1.7), point(2.1, 1.8), point(2.2, 2.1))); GeometryCollection geometryCollection = GeoJson.geometryCollection(polygonWithHoles); // when DBObject dbObject = getMorphia().toDBObject(geometryCollection); assertThat(dbObject, is(notNullValue())); assertThat( dbObject.toString(), JSONMatcher.jsonEqual( " {" + " type: 'GeometryCollection', " + " geometries: " + " [" + " {" + " type: 'Polygon', " + " coordinates: " + " [ [ [ 2.0, 1.1]," + " [ 3.5, 2.3]," + " [ 1.0, 3.7]," + " [ 2.0, 1.1] " + " ]," + " [ [ 2.0, 1.5]," + " [ 2.0, 1.9]," + " [ 1.8, 1.9]," + " [ 2.0, 1.5] " + " ]," + " [ [ 2.1, 2.2]," + " [ 1.9, 2.4]," + " [ 1.7, 2.4]," + " [ 1.8, 2.1]," + " [ 2.1, 2.2] " + " ]" + " ]" + " }," + " ]" + " }" + "}")); }
public boolean updatedb(String input, String username) { MongoClientURI uri = new MongoClientURI("mongodb://*****:*****@ds037824.mongolab.com:37824/ase"); MongoClient client = new MongoClient(uri); DB db = client.getDB(uri.getDatabase()); DBCollection Users = db.getCollection("Patients"); DBObject inputDBObj = (DBObject) JSON.parse(input); System.out.println(inputDBObj.toString()); BasicDBObject searchQuery = new BasicDBObject().append("username", username); Users.update(searchQuery, inputDBObj); client.close(); return true; }
public static void assertDbObject( OgmSessionFactory sessionFactory, String collection, String queryDbObject, String projectionDbObject, String expectedDbObject) { DBObject finder = (DBObject) JSON.parse(queryDbObject); DBObject fields = projectionDbObject != null ? (DBObject) JSON.parse(projectionDbObject) : null; MongoDBDatastoreProvider provider = MongoDBTestHelper.getProvider(sessionFactory); DBObject actual = provider.getDatabase().getCollection(collection).findOne(finder, fields); assertJsonEquals(expectedDbObject, actual.toString()); }
@org.testng.annotations.Test public void testRegexNoOptions() { String x = "^Hello$"; String serializedPattern = "{ \"$regex\" : \"" + x + "\"}"; Pattern pattern = Pattern.compile(x); assertEquals(serializedPattern, JSON.serialize(pattern)); BasicDBObject a = new BasicDBObject("x", pattern); assertEquals("{ \"x\" : " + serializedPattern + "}", a.toString()); DBObject b = (DBObject) JSON.parse(a.toString()); assertEquals(b.get("x").getClass(), Pattern.class); assertEquals(a.toString(), b.toString()); }
@ResponseBody @RequestMapping(value = "tuanP.json", method = RequestMethod.POST) public JsonVo tuanP(ModelMap modelMap, HttpServletRequest request) { JsonVo<String> json = new JsonVo<String>(); request.setAttribute("toWhat", 1); modelMap = indexService.getIndexProduct(modelMap, request); List list = ((PageVo) modelMap.get("pageVo")).getList(); for (int oo = 0; oo < list.size(); oo++) { DBObject dbObject = (DBObject) list.get(oo); list.set(oo, dbObject.toString()); } json.setObject(list); json.setResult(true); return json; }
public String retrieveJson(String name) { BasicDBObject query = new BasicDBObject("name", name); DBObject resp; // DBCursor cur; resp = this.services.findOne(query); // resp = cur.next(); if (resp != null) { resp.removeField("_id"); System.out.println(resp); } return resp.toString(); }
// 删除指定id的语料 public void deletecorpus() throws UnknownHostException { String message = "请输入要读取的文本编号!"; long idm = 1; Object obj = JOptionPane.showInputDialog(null, message, idm); String obj1 = (String) obj; if (obj1 == null) { return; } long id1 = Long.parseLong(obj1); MongoClient mc = null; DB db = null; mc = new MongoClient("127.0.0.1", 27017); db = mc.getDB("corpus"); DBCollection textsave = null; if (Readcorpustype == "熟语料") { textsave = db.getCollection("ripe"); } else if (Readcorpustype == "生语料") { textsave = db.getCollection("raw"); } else if (Readcorpustype == null) { JOptionPane.showMessageDialog(null, "请在帮助菜单中设置语料类型!"); return; } DBCursor cursor = textsave.find(); Gson gson = new Gson(); long countoftextsave = textsave.getCount(); long counti = 0; long uid = -1; while (cursor.hasNext()) { DBObject st = cursor.next(); Savetext u = gson.fromJson(st.toString(), Savetext.class); counti++; uid = u.id; if (uid == id1) { ReadDbobject = cursor.curr(); textsave.remove(ReadDbobject); System.out.println("删除成功"); break; } else if (uid != id1) { continue; } } if ((counti == countoftextsave) && (uid != id1)) { JOptionPane.showMessageDialog(null, "wrong id!"); return; } }
@Override public void loadPlayer(UUID uuid) { service.submit( () -> { DBCursor cursor = collection.find(new BasicDBObject("uuid", uuid)); GamePlayer player = null; if (cursor.hasNext()) { DBObject next = cursor.next(); String json = next.toString(); player = GSON.fromJson(json, new TypeToken<GamePlayer>() {}.getType()); } if (player == null) { player = new GamePlayer(uuid); } PlayerRegistry.registerPlayer(player); }); }
@Test public void shouldCorrectlySerialiseMultiPolygonsInGeometryCollection() { // given MultiPolygon multiPolygon = multiPolygon( polygon(lineString(point(1.1, 2.0), point(2.3, 3.5), point(3.7, 1.0), point(1.1, 2.0))), polygon( lineString(point(1.2, 3.0), point(2.5, 4.5), point(6.7, 1.9), point(1.2, 3.0)), lineString(point(3.5, 2.4), point(1.7, 2.8), point(3.5, 2.4)))); GeometryCollection geometryCollection = GeoJson.geometryCollection(multiPolygon); // when DBObject dbObject = getMorphia().toDBObject(geometryCollection); assertThat(dbObject, is(notNullValue())); assertThat( dbObject.toString(), JSONMatcher.jsonEqual( " {" + " type: 'GeometryCollection', " + " geometries: " + " [" + " {" + " type: 'MultiPolygon', " + " coordinates: [ [ [ [ 2.0, 1.1]," + " [ 3.5, 2.3]," + " [ 1.0, 3.7]," + " [ 2.0, 1.1]," + " ]" + " ]," + " [ [ [ 3.0, 1.2]," + " [ 4.5, 2.5]," + " [ 1.9, 6.7]," + " [ 3.0, 1.2] " + " ]," + " [ [ 2.4, 3.5]," + " [ 2.8, 1.7]," + " [ 2.4, 3.5] " + " ]," + " ]" + " ]" + " }" + " ]" + " }" + "}")); }
public Usage getMdnUsageDetail(String mdn) { Usage usage = null; MongoClient mongo = null; String database = "usage"; try { Map<String, Object> dbMap = DataUtils.getConnection(); DB db = (DB) dbMap.get("db"); mongo = (MongoClient) dbMap.get("mongo"); /*MongoClientURI uri = new MongoClientURI("mongodb://*****:*****@ds051863.mongolab.com:51863/CloudFoundry_omfu0lp3_t4cigvf3"); mongo = new MongoClient(uri); DB db = mongo.getDB(uri.getDatabase());*/ /*if(!DataUtils.auth){ DataUtils.auth = db.authenticate("yoga", "test123".toCharArray()); System.out.println("db authenticated "+DataUtils.auth); }*/ DBCollection col = db.getCollection("usage"); DBObject query = BasicDBObjectBuilder.start().add("mdn", mdn).get(); DBCursor cursor = col.find(query); ObjectMapper objectMapper = new ObjectMapper(); if (cursor.hasNext()) { // System.out.println(cursor.next()); DBObject obj = cursor.next(); usage = objectMapper.readValue(obj.toString(), Usage.class); } } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JsonParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JsonMappingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { mongo.close(); } return usage; }
public static String get(String id) { // Since 2.10.0, uses MongoClient try { DBCollection message = Database.gardensharing().getCollection("message"); BasicDBObject searchQuery = new BasicDBObject(); searchQuery.put("id", id); DBCursor cursor = message.find(searchQuery); if (cursor.hasNext()) { DBObject object = cursor.next(); return object.toString(); } else { return null; } } catch (MongoException e) { e.printStackTrace(); } return null; }
@GET @Produces(MediaType.APPLICATION_JSON) @Path("finalizarEjercicio") public String finalizarEjercicio( @QueryParam("idAlumno") Long idAlumno, @QueryParam("idEjercicio") Integer idEjercicio, @QueryParam("valor") double valor) { ModeloEstudiante estudiante = new ModeloEstudiante(); estudiante.setId(idAlumno); EstudiantesManager manager = new EstudiantesManager(estudiante); DBObject json = new BasicDBObject(); Double value = manager.getAbilityGlobal(); json.put("result", manager.finalizarEjercicio(idEjercicio, valor)); json.put("habilidadGlobal", value); manager.saveAbilityGlobal(value); return json.toString(); }
public DBObject findOne(String collection, DBObject query) { Jedis jedis = JedisManager.getJedis(); Set<String> expiredKeys = jedis.zrangeByScore("expire", 0, System.currentTimeMillis()); if (expiredKeys.isEmpty() == false) { String[] keyArray = new String[expiredKeys.size()]; expiredKeys.toArray(keyArray); jedis.del(keyArray); jedis.zrem("expire", keyArray); } JSONObject jsonObject = null; if (jedis.hexists(collection, query.toString())) { String data = jedis.hget(collection, query.toString()); if (data != null) { try { jsonObject = new JSONObject(data); } catch (JSONException e) { e.printStackTrace(); } } } DBObject dbObject; if (jsonObject == null) { DBCollection dbCollection = getCollection(collection); DBCursor dbCursor = dbCollection.find(query).limit(1); if (dbCursor.hasNext() == false) { return null; } dbObject = dbCursor.next(); dbCursor.close(); jedis.hset(collection, query.toString(), dbObject.toString()); jedis.zadd("expire", System.currentTimeMillis() + 300000, collection + "_" + query); } else { dbObject = (DBObject) JSON.parse(jsonObject.toString()); jedis.hset(collection, query.toString(), dbObject.toString()); jedis.zadd("expire", System.currentTimeMillis() + 300000, collection + "_" + query); } JedisManager.returnJedis(jedis); return dbObject; }