List of usage examples for com.mongodb.util JSON parse
public static Object parse(final String jsonString)
Parses a JSON string and returns a corresponding Java object.
From source file:com.appdynamics.monitors.mongo.MongoDBMonitor.java
License:Apache License
private DBObject executeMongoCommand(MongoDatabase db, Document command) { DBObject dbObject = null;//from w w w .j a v a 2 s . c om try { dbObject = (DBObject) JSON.parse(db.runCommand(command).toJson()); /*if (dbStats != null && !dbStats.getOk().toString().equals(OK_RESPONSE)) { logger.error("Error retrieving db stats. Invalid permissions set for this user.DB= " + db.getName()); }*/ } catch (MongoCommandException e) { logger.error("Error while executing " + command + " for db " + db, e); } return dbObject; }
From source file:com.appdynamics.monitors.mongo.MongoDBMonitor.java
License:Apache License
private void fetchAndPrintCollectionStats() { for (String databaseName : mongoClient.listDatabaseNames()) { DB db = mongoClient.getDB(databaseName); Set<String> collectionNames = db.getCollectionNames(); if (collectionNames != null && collectionNames.size() > 0) { for (String collectionName : collectionNames) { DBCollection collection = db.getCollection(collectionName); CommandResult collectionStatsResult = collection.getStats(); if (collectionStatsResult != null && collectionStatsResult.ok()) { DBObject collectionStats = (DBObject) JSON.parse(collectionStatsResult.toString()); printCollectionStats(db.getName(), collectionName, collectionStats); } else { String errorMessage = "Retrieving stats for collection " + collectionName + " of " + db.getName() + " failed"; if (collectionStatsResult != null) { errorMessage = errorMessage .concat(" with error message " + collectionStatsResult.getErrorMessage()); }//from w w w . j a va 2 s . com logger.error(errorMessage); } } } } }
From source file:com.badger.observationmongotest.execute.Main.java
public static void main(String[] args) throws ParseException, UnknownHostException, IOException { List<Observation> observations = new LinkedList(); Customer customer = new Customer(); customer.setName("Mr Customer"); customer.setId("cid123"); customer.setBackOfficeId("boid123"); SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd"); String dateStr = "2015/08/10"; Date date = format.parse(dateStr); CustomerObservationReport report = new CustomerObservationReport(customer); MonthlyProductOrderCountIssue productOrderCountIssue = new MonthlyProductOrderCountIssue(); productOrderCountIssue.setActionRequired(true); productOrderCountIssue.setCatagory("product issue"); productOrderCountIssue.setCurrentYear(2015); productOrderCountIssue.setCurrentYearValue(30); productOrderCountIssue.setCustomerId(customer.getId()); productOrderCountIssue.setDate(date); productOrderCountIssue.setDrop(50.0); productOrderCountIssue.setLastYearValue(60); productOrderCountIssue.setMonth("Feb"); productOrderCountIssue.setObservationId("oid123"); productOrderCountIssue.setPreviousYear(2014); productOrderCountIssue.setProductName("cool product"); productOrderCountIssue.setScore(4500); productOrderCountIssue.setType("monthy order count"); MonthlyProductOrderCountIssue monthlyProductOrderCountIssue = new MonthlyProductOrderCountIssue(); monthlyProductOrderCountIssue.setActionRequired(true); monthlyProductOrderCountIssue.setCatagory("product issue"); monthlyProductOrderCountIssue.setCurrentYear(2015); monthlyProductOrderCountIssue.setCurrentYearValue(30); monthlyProductOrderCountIssue.setCustomerId(customer.getId()); monthlyProductOrderCountIssue.setDate(date); monthlyProductOrderCountIssue.setDrop(50.0); monthlyProductOrderCountIssue.setLastYearValue(60); monthlyProductOrderCountIssue.setMonth("March"); monthlyProductOrderCountIssue.setObservationId("oid456"); monthlyProductOrderCountIssue.setPreviousYear(2014); monthlyProductOrderCountIssue.setProductName("cool product"); monthlyProductOrderCountIssue.setScore(4500); monthlyProductOrderCountIssue.setType("monthy order count"); MonthlyProductRevenueIssue monthlyProductRevenueIssue = new MonthlyProductRevenueIssue(); monthlyProductRevenueIssue.setActionRequired(true); monthlyProductRevenueIssue.setCatagory("product issue"); monthlyProductRevenueIssue.setCurrentYear(2015); monthlyProductRevenueIssue.setCurrentYearValue(3000.00); monthlyProductRevenueIssue.setCustomerId(customer.getId()); monthlyProductRevenueIssue.setDate(date); monthlyProductRevenueIssue.setDrop(50.0); monthlyProductRevenueIssue.setLastYearValue(6000.00); monthlyProductRevenueIssue.setMonth("Dec"); monthlyProductRevenueIssue.setObservationId("oid3445"); monthlyProductRevenueIssue.setPreviousYear(2014); monthlyProductRevenueIssue.setProductName("test product"); monthlyProductRevenueIssue.setScore(5667); monthlyProductRevenueIssue.setType("monthly product ervenue"); MonthlyRevenueIssue monthlyRevenueIssue = new MonthlyRevenueIssue(); monthlyRevenueIssue.setActionRequired(true); monthlyRevenueIssue.setCatagory("Reveue Issue"); monthlyRevenueIssue.setCurrentValue(3000); monthlyRevenueIssue.setCurrentYear(2015); monthlyRevenueIssue.setCustomerId(customer.getId()); monthlyRevenueIssue.setDate(date);//from w w w.j a v a 2s . co m monthlyRevenueIssue.setDrop(45.0); monthlyRevenueIssue.setMonth("Nov"); monthlyRevenueIssue.setObservationId("oid4646646"); monthlyRevenueIssue.setPreviousValue(5000); monthlyRevenueIssue.setPreviousYear(2014); monthlyRevenueIssue.setScore(5600); monthlyRevenueIssue.setType("monthly revenue issue"); observations.add(monthlyRevenueIssue); observations.add(monthlyProductRevenueIssue); observations.add(monthlyProductOrderCountIssue); observations.add(productOrderCountIssue); report.setAccountId("acid123"); report.addObservations(observations); // BasicDBObject documentDetail = new BasicDBObject(); /** * documentDetail.put("accountId", report.getAccountId()); * documentDetail.put("customerId", report.getCustomerId()); * documentDetail.put("Observations", * report.getObservations().toString()); * */ MongoClient mongo = new MongoClient("localhost", 27017); DB db = mongo.getDB("ObservationReports"); DBCollection col = db.getCollection("reports"); Gson gson = new Gson(); String json = gson.toJson(report); DBObject dbObject = (DBObject) JSON.parse(json); col.insert(dbObject); //DBObject query = BasicDBObjectBuilder.start().add("_id", report.getId()).get(); DBCursor cursor = col.find(); while (cursor.hasNext()) { System.out.println("First Cursor: " + cursor.next().get("observations")); } while (cursor.hasNext()) { DBObject dbobj = cursor.next(); Map map = dbObject.toMap(); CustomerObservationReport report2 = new CustomerObservationReport(customer); //System.out.println("observations " +dbObject.get("observations")); List<Observation> dbObservations = (List<Observation>) dbObject.get("observations"); report2.setAccountId(report.getAccountId()); report2.setCustomerId(report.getCustomerName()); report2.setBackOfficeId(report.getBackOfficeId()); report2.setObservations((dbObservations)); System.out.println(report2.getClass().getTypeName()); } }
From source file:com.caci.dummyserver.InstanceEndpointDefinition.java
private Boolean doIdsMatch(List<Pair<String, String>> keys, String json, String table) { DBObject obj = json != null && !json.equals("") ? (DBObject) JSON.parse(json) : null; if (obj == null) { return false; }/* w ww . j a v a2 s. com*/ Collection<String> jsonFields = obj.keySet(); for (Pair<String, String> key : keys) { String keyName = key.getKey(); String jsonField = keyName.equals(":" + table) ? "id" : keyName.substring(1); if (!jsonFields.contains(jsonField) || !key.getValue().equals(obj.get(jsonField).toString())) { return false; } break; } return true; }
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()); }/* w w w . ja v a2 s .c om*/ 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
/** * 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. *//* w w w .ja va 2 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.cc.manage.logic.BcompanyapplyLogic.java
/** * ?/* w w w. ja va 2 s .c o m*/ * * @param request * @return */ public JSONObject getDetailInfo(HttpServletRequest request) { DBObject conditionBean = new BasicDBObject(); String table = RequestUtils.getString(request, "table"); List<DBObject> List = new ArrayList<DBObject>(); String scheduleList = this.scheduleList(request); if (StringUtils.isNotBlank(scheduleList)) { // ? JSONArray json = JSONArray.fromObject(scheduleList); for (int i = 0; i < json.size(); i++) { JSONObject obj = json.getJSONObject(i); // ?????? conditionBean.put("flowid", JSONUtils.getString(obj, "flowno")); Object checks = commonDaoImpl.searchCommon(table, conditionBean);// b_companyapply if (checks != null) { JSONArray jsonarray = JSONArray.fromObject(checks); for (int j = 0; j < jsonarray.size(); j++) { JSONObject jo = jsonarray.getJSONObject(j); String objString = jo.toString().substring(1, jo.toString().length() - 1);// {}? // ??? String newString = obj.toString().substring(0, obj.toString().length() - 1) + AplicationKeyConstant.STRING_SPLIT_CHAR + objString + obj.toString().substring(obj.toString().length() - 1, obj.toString().length()); // StringDBobject DBObject object = (DBObject) JSON.parse(newString); List.add(object); } } } JSONObject resultBean = new JSONObject(); JSONArray jsons = JSONUtils.resertJSON(List);// _id resultBean.put("data", jsons.toString()); resultBean.put("total", jsons.size()); return resultBean; } return null; }
From source file:com.cetsoft.caudit.observers.MongoObserver.java
License:Apache License
public void onAuditEvent(AuditEvent auditEvent) { DBObject dbObject = (DBObject) JSON.parse(auditEvent.toJSON()); collection.insert(dbObject); }
From source file:com.cyslab.craftvm.rest.mongo.AggregateServlet.java
License:GNU General Public License
@Override protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { log.trace("doPost()"); if (!can_read(req)) { res.sendError(SC_UNAUTHORIZED);//from w w w . j av a2 s .c o m return; } InputStream is = req.getInputStream(); String db_name = req.getParameter("dbname"); String col_name = req.getParameter("colname"); if (db_name == null || col_name == null) { error(res, SC_BAD_REQUEST, Status.get("param name missing")); return; } String skip = req.getParameter("skip"); String limit = req.getParameter("limit"); DB db = mongo.getDB(db_name); DBCollection col = db.getCollection(col_name); BufferedReader r = null; DBObject q = null, sort = null; try { r = new BufferedReader(new InputStreamReader(is)); String data = r.readLine(); if (data == null) { error(res, SC_BAD_REQUEST, Status.get("no data")); return; } try { q = (DBObject) JSON.parse(data); } catch (JSONParseException e) { error(res, SC_BAD_REQUEST, Status.get("can not parse data")); return; } // sort param data = r.readLine(); if (data != null) { try { sort = (DBObject) JSON.parse(data); } catch (JSONParseException e) { error(res, SC_BAD_REQUEST, Status.get("can not parse sort arg")); return; } } } finally { if (r != null) r.close(); } DBCursor c; if (sort == null) c = col.find(q); else c = col.find(q).sort(sort); if (c == null) { error(res, SC_NOT_FOUND, Status.get("no documents found")); return; } res.setIntHeader("X-Documents-Count", c.count()); if (limit != null) { try { c.limit(Math.min(Integer.parseInt(limit), MAX_FIELDS_TO_RETURN)); } catch (NumberFormatException e) { error(res, SC_BAD_REQUEST, Status.get("can not parse limit")); c.close(); return; } } else c.limit(MAX_FIELDS_TO_RETURN); if (skip != null) { try { c.skip(Integer.parseInt(skip)); } catch (NumberFormatException e) { error(res, SC_BAD_REQUEST, Status.get("can not parse skip")); c.close(); return; } } StringBuilder buf = tl.get(); // reset buf buf.setLength(0); int no = 0; buf.append("["); while (c.hasNext()) { DBObject o = c.next(); JSON.serialize(o, buf); buf.append(","); no++; } if (no > 0) buf.setCharAt(buf.length() - 1, ']'); else buf.append(']'); res.setIntHeader("X-Documents-Returned", no); out_str(req, buf.toString(), "application/json"); }
From source file:com.cyslab.craftvm.rest.mongo.DistinctServlet.java
License:GNU General Public License
@Override protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { log.trace("doPost()"); if (!can_read(req)) { res.sendError(SC_UNAUTHORIZED);//from w ww . ja v a2 s . c o m return; } InputStream is = req.getInputStream(); String db_name = req.getParameter("dbname"); String col_name = req.getParameter("colname"); String key = req.getParameter("key"); if (db_name == null || col_name == null) { String names[] = req2mongonames(req); if (names != null) { db_name = names[0]; col_name = names[1]; } if (db_name == null || col_name == null) { error(res, SC_BAD_REQUEST, Status.get("param name missing")); return; } } if (key == null) { error(res, SC_BAD_REQUEST, Status.get("param name missing")); return; } DB db = mongo.getDB(db_name); DBCollection col = db.getCollection(col_name); BufferedReader r = null; DBObject q = null; try { r = new BufferedReader(new InputStreamReader(is)); String data = r.readLine(); if (data == null) { error(res, SC_BAD_REQUEST, Status.get("no data")); return; } try { q = (DBObject) JSON.parse(data); } catch (JSONParseException e) { error(res, SC_BAD_REQUEST, Status.get("can not parse data")); return; } } finally { if (r != null) r.close(); } List l = col.distinct(key, q); if (l == null || l.size() == 0) { error(res, SC_NOT_FOUND, Status.get("no documents found")); return; } res.setIntHeader("X-Documents-Count", l.size()); StringBuilder buf = tl.get(); // reset buf buf.setLength(0); JSON.serialize(l, buf); out_str(req, buf.toString(), "application/json"); }