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:net.jurre.edutil.persistence.MongoDB.java
License:Open Source License
private void saveData(String data, String collectionName) { BasicDBObject dataObj = (BasicDBObject) JSON.parse(data); DBCollection collection = this.db.getCollection(collectionName); if (!dataObj.containsField("_id")) { if (dataObj.containsField("id")) dataObj.append("_id", dataObj.get("id")); }/*from w ww.j ava 2 s . co m*/ /* BasicDBObject search = new BasicDBObject(); search.put("name", dataObj.getString("name")); DBObject lookup = collection.findOne(search); if ( lookup != null){ dataObj.append("_id", lookup.get("_id")); logger.debug("Found id adding to object"); } */ collection.save(dataObj); }
From source file:net.kamradtfamily.mongorest.AggregateServlet.java
License:GNU General Public License
@Override protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { log.fine("doPost()"); 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;/*w w w. j av a2s . c om*/ } 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:net.kamradtfamily.mongorest.DistinctServlet.java
License:GNU General Public License
@Override protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { log.fine("doPost()"); 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];/* ww w .j a v a 2s . c o m*/ 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.isEmpty()) { 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"); }
From source file:net.kamradtfamily.mongorest.IndexServlet.java
License:GNU General Public License
@Override protected void doPut(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { log.fine("doPut()"); 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;//from ww w. j a va 2 s .c o m } DB db = mongo.getDB(db_name); // mongo auth String user = req.getParameter("user"); String passwd = req.getParameter("passwd"); if (user != null && passwd != null && (!db.isAuthenticated())) { boolean auth = db.authenticate(user, passwd.toCharArray()); if (!auth) { res.sendError(SC_UNAUTHORIZED); return; } } DBCollection col = db.getCollection(col_name); BufferedReader r = null; String data = null; try { r = new BufferedReader(new InputStreamReader(is)); data = r.readLine(); } finally { if (r != null) r.close(); } if (data == null) { error(res, SC_BAD_REQUEST, Status.get("no data")); return; } DBObject o; try { o = (DBObject) JSON.parse(data); } catch (JSONParseException e) { error(res, SC_BAD_REQUEST, Status.get("can not parse data")); return; } col.createIndex(o); res.setStatus(SC_CREATED); }
From source file:net.kamradtfamily.mongorest.IndexServlet.java
License:GNU General Public License
@Override protected void doDelete(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { log.fine("doDelete()"); 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;// w w w.ja v a 2s . com } BufferedReader r = null; String data = null; try { r = new BufferedReader(new InputStreamReader(is)); data = r.readLine(); } finally { if (r != null) r.close(); } if (data == null) { error(res, SC_BAD_REQUEST, Status.get("no data")); return; } DBObject o; try { o = (DBObject) JSON.parse(data); } catch (JSONParseException e) { error(res, SC_BAD_REQUEST, Status.get("can not parse data")); return; } DB db = mongo.getDB(db_name); // mongo auth String user = req.getParameter("user"); String passwd = req.getParameter("passwd"); if (user != null && passwd != null && (!db.isAuthenticated())) { boolean auth = db.authenticate(user, passwd.toCharArray()); if (!auth) { res.sendError(SC_UNAUTHORIZED); return; } } DBCollection col = db.getCollection(col_name); col.dropIndex(o); res.setStatus(SC_OK); }
From source file:net.kamradtfamily.mongorest.QueryServlet.java
License:GNU General Public License
@Override protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { log.fine("doPost()"); // server auth String ret;/* w ww .ja va 2s.c om*/ InputStream is = req.getInputStream(); String db_name = req.getParameter("dbname"); String col_name = req.getParameter("colname"); 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; } } String skip = req.getParameter("skip"); String limit = req.getParameter("limit"); String _fields = req.getParameter("fields"); String fields[] = null; if (_fields != null) fields = _fields.split("[,]"); DB db = mongo.getDB(db_name); // mongo auth String user = req.getParameter("user"); String passwd = req.getParameter("passwd"); if (user != null && passwd != null && (!db.isAuthenticated())) { boolean auth = db.authenticate(user, passwd.toCharArray()); if (!auth) { res.sendError(SC_UNAUTHORIZED); return; } } DBCollection col = db.getCollection(col_name); StringBuilder buf = tl.get(); // reset buf buf.setLength(0); 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); if (cache != null) { buf.append(db_name); buf.append(col_name); buf.append(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; } if (cache != null) buf.append(data); } } finally { if (r != null) r.close(); } // limit int lim; if (limit != null) { try { lim = Math.min(Integer.parseInt(limit), MAX_FIELDS_TO_RETURN); } catch (NumberFormatException e) { error(res, SC_BAD_REQUEST, Status.get("can not parse limit")); return; } } else { lim = MAX_FIELDS_TO_RETURN; } if (cache != null) { buf.append(";limit="); buf.append(lim); } // skip int sk = -1; if (skip != null) { try { sk = Integer.parseInt(skip); if (cache != null) { buf.append(";skip="); buf.append(sk); } } catch (NumberFormatException e) { error(res, SC_BAD_REQUEST, Status.get("can not parse skip")); return; } } // fields if (cache != null && _fields != null) { buf.append(";fields="); buf.append(_fields); } // from cache String cache_key = null; if (cache != null) { cache_key = buf.toString(); try { ret = (String) cache.get(cache_key); } // some wrong char in key catch (IllegalArgumentException e) { int l = buf.length(); for (int i = 0; i < l; i++) { if (buf.charAt(i) == ' ') buf.setCharAt(i, '*'); } cache_key = buf.toString(); ret = (String) cache.get(cache_key); } if (ret != null) { out_str(req, ret, "application/json"); return; } } // cursor DBCursor c; if (fields != null) { StringBuilder sb = new StringBuilder(); sb.append("{"); int len = fields.length; for (int i = 0; i < len; i++) { String s = fields[i]; sb.append('"'); sb.append(s); sb.append('"'); sb.append(":1"); if (i != (len - 1)) sb.append(","); } sb.append("}"); c = col.find(q, (DBObject) JSON.parse(sb.toString())); } else c = col.find(q); if (c == null || c.count() == 0) { error(res, SC_NOT_FOUND, Status.get("no documents found")); return; } if (sort != null) c.sort(sort); res.setIntHeader("X-Documents-Count", c.count()); c.limit(lim); if (sk != -1) c.skip(sk); // reset buf buf.setLength(0); int no = 0; buf.append("["); while (c.hasNext()) { DBObject o = c.next(); if (rm_id) o.removeField("_id"); JSON.serialize(o, buf); buf.append(","); no++; } c.close(); if (no > 0) buf.setCharAt(buf.length() - 1, ']'); else buf.append(']'); res.setIntHeader("X-Documents-Returned", no); ret = buf.toString(); if (cache != null) cache.set(cache_key, ret); out_str(req, ret, "application/json"); }
From source file:nl.kpmg.af.service.data.DatabaseInitialiser.java
License:Apache License
private void loadMockData(List<String> mockFiles) throws IOException { for (String mockFile : mockFiles) { String[] split = mockFile.split("\\."); DB database = mockDatabase.mongoClient.getDB(split[0]); Path filePath = Paths.get(".", "src", "test", "resources", "mock", mockFile); BufferedReader jsonReader = Files.newBufferedReader(filePath, StandardCharsets.UTF_8); StringBuilder json;/*from ww w .ja va2 s . c o m*/ for (json = new StringBuilder(); jsonReader.ready(); json.append(jsonReader.readLine())) { } BasicDBList mockData = (BasicDBList) JSON.parse(json.toString()); WriteResult insert = database.createCollection(split[1], new BasicDBObject()) .insert(mockData.toArray(new BasicDBObject[mockData.size()]), database.getWriteConcern()); } }
From source file:nosqltools.DBConnection.java
/** * Saves a collection to the DB// w ww. ja v a 2s . c o m * @param JSON string */ public boolean saveColl(String json) { BasicDBList objList = null; List<Object> documents = new ArrayList<>(); boolean parse_error = false; //Get the string from text area and typecast to basic db list and dbobjects respectively try { objList = (BasicDBList) JSON.parse(json); parse_error = true; //Add objects to array list for (int i = 0; i < objList.size(); i++) { documents.add(objList.get(i)); } //Save each document to collection for (int i = 0; i < documents.size(); i++) { DBObject object = (DBObject) documents.get(i); collection.save(object); } } catch (Exception e) { parse_error = false; } return parse_error; }
From source file:nosqltools.DBConnection.java
/** * Inserts a JSON objects into the collection * @param JSON object as a string/* w w w . j a va 2 s. co m*/ * @return true if insert operation was unsuccessful, else false */ public boolean insertInDatabase(String obj) { boolean flag = true; try { //If the object passed as a parameter is a JSON array, it is rejected if (json_util.isArray(obj)) { JOptionPane.showMessageDialog(null, "JSON Arrays are not allowed - Insert only one JSON object!", "Error", JOptionPane.ERROR_MESSAGE); } else //If the object passed as a parameter is a JSON object { //If the object is not empty if (!obj.isEmpty()) { //Parse the object and insert into the collection flag = false; DBObject dbobj = (DBObject) JSON.parse(obj); collection.insert(dbobj); JOptionPane.showMessageDialog(null, "JSON Object " + dbobj + " has been added to Collection!", "Inserted Successfully", JOptionPane.INFORMATION_MESSAGE); } } } catch (MongoException me) { JOptionPane.showMessageDialog(null, me.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } return flag; }
From source file:nosqltools.DBConnection.java
/** * // w w w .ja v a2 s. c om * @param obj1 * @param obj2 * @return */ public boolean updateDatabase(String obj1, String obj2) { boolean flag = false; try { if (json_util.isArray(obj1) || json_util.isArray(obj2)) { JOptionPane.showMessageDialog(null, "JSON Arrays are not allowed - Change details for only one JSON object!", "Error", JOptionPane.ERROR_MESSAGE); } else { DBObject dbobj1 = (DBObject) JSON.parse(obj1); DBObject dbobj2 = (DBObject) JSON.parse(obj2); DBCursor cursor = collection.find(dbobj1); int count = cursor.count(); if (cursor.count() == 0) { flag = true; JOptionPane.showMessageDialog(null, "JSON object " + dbobj1 + " does not exist in collection!", "Error", JOptionPane.ERROR_MESSAGE); } else { while (count != 0) { while (cursor.hasNext()) { System.out.println(cursor.next()); } if (count != 0) collection.update(dbobj1, dbobj2, true, false); count--; } JOptionPane.showMessageDialog(null, "JSON Object " + dbobj2 + " has been updated to Collection!", "Updated Successfully", JOptionPane.INFORMATION_MESSAGE); } } } catch (MongoException me) { JOptionPane.showMessageDialog(null, me.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } return flag; }