List of usage examples for com.mongodb DBObject removeField
Object removeField(String key);
From source file:act.shared.helpers.XMLToImportantChemicals.java
License:Open Source License
private void process(XMLStreamReader xml) throws XMLStreamException { String tag;/*w ww . ja v a2s. com*/ String root = null; Stack<DBObject> json = new Stack<DBObject>(); DBObject js; while (xml.hasNext()) { int eventType = xml.next(); while (xml.isWhiteSpace() || eventType == XMLEvent.SPACE) eventType = xml.next(); switch (eventType) { case XMLEvent.START_ELEMENT: tag = xml.getLocalName(); if (root == null) { root = tag; } else { json.push(new BasicDBObject()); } break; case XMLEvent.END_ELEMENT: tag = xml.getLocalName(); if (tag.equals(root)) { // will terminate in next iteration } else { js = json.pop(); if (json.size() == 0) { if (tag.equals(rowTag)) printEntry(js); else printUnwantedEntry(js); } else { putListStrOrJSON(json.peek(), tag, js); } } break; case XMLEvent.CHARACTERS: String txt = xml.getText(); js = json.peek(); if (js.containsField(strTag)) { txt = js.get(strTag) + txt; js.removeField(strTag); } js.put(strTag, txt); break; case XMLEvent.START_DOCUMENT: break; case XMLEvent.END_DOCUMENT: break; case XMLEvent.COMMENT: case XMLEvent.ENTITY_REFERENCE: case XMLEvent.ATTRIBUTE: case XMLEvent.PROCESSING_INSTRUCTION: case XMLEvent.DTD: case XMLEvent.CDATA: case XMLEvent.SPACE: System.out.format("%s --\n", eventType); break; } } }
From source file:act.shared.helpers.XMLToImportantChemicals.java
License:Open Source License
private void putElemOrList(DBObject json, String tag, Object add) { // if tag already present then make it a list if (json.containsField(tag)) { BasicDBList l;/*ww w.j a v a 2 s.co m*/ Object already = json.get(tag); if (already instanceof BasicDBList) { l = (BasicDBList) already; } else { l = new BasicDBList(); l.add(already); } l.add(add); json.removeField(tag); json.put(tag, l); return; } // else, just add as is json.put(tag, add); return; }
From source file:br.ufabc.impress.mongo.manager.DBHelper.java
@Override public List<Boolean> modifyNotOveride(String tableName, String json, String _id) { if (tableName == null || tableName.equals("") || json == null || json.equals("") || _id == null || _id.equals("")) { return null; }/*from w w w . j a va 2 s .co m*/ List<Boolean> resList = new ArrayList(); DBCollection table = db.getCollection(tableName); DBCursor cursor = table.find(); while (cursor.hasNext()) { DBObject updateDocument = cursor.next(); DBObject searchQuery = cursor.next(); DBObject dbObject = (DBObject) JSON.parse(json); updateDocument.putAll(dbObject.toMap()); updateDocument.removeField("_id"); WriteResult result = table.update(searchQuery, updateDocument); resList.add(result.isUpdateOfExisting()); } return resList; }
From source file:calliope.core.database.MongoConnection.java
License:Open Source License
/** * Get the metadata as a string/*from w w w.j ava 2s .c o m*/ * @param docid its filename or docid * @return the metadata of the document as a string */ public String getMetadata(String docid) { try { connect(); DBCollection collection = getCollectionFromName(Database.METADATA); DBObject query; query = new BasicDBObject(JSONKeys.DOCID, docid); DBObject obj = collection.findOne(query); if (obj != null) { obj.removeField(JSONKeys._ID); return obj.toString(); } else return null; } catch (Exception e) { e.printStackTrace(System.out); return null; } }
From source file:calliope.export.PDEFArchive.java
License:Open Source License
/** * Remove fields that will be added by the database after import * @param json the original JSON string/*from ww w . jav a2s . c om*/ * @return a possibly modified JSON string with the fields removed */ private String removeTabooFields(String json) { boolean changed = false; DBObject jdoc = (DBObject) JSON.parse(json); for (int i = 0; i < tabooFields.length; i++) { if (jdoc.containsField(tabooFields[i])) { jdoc.removeField(tabooFields[i]); changed = true; } } if (changed) json = jdoc.toString(); return json; }
From source file:ch.windmobile.server.social.mongodb.UserServiceImpl.java
License:Open Source License
@Override public List<Favorite> removeFromFavorites(String email, List<Favorite> favoritesToRemove) throws UserNotFound { if (email == null) { throw new IllegalArgumentException("Email cannot be null"); }//from w w w . ja va 2s .co m DBCollection col = db.getCollection(MongoDBConstants.COLLECTION_USERS); // Search user by email DBObject userDb = col.findOne(new BasicDBObject(MongoDBConstants.USER_PROP_EMAIL, email)); if (userDb == null) { throw new UserNotFound("Unable to find user with email '" + email + "'"); } DBObject favoritesDb = (DBObject) userDb.get(MongoDBConstants.USER_PROP_FAVORITES); if (favoritesDb == null) { favoritesDb = new BasicDBObject(); } if (favoritesToRemove != null) { for (Favorite favoriteToRemove : favoritesToRemove) { DBObject favoriteItemsDb = (DBObject) favoritesDb.get(favoriteToRemove.getStationId()); if (favoriteItemsDb != null) { favoritesDb.removeField(favoriteToRemove.getStationId()); } } } userDb.put(MongoDBConstants.USER_PROP_FAVORITES, favoritesDb); col.save(userDb); List<Favorite> returnValue = new ArrayList<Favorite>(favoritesDb.keySet().size()); for (String stationId : favoritesDb.keySet()) { Favorite favorite = new Favorite(); favorite.setStationId(stationId); DBObject favoriteItemDb = (DBObject) favoritesDb.get(stationId); favorite.setLastMessageId((Long) favoriteItemDb.get(MongoDBConstants.USER_PROP_FAVORITE_LASTMESSAGEID)); returnValue.add(favorite); } return returnValue; }
From source file:ch.windmobile.server.social.mongodb.UserServiceImpl.java
License:Open Source License
@Override public void clearFavorites(String email) throws UserNotFound { if (email == null) { throw new IllegalArgumentException("Email cannot be null"); }//from ww w . j a v a2s . co m DBCollection col = db.getCollection(MongoDBConstants.COLLECTION_USERS); // Search user by email DBObject userDb = col.findOne(new BasicDBObject(MongoDBConstants.USER_PROP_EMAIL, email)); if (userDb == null) { throw new UserNotFound("Unable to find user with email '" + email + "'"); } userDb.removeField(MongoDBConstants.USER_PROP_FAVORITES); col.save(userDb); }
From source file:com.andreig.jetty.QueryServlet.java
License:GNU General Public License
@Override protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { log.fine("doPost()"); // server auth if (!can_read(req)) { res.sendError(SC_UNAUTHORIZED);//from w ww . j av a2s . c om return; } String ret = null; 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:com.andreig.jetty.QueryServlet.java
License:GNU General Public License
@Override protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { log.fine("doGet()"); if (!can_read(req)) { res.sendError(SC_UNAUTHORIZED);/* w w w. jav a2 s .com*/ return; } 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"); 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); DBCursor c = col.find(); if (c == null || c.count() == 0) { 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(); 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); out_str(req, buf.toString(), "application/json"); }
From source file:com.andreig.jetty.SearchServlet.java
License:GNU General Public License
private String search2mongo(Document hits[], DBCollection col) { List<ObjectId> values = new ArrayList<ObjectId>(); for (Document hit : hits) { String _id = hit.get("_id"); ObjectId oid = ObjectId.massageToObjectId(_id); values.add(oid);//from ww w .j a v a2 s.co m } BasicDBObject q = new BasicDBObject(); q.put("_id", new BasicDBObject("$in", values)); DBCursor c = col.find(q); if (c == null || c.count() == 0) { return null; } StringBuilder buf = tl.get(); // 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(']'); return buf.toString(); }