List of usage examples for com.mongodb DBCollection update
public WriteResult update(final DBObject query, final DBObject update)
From source file:edu.wayne.cs.fms.controller.CRUD.java
public static void Update(String id, FlightInfo newInfo, MongoClient mongoClient) { //MongoClient mongoClient = Connector.connect("localhost", 27017); DB db = mongoClient.getDB("project"); DBCollection flight = db.getCollection("flight"); ObjectId oId = new ObjectId(id); BasicDBObject query0 = new BasicDBObject("_id", oId); BasicDBObject query = new BasicDBObject("FL_DATE", newInfo.getDate()).append("UNIQUE_CARRIER", newInfo.getCarrier());/*from w ww .ja v a 2 s. c o m*/ query.append("FL_NUM", newInfo.getTailNum()).append("ORIGIN_CITY_NAME", newInfo.getDepCity()); query.append("DEST_CITY_NAME", newInfo.getArrCity()).append("CRS_DEP_TIME", newInfo.getCrsDepTime()); query.append("CRS_ARR_TIME", newInfo.getCrsArrTime()).append("DISTANCE", newInfo.getDistance()); query.append("CANCELLED", newInfo.getCancel()); if (newInfo.getCancel() == 0) { query.append("DEP_TIME", newInfo.getDepTime()).append("DEP_DELAY", newInfo.getDepDelay()); query.append("ARR_TIME", newInfo.getArrTime()).append("ARR_DELAY", newInfo.getArrDelay()); } System.out.println(query0); System.out.println(query); flight.update(query0, query); //mongoClient.close(); }
From source file:ezbake.locksmith.db.RsaLocksmithManager.java
License:Apache License
@Override public byte[] insertKey(String keyId, byte[] keyData, String owner, String... sharedWith) throws KeyExistsException { byte[] insertedKey = keyData; if (!keyExists(keyId)) { BasicDBObject doc = new BasicDBObject(KEY_ID, keyId).append(KEY_DATA, keyData).append(KEY_OWNER, owner) .append(ACCESS_LIST, sharedWith); mongoService.insertDocumentIntoCollection(getTableName(), doc); } else {/*from www .j a v a 2 s.c o m*/ // Try to claim ownership DBObject keyQuery = keyQuery(keyId); DBObject projection = new BasicDBObject(KEY_OWNER, 1).append(KEY_DATA, 1); Iterator<DBObject> it = mongoService.findInCollection(getTableName(), keyQuery, projection).iterator(); if (it.hasNext()) { DBObject obj = it.next(); String keyOwner = (String) obj.get(KEY_OWNER); insertedKey = (byte[]) obj.get(KEY_DATA); if (keyOwner == null) { // Take ownership DBObject upd = new BasicDBObjectBuilder().push("$set").add(KEY_OWNER, owner).pop().get(); DBCollection coll = mongoService.getMongoDB().getCollection(getTableName()); coll.update(keyQuery, upd); } else { throw new KeyExistsException("The keyId [" + keyId + "] Already Exists."); } } } return insertedKey; }
From source file:GeoHazardServices.Inst.java
License:Apache License
@POST @Path("/data_insert") @Produces(MediaType.APPLICATION_JSON)//from ww w . j ava 2s . c o m public String data_insert(@Context HttpServletRequest request, @FormParam("inst") String inst, @FormParam("secret") String secret, @FormParam("id") String id, @FormParam("name") String name, @FormParam("lon") Double lon, @FormParam("lat") Double lat, @FormParam("mag") Double mag, @FormParam("slip") Double slip, @FormParam("length") Double length, @FormParam("width") Double width, @FormParam("depth") Double depth, @FormParam("dip") Double dip, @FormParam("strike") Double strike, @FormParam("rake") Double rake, @FormParam("date") String dateStr, @FormParam("sea_area") String sea_area, @FormParam("root") String root, @FormParam("parent") String parent, @FormParam("comp") Integer comp, @FormParam("accel") Integer accel, @FormParam("gridres") Integer gridres, @FormParam("apikey") String apikey, @FormParam("algo") @DefaultValue("easywave") String algo) { /* Check for invalid parameter configurations. */ if ((inst != null || secret != null) && apikey != null) return jsfailure("Don't mix 'apikey' and 'secret'."); if (mag != null && (slip != null || length != null || width != null)) return jsfailure("Don't mix 'mag' with 'slip', 'length' and 'width'."); /* Support 'inst' and 'secret' for compatibility reasons. */ if (inst != null && secret != null) { /* Obtain the 'apikey' and pretend a call to the new api. */ DBObject query = new BasicDBObject("name", inst).append("secret", secret); DBObject tmp_inst = db.getCollection("institutions").findOne(query); if (tmp_inst == null) return jsdenied(); apikey = (String) ((DBObject) tmp_inst.get("api")).get("key"); if (apikey == null) return jsfailure("No 'apikey' set for this institution!"); } /* Continue with the new API. */ Object[] required = { apikey, id, name, dateStr }; if (!checkParams(request, required)) return jsfailure(); DBObject db_user = auth_api(apikey, "user"); DBObject db_inst = auth_api(apikey, "inst"); /* check if we got a valid institution and the correct secret */ ObjectId user_id; String user_name; User user; if (db_user != null) { user_id = (ObjectId) db_user.get("_id"); user_name = (String) db_user.get("username"); user = new User(db_user, getInst(db_user)); } else if (db_inst != null) { user_id = (ObjectId) db_inst.get("_id"); user_name = (String) db_inst.get("name"); user = new Inst(db_inst); } else { return jsdenied(); } System.out.println(user.name + " - " + user.inst); /* get Date object from date string */ System.out.println(dateStr); Date date = parseIsoDate(dateStr); if (date == null) return jsfailure("Invalid date format."); System.out.println(id); /* get current timestamp */ Date timestamp = new Date(); /* create new sub object that stores the properties */ BasicDBObject sub = new BasicDBObject(); sub.put("date", date); sub.put("region", name); sub.put("latitude", lat); sub.put("longitude", lon); sub.put("magnitude", mag); sub.put("slip", slip); sub.put("length", length); sub.put("width", width); sub.put("depth", depth); sub.put("dip", dip); sub.put("strike", strike); sub.put("rake", rake); sub.put("sea_area", sea_area); if (accel == null) accel = 1; /* create new DB object that should be added to the eqs collection */ BasicDBObject obj = new BasicDBObject(); obj.put("id", id); obj.put("user", user_id); obj.put("timestamp", timestamp); obj.put("prop", sub); obj.put("root", root); obj.put("parent", parent); obj.put("accel", accel); //obj.put( "gridres", gridres ); /* create a new event */ BasicDBObject event = new BasicDBObject(); event.put("user", user_id); event.put("timestamp", timestamp); event.put("event", "new"); Long refineId = 0L; /* get earthquake collection */ DBCollection coll = db.getCollection("eqs"); /* search for given id */ BasicDBObject inQuery = new BasicDBObject("id", id).append("user", user_id); DBCursor cursor = coll.find(inQuery).sort(new BasicDBObject("refineId", -1)); BasicDBObject entry = null; /* if id is already used, make a refinement */ if (cursor.hasNext()) { /* get properties of returned entry */ entry = (BasicDBObject) cursor.next(); /* update entry ID in database by appending deprecated field */ BasicDBObject depr = new BasicDBObject("depr", true); coll.update(entry, new BasicDBObject("$set", depr)); refineId = (Long) entry.get("refineId"); if (refineId == null) { refineId = new Long(0); } refineId++; /* override parent and root attributes */ root = entry.get("root") == null ? (String) entry.get("_id") : (String) entry.get("root"); obj.put("root", root); obj.put("parent", entry.get("_id")); /* override event type */ event.put("event", "update"); } /* set refinement and compound Ids */ final CompId compId = new CompId(user_name, id, refineId); obj.put("_id", compId.toString()); obj.put("refineId", refineId); event.put("id", compId.toString()); /* clean up query */ cursor.close(); /* insert object into 'eqs' collection */ coll.insert(obj); System.out.println(obj); Object[] reqComp1 = { id, lon, lat, mag, depth, dip, strike, rake }; Object[] reqComp2 = { id, lon, lat, slip, length, width, depth, dip, strike, rake }; boolean simulate = comp != null && (checkParams(request, reqComp1) || checkParams(request, reqComp2)); /* insert new event into 'events'-collection */ db.getCollection("events").insert(event); System.out.println(simulate); if (simulate) //computeById( request, null, null, id, refineId, comp, accel, apikey ); _computeById(user, compId.toString(), comp, accel, gridres, algo); else /* run request in a separate thread to avoid blocking */ new Thread() { public void run() { sendPost(GlobalParameter.wsgi_url + "webguisrv/post_compute", "evtid=" + compId.toString()); } }.start(); return jssuccess(new BasicDBObject("refineId", refineId).append("evtid", compId.toString())); }
From source file:GeoHazardServices.Inst.java
License:Apache License
@POST @Path("/signin") @Produces(MediaType.APPLICATION_JSON)/*w w w . j a v a2 s .co m*/ public String signin(@Context HttpServletRequest request, @Context HttpServletResponse response, @FormParam("username") String username, @FormParam("password") String password) { Cookie sessionCookie = new Cookie("server_cookie", "java!"); sessionCookie.setPath("/"); sessionCookie.setHttpOnly(true); //sessionCookie.setSecure( true ); if (username == null || password == null || username.equals("") || password.equals("")) return jsfailure(); DBCollection coll = db.getCollection("users"); DBCursor cursor = coll.find(new BasicDBObject("username", username)); DBObject obj; if (cursor.hasNext()) { obj = cursor.next(); String hash = (String) obj.get("password"); String session = (String) obj.get("session"); MessageDigest sha256; try { sha256 = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { return "{ \"status\": \"error\" }"; } Base64Codec base64Codec = new Base64Codec(); if (hash.equals(base64Codec.encode(sha256.digest(password.getBytes())))) { if (session == null) { session = getSessionKey(); obj.put("session", session); coll.update(new BasicDBObject("username", username), obj); } sessionCookie.setValue(session); response.addCookie(sessionCookie); BasicDBObject result = new BasicDBObject("status", "success"); result.put("user", getUserObj(username)); BasicDBObject perm = (BasicDBObject) obj.get("permissions"); if (perm != null && perm.getBoolean("nologin") == true) return jsdenied(new BasicDBObject("nologin", true)); System.out.println("CLOUD " + new Date() + " SignIn from user " + username); DBObject login = new BasicDBObject("date", new Date()).append("user", username); db.getCollection("logins").insert(login); return gson.toJson(result); } } return jsfailure(); }
From source file:GeoHazardServices.Inst.java
License:Apache License
@POST @Path("/signout") @Produces(MediaType.APPLICATION_JSON)/* w ww .j a v a 2 s . c om*/ public String signout(@Context HttpServletRequest request, @Context HttpServletResponse response, @FormParam("username") String username, @CookieParam("server_cookie") String session) { if (username == null || username.equals("") || session == null) return jsfailure(); DBCollection coll = db.getCollection("users"); DBCursor cursor = coll.find(new BasicDBObject("username", username)); DBObject obj; if (cursor.hasNext()) { obj = cursor.next(); if (session.equals((String) obj.get("session"))) { obj.put("session", null); coll.update(new BasicDBObject("username", username), obj); Cookie sessionCookie = new Cookie("server_cookie", ""); sessionCookie.setPath("/"); sessionCookie.setMaxAge(0); response.addCookie(sessionCookie); System.out.println("CLOUD " + new Date() + " SignOut from user " + username); return jssuccess(); } } return jsfailure(); }
From source file:GeoHazardServices.Inst.java
License:Apache License
@POST @Path("/delete") @Produces(MediaType.APPLICATION_JSON)//from ww w.j a v a 2s. co m public String delete(@Context HttpServletRequest request, @FormParam("id") String id, @FormParam("type") String type, @CookieParam("server_cookie") String session) { Object[] required = { id }; if (!checkParams(request, required)) return jsfailure(); /* check session key and find out if the request comes from an authorized user */ User user = signedIn(session); if (user == null) return jsdenied(); DBCollection coll; BasicDBObject inQuery = new BasicDBObject(); BasicDBObject fields = new BasicDBObject(); if (type != null && type.equals("msg_in")) { coll = db.getCollection("messages_received"); inQuery.put("ReceiverID", user.objId); inQuery.put("Message-ID", id); fields.put("ReceiverID", null); } else if (type != null && type.equals("msg_out")) { coll = db.getCollection("messages_sent"); inQuery.put("SenderID", user.objId); inQuery.put("Message-ID", id); fields.put("SenderID", null); } else { coll = db.getCollection("eqs"); inQuery.put("user", user.objId); inQuery.put("_id", id); fields.put("user", null); } fields.put("olduser", user.objId); //int num = coll.remove( inQuery ).getN(); BasicDBObject set = new BasicDBObject("$set", fields); System.out.println(set); int num = coll.update(inQuery, set).getN(); if (num > 0) return jssuccess(); return jsfailure(); }
From source file:govt_import_export.aircrafts2.java
private void placeorderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_placeorderActionPerformed try {//from w ww . j av a 2 s .c o m MongoClient mongo = new MongoClient("localhost", 27017); DB db0 = mongo.getDB("admindata"); DBCollection collection0 = db0.getCollection("admin"); DBCursor c = collection0.find(); DBObject o; while (c.hasNext()) { o = c.next(); if (o.get("rate") != null) { db_rate = o.get("rate").toString(); } } c = collection0.find(); while (c.hasNext()) { o = c.next(); if (o.get("balance") != null) { db_balance = nf.format(o.get("balance")); } } ratio = ((double) unitsXcost) / Double.parseDouble(db_balance); newbalance = Long.parseLong(db_balance) - unitsXcost; newrate = Double.parseDouble(db_rate) * pow(Math.E, ratio); System.out.println("'newrate'" + newrate); //System.out.println(newbalance); String q = nf.format(newbalance); //System.out.println(q); //--------------------setting the updated values in the db---------------------- BasicDBObject searchupdate = new BasicDBObject(); searchupdate.append("rate", Double.parseDouble(db_rate)); //finds the document(s) where "date":last_activity BasicDBObject update = new BasicDBObject(); update.append("$set", new BasicDBObject("rate", /*Double.toString(newrate)*/newrate)); collection0.update(searchupdate, update); //----- BasicDBObject searchupdate1 = new BasicDBObject(); searchupdate1.append("balance", Long.parseLong(db_balance)); BasicDBObject update1 = new BasicDBObject(); update1.append("$set", new BasicDBObject("balance", Long.parseLong(q))); collection0.update(searchupdate1, update1); //------------------------------------------------------------------------------ DB db = mongo.getDB("AIRCRAFTS"); DBCollection collection = db.getCollection(type); //insert BasicDBObject document = new BasicDBObject(); document.append("model", make_model); document.append("type", type); document.append("cost", zzz); document.append("month", java_month); document.append("year", java_year); document.append("units", Integer.parseInt(units_string)); document.append("totalcost", totalcost.getText()); javax.swing.JOptionPane.showMessageDialog(aircrafts2.this, "Waiting for acceptance"); collection.insert(document); } catch (UnknownHostException | MongoException e) { //e.printStackTrace(); } }
From source file:govt_import_export.export.java
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed // TODO add your handling code here: MongoClient mongo = null;/*w w w.ja v a 2s . c o m*/ try { mongo = new MongoClient("localhost", 27017); //get database } catch (UnknownHostException e) { e.printStackTrace(); } catch (MongoException e) { e.printStackTrace(); } DB db = mongo.getDB("AUTOMOBILEXPO"); //DB db2=mongo.getDB("automobile_expo"); String batches = (String) jComboBox1.getSelectedItem(); int unit, month, year; unit = Integer.parseInt(batches); //get collections DBCollection table = db.getCollection(manufac); //DBCollection table1=db2.getCollection(db1); BasicDBObject document1 = new BasicDBObject(); String st = (String) jComboBox2.getSelectedItem(); String st1 = (String) jComboBox3.getSelectedItem(); String st2 = (String) jComboBox4.getSelectedItem(); month = Integer.parseInt(st1); year = Integer.parseInt(st2); cost = cost * unit; //jTextField1.setText(z); DB db0 = mongo.getDB("admindata"); DBCollection collection0 = db0.getCollection("admin"); DBCursor c = collection0.find(); //yes DBObject o; //DBCursor c=collection0.find(); //yes while (c.hasNext()) { o = c.next(); if (o.get("rate") != null) { db_rate = o.get("rate").toString(); } } c = collection0.find(); while (c.hasNext()) { o = c.next(); if (o.get("balance") != null) { db_balance = nf.format(o.get("balance")); } } ratio = ((double) cost) / Double.parseDouble(db_balance); ratio = -ratio * .1; newbalance = Long.parseLong(db_balance) - cost; newrate = Double.parseDouble(db_rate) * pow(Math.E, ratio); System.out.println("'newrate'" + newrate); //System.out.println(newbalance); String q = nf.format(newbalance); //System.out.println(q); //--------------------setting the updated values in the db---------------------- BasicDBObject searchupdate = new BasicDBObject(); searchupdate.append("rate", Double.parseDouble(db_rate)); //finds the document(s) where "date":last_activity BasicDBObject update = new BasicDBObject(); update.append("$set", new BasicDBObject("rate", /*Double.toString(newrate)*/newrate)); collection0.update(searchupdate, update); //----- BasicDBObject searchupdate1 = new BasicDBObject(); searchupdate1.append("balance", Long.parseLong(db_balance)); BasicDBObject update1 = new BasicDBObject(); update1.append("$set", new BasicDBObject("balance", Long.parseLong(q))); collection0.update(searchupdate1, update1); //DBObject o; BasicDBObject document = new BasicDBObject(); BasicDBObject prev = new BasicDBObject(); document.append("manufacturer", manufac); document.append("model", model_selected); document.append("country", st); document.append("Units", unit); document.append("Cost", cost); document.append("Month", month); document.append("Year", year); table.insert(document); //long x=table.count(); //find and display //System.out.println(x); GroupCommand cmd = new GroupCommand(table, null, new BasicDBObject("model", model_selected), new BasicDBObject("Units", 0), "function(document,prev){prev.Units=prev.Units+this.Units;}", null); o = table.group(cmd); //System.out.println(o); sort_cars(); javax.swing.JOptionPane.showMessageDialog(export.this, "Waiting for acceptance"); st = String.valueOf(total_cost); jTextField1.setText(st); System.out.println("donee"); }
From source file:io.github.apfelcreme.LitePortals.Bungee.Database.MongoController.java
License:Open Source License
/** * deletes a portal and resets the target of all portals it was connected to * * @param portal a portal//from w w w .j ava2 s.c o m */ public void deletePortal(Portal portal) { DBCollection collection = MongoConnector.getInstance().getCollection(); // find all portals who have this portal as target BasicDBObject query = new BasicDBObject("target", portal.getId().toString()); DBCursor dbCursor = collection.find(query); while (dbCursor.hasNext()) { DBObject portalObject = dbCursor.next(); portalObject.removeField("target"); UUID targetId = UUID.fromString((String) portalObject.get("portal_id")); collection.update(query, portalObject); Portal p = PortalManager.getInstance().getPortal(targetId); if (p != null) { p.setTarget(null); } } // remove the object itself BasicDBObject portalObject = new BasicDBObject("portal_id", portal.getId().toString()); collection.remove(portalObject); PortalManager.getInstance().getPortals().remove(portal); }
From source file:io.github.apfelcreme.LitePortals.Bungee.Database.MongoController.java
License:Open Source License
/** * sets the portals target/* w w w.j a v a2 s . c om*/ * * @param portal1 the source portal * @param portal2 the target the portal shall be connected to */ public void link(Portal portal1, Portal portal2) { DBCollection collection = MongoConnector.getInstance().getCollection(); BasicDBObject query = new BasicDBObject("portal_id", portal1.getId().toString()); DBCursor dbCursor = collection.find(query); if (dbCursor.hasNext()) { DBObject portalObject = dbCursor.next(); portalObject.put("target", portal2.getId().toString()); collection.update(query, portalObject); portal1.setTarget(portal2.getId()); } }