@Test(dataProvider = "ids") public void generateSchedule(String id) throws ParseException, UnknownHostException { DBObject query = (DBObject) JSON.parse("{_id:\"" + id + "\" }"); DBObject filter = (DBObject) JSON.parse( "{" + "\"FpML.trade.swap.swapStream.calculationPeriodDates.effectiveDate\":1," + "\"FpML.trade.swap.swapStream.calculationPeriodDates.terminationDate\":1," + "\"FpML.trade.swap.swapStream.calculationPeriodDates.calculationPeriodFrequency\":1," + "\"FpML.trade.swap.swapStream.calculationPeriodDates.calculationPeriodDatesAdjustments\":1," + "}"); DBCursor dbCursor = fpmls.find(query, filter); DBObject dates = dbCursor.next(); DBObject stream1 = get(dates, "FpML.trade.swap.swapStream.0.calculationPeriodDates"); List<org.jquantlib.time.Date> dates11 = generateCouponDates(stream1); List<Date> dates12 = (List<Date>) cashflows.findOne(query).get("P"); for (Date date : dates12) Assert.assertTrue(dates11.contains(new org.jquantlib.time.Date(date))); DBObject stream2 = get(dates, "FpML.trade.swap.swapStream.1.calculationPeriodDates"); List<org.jquantlib.time.Date> dates21 = generateCouponDates(stream2); List<Date> dates22 = (List<Date>) cashflows.findOne(query).get("R"); for (Date date : dates22) Assert.assertTrue(dates21.contains(new org.jquantlib.time.Date(date))); }
/** execute map reduce */ private void executeMapReduce() throws Exception { String strMap = textMap.getText(); String strReduce = textReduce.getText(); String strFinilize = textFinalize.getText(); String strOutputTarget = textOutputTarget.getText(); MapReduceCommand.OutputType outputType = (MapReduceCommand.OutputType) comboOutputType.getData(comboOutputType.getText()); DBObject dbQuery = null; if (!"".equals(textQuery.getText())) dbQuery = (DBObject) JSON.parse(textQuery.getText()); DBObject dbSort = null; if (!"".equals(textSort.getText())) dbSort = (DBObject) JSON.parse(textSort.getText()); // 쿼리 합니다. DBCollection dbCol = MongoDBQuery.findCollection(userDB, initColName); MapReduceCommand mrCmd = new MapReduceCommand(dbCol, strMap, strReduce, strOutputTarget, outputType, dbQuery); if (!"".equals(strFinilize)) mrCmd.setFinalize(strFinilize); if (dbSort != null) mrCmd.setSort(dbSort); if (getLimit() > 0) mrCmd.setLimit(getLimit()); if (btnJsMode.getSelection()) mrCmd.addExtraOption("jsMode", true); final BasicDBObject searchObj = (BasicDBObject) mrCmd.toDBObject(); if (btnSharded.getSelection()) ((BasicDBObject) searchObj.get("out")).put("sharded", true); if (btnNoneAtomic.getSelection()) ((BasicDBObject) searchObj.get("out")).put("nonAtomic", true); goMapReduce(dbCol, searchObj, outputType); }
public static String getLogList(String userID) { DBCursor cursor = collLog .find( (DBObject) JSON.parse( "{ $or : [ { userID : \"" + userID + "\"}, {users: \"" + userID + "\" }]}"), (DBObject) JSON.parse("{ _id : 0, nodeID : 0, users : 0 }")) .sort((DBObject) JSON.parse("{ time : -1 }")); JsonArray logArray = new JsonArray(); try { while (cursor.hasNext()) { String data = cursor.next().toString(); JsonObject jsonObj = new JsonObject(data); System.out.println(data); logArray.addObject(jsonObj); } } finally { cursor.close(); } JsonObject logList = new JsonObject(); logList.putArray("log", logArray); return logList.encode(); }
public void LoadSeedData(String strColl, String metadatafile) throws Exception { try { InputStream is = this.getClass().getResourceAsStream(metadatafile); String xml; xml = IOUtils.toString(is); JSONObject rwSeed = XML.toJSONObject(xml); if (!rwSeed.isNull("ReferralWireSeedData")) { JSONObject json = rwSeed.getJSONObject("ReferralWireSeedData"); DBCollection dbcoll = store.getColl(strColl); Object coll = (Object) json.get(strColl); if (coll instanceof JSONArray) { JSONArray defs = (JSONArray) coll; for (int i = 0; i < defs.length(); i++) { Object obj = (JSONObject) defs.get(i); dbcoll.insert((DBObject) com.mongodb.util.JSON.parse(obj.toString())); } } else { dbcoll.insert((DBObject) com.mongodb.util.JSON.parse(coll.toString())); } } } catch (IOException e) { // TODO Auto-generated catch block log.debug("API Error: ", e); } }
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()); }
/** * submit a command to the database * * @param database - databse name * @param collection - collection name * @param query - query for doc search * @param operation - operation to be done in DB (insert, remove or update) * @param command - command * @param all - if true, all docs will be affected by the command * @return */ public String submitDBCommand( String database, String collection, String query, String operation, String command, Boolean all) { WriteResult result = null; try { DBCollection DBCollection = getCollection(database, collection); if (operation.equals("insert")) { JSONObject teste = new JSONObject(command); Object teste1 = JSON.parse(teste.toString()); DBObject doc = (DBObject) teste1; result = DBCollection.save(doc); } else if (operation.equals("update")) { DBObject queryDB = (DBObject) JSON.parse(query); DBObject doc = (DBObject) JSON.parse(command); if (all) { result = DBCollection.update(queryDB, doc, false, true); } else { result = DBCollection.update(queryDB, doc); } } else if (operation.equals("remove")) { DBObject queryDB = (DBObject) JSON.parse(query); DBObject doc = (DBObject) JSON.parse(command); if (all) { result = DBCollection.update(queryDB, doc, false, true); } else { result = DBCollection.update(queryDB, doc); } } return "Result: " + result.toString(); } catch (Exception e) { logger.logp( Level.SEVERE, TAG, "executeDBCommand", e.getMessage() + " database:" + database + " collection: " + collection + ", result: " + result.toString()); e.printStackTrace(); } return null; } // database, collection, query, operation, command, all
@DataProvider(name = "ids") public Object[][] generateTradeIds() { ArrayList<Object[]> objects = new ArrayList<Object[]>(); DBObject query = (DBObject) JSON.parse("{}"); DBObject filter = (DBObject) JSON.parse("{_id:1}"); DBCursor cursor = fpmls.find(query, filter); while (cursor.hasNext()) { DBObject id = cursor.next(); objects.add(new Object[] {id.get("_id")}); } return objects.toArray(new Object[][] {}); }
protected DBObject prepareObject(StreamsDatum streamsDatum) { DBObject dbObject = null; if (streamsDatum.getDocument() instanceof String) { dbObject = (DBObject) JSON.parse((String) streamsDatum.getDocument()); } else { try { ObjectNode node = mapper.valueToTree(streamsDatum.getDocument()); dbObject = (DBObject) JSON.parse(node.toString()); } catch (Exception e) { e.printStackTrace(); LOGGER.error("Unsupported type: " + streamsDatum.getDocument().getClass(), e); } } return dbObject; }
@Path("insertcourses") @PUT @Produces(MediaType.APPLICATION_JSON) public String createCourses(String jsonData) { System.out.println("data received from front end" + jsonData); Object jsonObject = JSON.parse(jsonData); BasicDBObject basicdbobject = (BasicDBObject) jsonObject; CoursesDAO coursesdao = new CoursesDAO(); JSONObject jsonobject = new JSONObject(); try { if (coursesdao.insertCourseInfo(basicdbobject)) { jsonobject.put("status", "success"); } else { jsonobject.put("status", "fail"); } } catch (JSONException e) { System.out.println("Exception in json conversion" + e.getMessage()); } return jsonobject.toString(); }
@Path("deletecourses") @DELETE public String deleteCourses(String jsondata) { System.out.println("data received from front end" + jsondata); Object jsonObject = JSON.parse(jsondata); BasicDBObject basicdbobject = (BasicDBObject) jsonObject; CoursesDAO coursesdao = new CoursesDAO(); boolean status = coursesdao.deleteCourseFromDatabase(basicdbobject); JSONObject statusObject = new JSONObject(); try { if (status) { statusObject.put("status", "success"); } else { statusObject.put("status", "fail"); } } catch (JSONException e) { System.out.println("exception in message" + e.getMessage()); } return statusObject.toString(); }
public static Result record() { try { /*String user = session("connected"); if(user == null) { return unauthorized("Oops, you are not connected"); }else{System.out.println("authorized "+user );} */ BasicDBObject res = new BasicDBObject(); JsonNode json = request().body().asJson(); response().setContentType("application/json"); if (json == null) { return badRequest("Expecting Json data"); } else { String recid = json.findPath("recid").getTextValue(); if (recid == null) { return notFound(); } else if (recid != null) { SearchServiceAccess acc = new SearchServiceAccess(); res = acc.searchEuropeanaRecord(recid); } return ok(com.mongodb.util.JSON.serialize(res)); } } catch (Exception ex) { System.out.println(ex.getMessage()); response().setContentType("application/json"); return internalServerError(Messages.get("apperror")); } }
//////////////////////////////////////////////////////////////////////// // Component //////////////////////////////////////////////////////////////////////// @Override protected boolean checkComponentCustom(BoxPanel comp) { // String txt = _field.getText().trim(); String txt = getComponentStringFieldValue(Item.jsonText); if (nonEmpty && txt.isEmpty()) { setDisplayError("Field cannot be empty"); return false; } if (!getComponentBooleanFieldValue(Item.validate)) { return true; } try { // 1st parse with GSON to check, since our parser has bugs MongoUtils.getJsonParser().parse(txt); DBObject doc = (DBObject) JSON.parse(txt); return true; } catch (Exception e) { // this could be because of binary in field getLogger().log(Level.INFO, null, e); } setDisplayError("Invalid JSON format: correct or disable validation"); return false; }
public String getDocument(String GUID, OutputStream out) throws DocumentException { try { GridFS gridFS = new GridFS(dataBase); ObjectId key = new ObjectId(GUID); GridFSDBFile gridFSDBFile = gridFS.find(key); if (gridFSDBFile == null) { throw new DocumentException("No existe el documento"); } if (out != null) gridFSDBFile.writeTo(out); CommandResult result = dataBase.getLastError(); if (!result.ok()) { throw new DocumentException(result.getErrorMessage()); } DBObject dbObject = gridFSDBFile.getMetaData(); return JSON.serialize(dbObject); } catch (Exception e) { log.error("getDocument error:" + e.getMessage()); e.printStackTrace(); throw new DocumentException(e.getMessage()); } }
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(); }
private boolean checkmsgsum(Object data, String touser, String userenc, String checksum) { String sdata = JSON.serialize(data); sdata = sdata.replaceAll("[ \\n\\r\\t]", ""); log.info(sdata); if (CommonUtil.eq(checksum, EncodeHelper.digest(sdata + touser + userenc, "SHA"))) return true; else return false; }
@Action("pushresult") public String pushresult() throws IOException { DB db = MongoUtil.getInstance().getDB(); BasicDBObject ret = null; if (checkTime(timestamp)) { if (checkenc(db, timestamp, clientid, userenc)) { DBObject dbo = db.getCollection("Pushmsgs").findOne(new BasicDBObject("msgid", msgid)); if (!CommonUtil.isEmpty(dbo)) { ret = new BasicDBObject() .append("msgid", dbo.get("msgid")) .append("status", dbo.get("status")); } else { errormsg = "Message not found"; } } else { errormsg = "User not authorized"; } } else errormsg = "Timestamp outof range"; HttpServletResponse resp = ServletActionContext.getResponse(); resp.setCharacterEncoding("utf-8"); resp.setContentType("application/json"); if (!CommonUtil.isEmpty(ret)) resp.getWriter().print(JSON.serialize(ret)); else resp.getWriter().write("{\"errcode\":50000,\"errmsg\":\"" + errormsg + "\"}"); return NONE; }
public boolean stop() { scheduler.stop(); try { ZKManager zkManager = new ZKManager(PropertiesUtil.loadProperties()); String serverPathStr = CommonConstants.ZK_ROOT_PATH + "/server"; List<String> serverNodeList = zkManager.getZooKeeper().getChildren(serverPathStr, false); for (int i = 0; (serverNodeList != null) && (i < serverNodeList.size()); i++) { String id = serverNodeList.get(i); String c = zkManager.getData(serverPathStr + "/" + id); if (c == null) { continue; } BasicDBObject record = (BasicDBObject) com.mongodb.util.JSON.parse(c); String ip = (String) record.get(CommonConstants.IP); if (!StringUtil.isEmpty(ip) && IpUtil.getLocalIP().equals(ip)) { zkManager.delete(serverPathStr + "/" + id); } } zkManager.close(); } catch (Exception e) { if (logger.isDebugEnabled()) e.printStackTrace(); logger.error("ModuleSchedulerServer-->>stop() error ", e); } return true; }
private Object JSONParse(Object object) { if (object instanceof String || object instanceof Number) { return object; } else { return JSON.parse(object.toString()); } }
static BasicDBObject convertToBasicDBObject(String object) { if (object == null || object.length() == 0) { return new BasicDBObject(); } else { return (BasicDBObject) JSON.parse(object); } }
static String addRemovePrefix(String prefix, String object, boolean add) { if (prefix == null) { throw new IllegalArgumentException("prefix"); } if (object == null) { throw new NullPointerException("object"); } if (object.length() == 0) { return ""; } DBObject bsonObject = (DBObject) JSON.parse(object); BasicBSONObject newObject = new BasicBSONObject(); for (String key : bsonObject.keySet()) { if (add) { newObject.put(prefix + key, bsonObject.get(key)); } else { if (key.startsWith(prefix)) { newObject.put(key.substring(prefix.length()), bsonObject.get(key)); } else { newObject.put(key, bsonObject.get(key)); } } } return newObject.toString(); }
public String newDocument(InputStream in, String json) throws DocumentException { try { GridFS gridFS = new GridFS(dataBase); GridFSInputFile gridFSInputFile = gridFS.createFile(in); ObjectId objectId = (ObjectId) gridFSInputFile.getId(); String GUID = objectId.toStringMongod(); DBObject dbObject = (DBObject) JSON.parse(json); gridFSInputFile.setFilename((String) dbObject.get(NAME)); gridFSInputFile.setContentType((String) dbObject.get(CONTENT_TYPE)); gridFSInputFile.setMetaData(dbObject); gridFSInputFile.save(); CommandResult result = dataBase.getLastError(); if (!result.ok()) { throw new DocumentException(result.getErrorMessage()); } return GUID; } catch (Exception e) { log.error("newDocument error:" + e.getMessage()); e.printStackTrace(); throw new DocumentException(e.getMessage()); } }
public JsonArray updatePerfResults(String perfResults) { BasicDBObject doc = (BasicDBObject) JSON.parse(perfResults); doc.append("_id", doc.get("name")); DBCollection coll = db.getCollection("performance"); BasicDBObject query = new BasicDBObject(); query.put("_id", doc.get("name")); DBCursor cursor = coll.find(query); JsonObjectBuilder objBuild = Json.createObjectBuilder(); JsonArrayBuilder arrBuild = Json.createArrayBuilder(); JsonObject json = objBuild.build(); if (cursor.count() > 0) { LOG.info("Performance Results Found and Updated: " + coll.update(query, doc, true, false)); json = Json.createReader(new StringReader(perfResults)).readObject(); return arrBuild.add(json).build(); } else { LOG.info("Performance Results Created: " + coll.insert(doc)); json = Json.createReader(new StringReader(perfResults)).readObject(); return arrBuild.add(json).build(); } }
/** * Imports a JSON resource into a MongoDB collection. * * @param resource the JSON resource * @param db the MongoDB datastore * @param collection the collection to update * @param drop indicates if the existing collection must be dropped */ private void mongoImport(URL resource, DB db, String collection, boolean drop) { // keep a reference to the collection DBCollection c = db.getCollection(collection); // drop the content quickly, note that indexes must be created again if // necessary. if (drop) c.drop(); int count = 0; // used to count the line try (BufferedReader reader = new BufferedReader(new InputStreamReader(resource.openStream()))) { String line = null; // used to store the line as a string while ((line = reader.readLine()) != null) { count++; // count the lines // skip empty lines and line with comments line = line.trim(); if (line.length() != 0 && !line.startsWith("#")) { // parse line DBObject obj = (DBObject) JSON.parse(line); // insert object to database try { c.insert(obj); } catch (MongoException e) { LOG.log(Level.WARNING, "Mongo DB exception while importing line " + count, e); } } } } catch (IOException e) { LOG.log(Level.WARNING, "IO exception while importing resource", e); } LOG.log( Level.INFO, "Imported {0} objects from {1} lines in collection {2}", new Object[] {c.getCount(), count, collection}); }
@Override public String IngresarJson(String nombreDB, String json, int clienteId) throws UnknownHostException { // TODO Auto-generated method stub MongoClient mongoClient = new MongoClient("localhost", 27017); DB base = mongoClient.getDB(nombreDB); // Ya existe if (ExisteCliente(nombreDB, clienteId)) { // System.out.println("********************\n"); // System.out.println("Ya existe cliente, error no se igresa el Json"); // System.out.println("********************\n"); return "Ya existe cliente, error no se igresa el Json"; } // no existe el cliente DBCollection collection = base.getCollection("Json"); BasicDBObject document = new BasicDBObject(); document.put("id", clienteId); DBObject object = (DBObject) JSON.parse(json); document.put("json", object); // document.put("json",json); collection.insert(document); return "Ok"; }
public JsonArray addPerfResults(String perfResults) { DBCollection coll = db.getCollection("performance"); BasicDBObject newPerfResults = (BasicDBObject) JSON.parse(perfResults); newPerfResults.append("_id", newPerfResults.getString("name")); BasicDBObject query = new BasicDBObject(); query.append("name", newPerfResults.getString("name")); BasicDBObject removeId = new BasicDBObject("_id", 0); DBCursor cursor = coll.find(query, removeId); JsonObjectBuilder objBuild = Json.createObjectBuilder(); JsonArrayBuilder arrBuild = Json.createArrayBuilder(); JsonObject json = objBuild.build(); if (cursor.count() > 0) { LOG.info("Performance Results Found: "); BasicDBObject found = (BasicDBObject) cursor.next(); json = Json.createReader(new StringReader(found.toString())).readObject(); arrBuild.add(json); } else { LOG.info("New Performance Results Created: " + coll.insert(newPerfResults)); json = Json.createReader(new StringReader(newPerfResults.toString())).readObject(); arrBuild.add(json); } LOG.info( "----------------------------------- ARR BUILD -------------------------------------------------\n" + arrBuild.build().toString()); return arrBuild.build(); }
@Override public String ActualizarJson(String nombreDB, String json, int clienteId) throws UnknownHostException { // TODO Auto-generated method stub if (!ExisteCliente(nombreDB, clienteId)) { // System.out.println("********************\n"); // System.out.println("No existe el cliente, no se puede actualizar"); // System.out.println("********************\n"); return "No existe el cliente, no se puede actualizar"; } MongoClient mongoClient = new MongoClient("localhost", 27017); DB base = mongoClient.getDB(nombreDB); DBCollection collection = base.getCollection("Json"); BasicDBObject document = new BasicDBObject(); DBObject object = (DBObject) JSON.parse(json); document.put("id", clienteId); document.put("json", object); BasicDBObject query = new BasicDBObject().append("id", clienteId); collection.findAndModify(query, document); return "Cliente actualizado"; }
@POST @Path("/queryMin") @Produces(MediaType.APPLICATION_JSON) @Consumes({MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN}) public String getMinimumField(String field) { String result = null; final ParameterQuerySender parameterQuerySenderService = (ParameterQuerySender) getServiceTracker().getService(); if (parameterQuerySenderService != null) { DBObject mongoQuery = new BasicDBObject(); Object qRes = parameterQuerySenderService.queryMin(mongoQuery, field); if (qRes instanceof List<?>) { List<?> dbResult = (List<?>) qRes; if (dbResult.size() == 1) { result = JSON.serialize(dbResult.get(0)); } else { LOG.error( "Expected only one result from database when querying for minimum value of a field! Received " + dbResult.size()); } } else { LOG.error("Object returned from the parameter archiver was not a List<?>"); } } else { LOG.warn("No " + SERVICE_INTERFACE + " service found."); } return result; }
/* * 用于复杂对象转换 e.g {key1:value1,key2:{key21:value21,key22:value22,...},key3:[value31,value32,...],...} * @param obj 需要转化的对象 */ public BasicDBObject converToMGObject(Object obj) { String jsonStr = JsonUtil.toJson(obj); BasicDBObject dbObject = (BasicDBObject) JSON.parse(jsonStr); return dbObject; }
public void LoadSTNSpeakers(String mapfile) throws Exception { String mongoTableName = "rwParty"; String xmlCollection = "SeedLOVMaps"; try { InputStream is = this.getClass().getResourceAsStream(mapfile); String xml; xml = IOUtils.toString(is); JSONObject rwSeed = XML.toJSONObject(xml); if (!rwSeed.isNull(xmlCollection)) { JSONObject json = rwSeed.getJSONObject(xmlCollection); DBCollection dbTable = store.getColl(mongoTableName); Object xmlRecords = (Object) json.get(mongoTableName); if (xmlRecords instanceof JSONArray == false) { JSONObject xmlRecord = (JSONObject) xmlRecords; JSONArray jAry = new JSONArray(); jAry.put(xmlRecord); xmlRecords = jAry; } if (xmlRecords instanceof JSONArray) { JSONArray xmlRecordAry = (JSONArray) xmlRecords; for (int i = 0; i < xmlRecordAry.length(); i++) { JSONObject xmlRecord = (JSONObject) xmlRecordAry.get(i); String parent_GlobalVal = xmlRecord.getString("parent_GlobalVal"); String child_GlobalVal = xmlRecord.getString("child_GlobalVal"); String parent_LovType = xmlRecord.getString("parent_LovType"); String child_LovType = xmlRecord.getString("child_LovType"); String childId = getLOVId(child_LovType, child_GlobalVal); String parentId = getLOVId(parent_LovType, parent_GlobalVal); xmlRecord.put("parentId", parentId); xmlRecord.put("childId", childId); dbTable.insert((DBObject) com.mongodb.util.JSON.parse(xmlRecord.toString())); } } else { dbTable.insert((DBObject) com.mongodb.util.JSON.parse(xmlRecords.toString())); } } } catch (IOException e) { // TODO Auto-generated catch block log.debug("API Error: ", e); } }
public DBObject parse(String line) { DBObject document = (DBObject) JSON.parse(line); // log.debug(MessageFormat.format(" Parsed {0} into {1} ", line, document )); System.out.println(MessageFormat.format(" Parsed {0} into {1} ", line, document)); return document; }