List of usage examples for com.mongodb DBCollection save
public WriteResult save(final DBObject document)
From source file:rapture.sheet.mongodb.MongoCellStore.java
License:Open Source License
public void deleteRow(final String sheetName, final int row) { final DBCollection collection = MongoDBFactory.getDB(instanceName).getCollection(tableName); MongoRetryWrapper<Object> wrapper = new MongoRetryWrapper<Object>() { public DBCursor makeCursor() { // Deleting a column is two things. // (a) find and remove all cells (in all dimensions) that have // this as a // column // (b) modify all cells that have a column > this column, // decreasing // their column by 1 DBCollection collection = MongoDBFactory.getDB(instanceName).getCollection(tableName); BasicDBObject query = new BasicDBObject(); query.put(KEY, sheetName);//w w w . ja va2s.com query.put(ROW, row); collection.findAndRemove(query); BasicDBObject changeQuery = new BasicDBObject(); changeQuery.put(KEY, sheetName); BasicDBObject testQuery = new BasicDBObject(); testQuery.put("$gt", row); changeQuery.put(ROW, testQuery); return collection.find(changeQuery); } public Object action(DBCursor cursor) { while (cursor.hasNext()) { BasicDBObject object = (BasicDBObject) cursor.next(); object.put(ROW, object.getInt(ROW) - 1); object.put(EPOCH, getLatestEpoch(sheetName, object.getInt(DIM))); collection.save(object); } return null; } }; @SuppressWarnings("unused") Object o = wrapper.doAction(); }
From source file:tugas.TwitterLike.java
public boolean register(String username, String password) { try {/*from w w w . j av a 2 s. co m*/ // If already exist, will be replaced by new value DBCollection coll = db.getCollection(USER_COLLECTION); BasicDBObject doc = new BasicDBObject("username", username).append("password", password); coll.save(doc); return true; } catch (Exception e) { System.out.println(e); return false; } }
From source file:tugas.TwitterLike.java
public boolean followFriend(String username, String friendname) { try {/*from w ww . ja v a 2 s .c o m*/ DBCollection coll_friends = db.getCollection(FRIENDS_COLLECTION); DBCollection coll_follow = db.getCollection(FOLLOWERS_COLLECTION); String since = (new SimpleDateFormat("dd-MM-yyyy")).format(new Date()); BasicDBObject doc_friends = new BasicDBObject("username", username).append("friend", friendname) .append("since", since); BasicDBObject doc_follow = new BasicDBObject("username", friendname).append("friend", username) .append("since", since); coll_friends.save(doc_friends); coll_follow.save(doc_follow); return true; } catch (Exception e) { System.out.println(e); return false; } }
From source file:tugas.TwitterLike.java
public void postTweet(String username, String tweet) { UUID tweet_id = UUID.randomUUID(); //session.execute("INSERT INTO tweets (tweet_id, username, body) VALUES ("+tweet_id+", '" + username + "', '" + tweet + "')"); DBCollection tweets = db.getCollection(TWEETS_COLLECTION); DBCollection userlines = db.getCollection(USERLINE_COLLECTION); DBCollection timelines = db.getCollection(TIMELINE_COLLECTION); String time = new Date().toString(); BasicDBObject _tweet = new BasicDBObject("username", username).append("body", tweet).append("tweet_id", tweet_id.toString());//from w ww .j av a 2s .c o m BasicDBObject _userline = new BasicDBObject("username", username).append("time", time).append("tweet_id", tweet_id.toString()); BasicDBObject _timeline = new BasicDBObject("username", username).append("time", time).append("tweet_id", tweet_id.toString()); tweets.save(_tweet); userlines.save(_userline); timelines.save(_timeline); //search all followers of username BasicDBObject query = new BasicDBObject("username", username); List<String> followers = new ArrayList<String>(); Cursor results = db.getCollection(FOLLOWERS_COLLECTION).find(query); while (results.hasNext()) { followers.add(String.valueOf(results.next().get("follower"))); } for (String follower : followers) { _timeline = new BasicDBObject("username", follower).append("time", time).append("tweet_id", tweet_id.toString()); timelines.save(_timeline); } }
From source file:v7cr.AuthFilter.java
License:Open Source License
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { if (req instanceof HttpServletRequest) { HttpServletRequest request = (HttpServletRequest) req; HttpSession session = request.getSession(false); // Authentication if (session == null || session.getAttribute("v7cr.user") == null) { Authentication auth = null;//from w w w . ja va 2 s .co m if (session != null) { auth = (Authentication) session.getAttribute(OpenIDServlet.OPENID_AUTHENTICATION); } if (auth == null) { // check if an admin has already been registered Role admins = Roles.load(InitDB.getDBCollection(context, "roles"), "admin"); if (admins.getMembers().isEmpty()) { ((HttpServletResponse) resp).sendRedirect(request.getContextPath() + "/install.html"); return; } ((HttpServletResponse) resp).sendRedirect(request.getContextPath() + "/login.html"); return; } AccountInfo account = new AccountInfo(auth.getEmail(), auth.getFullname()); session.setAttribute("v7cr.user", account); } // Authorization session = request.getSession(false); if (session != null && session.getAttribute("v7cr.sessionInfo") == null) { AccountInfo account = (AccountInfo) session.getAttribute("v7cr.user"); if (account != null) { // check if this ID can log in Map<String, Role> roles = Roles.loadRoles(InitDB.getDBCollection(context, "roles"), account.getId()); if (!roles.containsKey("connect")) { // check if an admin has already been registered DBCollection ac = InitDB.getDBCollection(context, "roles"); Role admins = Roles.load(ac, "admin"); if (admins.getMembers().isEmpty()) { admins = admins.addMember(account); ac.save(new BasicDBObject(admins.getBSONObject())); roles = Roles.loadRoles(InitDB.getDBCollection(context, "roles"), account.getId()); } } if (!roles.containsKey("connect")) { throw new SecurityException(account.getId() + " is not allowed to connect"); } SessionInfo sessionInfo = new SessionInfo(); sessionInfo.accountInfo = account; sessionInfo.roles = roles; session.setAttribute("v7cr.sessionInfo", sessionInfo); } else { throw new SecurityException("Authentication information missing"); } } } chain.doFilter(req, resp); }
From source file:v7cr.InitDB.java
License:Open Source License
@SuppressWarnings("unchecked") public void contextInitialized(ServletContextEvent e) { try {/*from w w w. j av a 2 s .c om*/ Mongo db = new Mongo(); ServletContext c = e.getServletContext(); c.setAttribute(getClass().getName(), db); // check if the "roles" collection // exists, if not create it if (getDBCollection(c, "roles").findOne() == null) { String json = IOUtils.toString(getClass().getResourceAsStream("roles.json"), "UTF-8"); List<DBObject> l = (List<DBObject>) JSON.parse(json); DBCollection roles = getDBCollection(c, "roles"); for (DBObject r : l) { r.put("_version", 1); roles.save(r); } } } catch (Exception ex) { throw new RuntimeException(ex); } }
From source file:v7cr.OpenIDServlet.java
License:Open Source License
private void checkNonce(String nonce) { if (nonce == null) throw new SecurityException("openid.nonce is missing"); DBCollection nonces = InitDB.getDB(getServletContext()).getCollection("openid.nonce"); DBObject c = nonces.findOne(nonce);/* w ww .j av a 2s . c o m*/ if (c != null) throw new SecurityException("openid.nonce " + nonce + " has been used before"); nonces.save(new BasicDBObject("_id", nonce)); }
From source file:v7cr.RoleEditor.java
License:Open Source License
public void buttonClick(ClickEvent event) { String roleId = (String) rolesTab.getValue(); BeanItem<Role> role = roles.getItem(roleId); if (role == null) return;/*from w w w. j av a 2 s. c o m*/ DBCollection db = V7CR.getInstance().getDBCollection("roles"); Role r = Roles.load(db, roleId); Collection<?> selected = (Collection<?>) memberSelect.getValue(); DBObject o = new BasicDBObject(r.getBSONObject()); List<BSONObject> members = new ArrayList<BSONObject>(); for (Object s : selected) { BeanItem<AccountInfo> biai = (BeanItem<AccountInfo>) memberSelect.getContainerDataSource().getItem(s); members.add(biai.getBean().getBSONObject()); } o.put("member", members); db.save(o); }
From source file:xbdd.webapp.resource.feature.Feature.java
License:Apache License
@SuppressWarnings("unchecked") protected void updateTestingTips(final DB db, final Coordinates coordinates, final String featureId, final DBObject feature) { final DBCollection tips = db.getCollection("testingTips"); final List<DBObject> elements = (List<DBObject>) feature.get("elements"); for (final DBObject scenario : elements) { if (scenario.get("testing-tips") != null) { final String tipText = (String) scenario.get("testing-tips"); final String scenarioId = (String) scenario.get("id"); final BasicDBObject tipQuery = coordinates.getTestingTipsCoordinatesQueryObject(featureId, scenarioId);//from w w w . ja va 2 s. c om DBObject oldTip = null; // get the most recent tip that is LTE to the current coordinates. i.e. sort in reverse chronological order and take the // first item (if one exists). final DBCursor oldTipCursor = tips.find(tipQuery) .sort(new BasicDBObject("coordinates.major", -1).append("coordinates.minor", -1) .append("coordinates.servicePack", -1).append("coordinates.build", -1)) .limit(1); try { if (oldTipCursor.hasNext()) { oldTip = oldTipCursor.next(); } } finally { oldTipCursor.close(); } if (oldTip != null) { // if there is an old tip... final String oldTipText = (String) oldTip.get("testing-tips"); // get it and... if (!tipText.equals(oldTipText)) {// compare it to the current tip to it, if they're not the same... final DBObject newTip = new BasicDBObject("testing-tips", tipText) .append("coordinates", coordinates.getTestingTipsCoordinates(featureId, scenarioId)) .append("_id", coordinates.getTestingTipsId(featureId, scenarioId)); tips.save(newTip);// then save this as a new tip. } } else { // no prior tip exists, add this one. final DBObject newTip = new BasicDBObject("testing-tips", tipText) .append("coordinates", coordinates.getTestingTipsCoordinates(featureId, scenarioId)) .append("_id", coordinates.getTestingTipsId(featureId, scenarioId)); tips.save(newTip);// then save this as a new tip. } } scenario.removeField("testing-tips"); } }
From source file:xbdd.webapp.resource.feature.Feature.java
License:Apache License
/** * Uses the '.+' regexp on featureId to allow for symbols such as slashes in the id * * @param String featureId The featureId to make changes to * @return DBObjet Returns the the features new state if changes were made and returns null if bad JSON was sent *//* w w w. j a v a 2 s .c om*/ @PUT @Path("/{product}/{major}.{minor}.{servicePack}/{build}/{featureId:.+}") @Consumes("application/json") public DBObject putFeature(@BeanParam final Coordinates coordinates, @PathParam("featureId") final String featureId, @Context final HttpServletRequest req, final DBObject feature) { feature.put("calculatedStatus", StatusHelper.getFeatureStatus(feature)); try { final DB db = this.client.getDB("bdd"); final DBCollection collection = db.getCollection("features"); final BasicDBObject example = coordinates.getReportCoordinatesQueryObject().append("id", featureId); final DBObject report = collection.findOne(example); // get the differences/new edits // Detect if the edits caused a change feature.put("statusLastEditedBy", req.getRemoteUser()); feature.put("lastEditOn", new Date()); final BasicDBList edits = updateEdits(feature, report); feature.put("edits", edits); updateTestingTips(db, coordinates, featureId, feature); // save testing tips / strip them out of the document. updateEnvironmentDetails(db, coordinates, feature); collection.save(feature); Feature.embedTestingTips(feature, coordinates, db); // rembed testing tips. return feature;// pull back feature - will re-include tips that were extracted prior to saving } catch (final Throwable th) { th.printStackTrace(); return null; } }