List of usage examples for com.mongodb DBCollection insert
public WriteResult insert(final List<? extends DBObject> documents)
From source file:framework.module.users.client.model.BLL.BLL_dummies.Make_dummies_client.java
public static void makedummies_client() { DBCollection table = Mongo_BD.getCollection(); for (int i = 0; i < 5; i++) { Client c1 = new Client(DNI(), user(), pass(), avatar(), state(), name(), surname(), email(), mobilephone(), datebirthday(), shopping(), dtos(), premium(), typeclient()); Singleton_client.userclient.add(c1); table.insert(c1.Client_to_BD()); }/* w ww .ja v a 2 s . com*/ }
From source file:framework.modules.users.client.Model.DAO.DAO_client_MG.java
/** * Insert a client in the DB/*from w w w. ja v a 2 s . c o m*/ * @param table * @param w */ public static void insert_client(client_class client) { DBCollection table = singleton.collection; table.insert(client.client_to_DB()); }
From source file:generate.MapGenerateAction.java
@Override public String execute() { String file_path = "/home/chanakya/NetBeansProjects/Concepto/UploadedFiles"; try {//w ww .j ava 2 s. c om File fileToCreate = new File(file_path, concept_map.getUploadedFileFileName()); FileUtils.copyFile(concept_map.getUploadedFile(), fileToCreate); } catch (Throwable t) { System.out.println("E1: " + t.getMessage()); return ERROR; } try { List<String> temp_text = FileUtils.readLines(concept_map.getUploadedFile()); StringBuilder text = new StringBuilder(); for (String s : temp_text) { text.append(s); } concept_map.setInput_text(text.toString()); } catch (IOException e) { //e.printStackTrace(); System.out.println("E2: " + e.getMessage()); return ERROR; } String temp_filename = concept_map.getUploadedFileFileName().split("\\.(?=[^\\.]+$)")[0]; temp_filename = temp_filename.trim(); try { String temp = "java -jar /home/chanakya/NetBeansProjects/Concepto/src/java/generate/MajorCore.jar " + file_path + " " + temp_filename; System.out.println(temp); File jarfile = new File("/home/chanakya/NetBeansProjects/Concepto/src/java/generate/MajorCore.jar"); JarFile jar = new JarFile(jarfile); Manifest manifest = jar.getManifest(); Attributes attrs = manifest.getMainAttributes(); String mainClassName = attrs.getValue(Attributes.Name.MAIN_CLASS); System.out.println(mainClassName); URL url = new URL("file", null, jarfile.getAbsolutePath()); ClassLoader cl = new URLClassLoader(new URL[] { url }); Class mainClass = cl.loadClass(mainClassName); Method mainMethod = mainClass.getMethod("main", new Class[] { String[].class }); String[] args = new String[2]; args[0] = file_path; args[1] = temp_filename; System.out.println(args[0]); System.out.println(args[1]); try { mainMethod.invoke(mainClass, new Object[] { args }); } catch (InvocationTargetException e) { System.out.println("This is the exception: " + e.getTargetException().toString()); } } catch (IllegalArgumentException | IllegalAccessException | NoSuchMethodException | ClassNotFoundException | IOException e) { System.out.println("E3: " + e.getMessage()); return ERROR; } try { String temp2 = "java -jar /home/chanakya/NetBeansProjects/Concepto/src/java/generate/MajorCoreII.jar " + file_path + " " + temp_filename; System.out.println(temp2); File jarfile = new File("/home/chanakya/NetBeansProjects/Concepto/src/java/generate/MajorCoreII.jar"); JarFile jar = new JarFile(jarfile); Manifest manifest = jar.getManifest(); Attributes attrs = manifest.getMainAttributes(); String mainClassName = attrs.getValue(Attributes.Name.MAIN_CLASS); System.out.println(mainClassName); URL url = new URL("file", null, jarfile.getAbsolutePath()); ClassLoader cl = new URLClassLoader(new URL[] { url }); Class mainClass = cl.loadClass(mainClassName); Method mainMethod = mainClass.getMethod("main", new Class[] { String[].class }); String[] args = new String[2]; args[0] = file_path; args[1] = temp_filename; mainMethod.invoke(mainClass, new Object[] { args }); } catch (InvocationTargetException | IllegalArgumentException | IllegalAccessException | NoSuchMethodException | ClassNotFoundException | IOException e) { System.out.println("E4: " + e.getMessage()); return ERROR; } String cmd = "python /home/chanakya/NetBeansProjects/Concepto/src/java/generate/add_to_graph.py \"/home/chanakya/NetBeansProjects/Concepto/UploadedFiles/" + temp_filename + "_OllieOutput.txt\""; String[] finalCommand; finalCommand = new String[3]; finalCommand[0] = "/bin/sh"; finalCommand[1] = "-c"; finalCommand[2] = cmd; System.out.println("CMD: " + cmd); try { //ProcessBuilder builder = new ProcessBuilder(finalCommand); //builder.redirectErrorStream(true); //Process process = builder.start(); Process process = Runtime.getRuntime().exec(finalCommand); int exitVal = process.waitFor(); System.out.println("Process exitValue2: " + exitVal); } catch (Throwable t) { System.out.println("E5: " + t.getMessage()); return ERROR; } cmd = "python /home/chanakya/NetBeansProjects/Concepto/src/java/generate/json_correct.py"; finalCommand = new String[3]; finalCommand[0] = "/bin/sh"; finalCommand[1] = "-c"; finalCommand[2] = cmd; try { //Process process = Runtime.getRuntime().exec(finalCommand); ProcessBuilder builder = new ProcessBuilder(finalCommand); // builder.redirectErrorStream(true); Process process = builder.start(); int exitVal = process.waitFor(); System.out.println("Process exitValue3: " + exitVal); } catch (Throwable t) { System.out.println("E6: " + t.getMessage()); return ERROR; } try { List<String> temp_text_1 = FileUtils .readLines(FileUtils.getFile("/home/chanakya/NetBeansProjects/Concepto/web", "new_graph.json")); StringBuilder text_1 = new StringBuilder(); for (String s : temp_text_1) { text_1.append(s); } concept_map.setOutput_text(text_1.toString()); } catch (IOException e) { System.out.println("E7: " + e.getMessage()); return ERROR; } Random rand = new Random(); int unique_id = rand.nextInt(99999999); System.out.println("Going In DB"); try { MongoClient mongo = new MongoClient(); DB db = mongo.getDB("Major"); DBCollection collection = db.getCollection("ConceptMap"); BasicDBObject document = new BasicDBObject(); document.append("InputText", concept_map.getInput_text()); document.append("OutputText", concept_map.getOutput_text()); document.append("ChapterName", concept_map.getChapter_name()); document.append("ChapterNumber", concept_map.getChapter_number()); document.append("SectionName", concept_map.getSection_name()); document.append("SectionNumber", concept_map.getSection_number()); document.append("UniqueID", Integer.toString(unique_id)); collection.insert(document); //collection.save(document); } catch (MongoException e) { System.out.println("E8: " + e.getMessage()); return ERROR; } catch (UnknownHostException ex) { Logger.getLogger(MapGenerateAction.class.getName()).log(Level.SEVERE, null, ex); System.out.println("E9"); return ERROR; } System.out.println("Out DB"); return SUCCESS; }
From source file:GeoHazardServices.Inst.java
License:Apache License
@POST @Path("/data_insert") @Produces(MediaType.APPLICATION_JSON)/*from w w w .j av a2s.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
private String static_int(String id, Double lon, Double lat, Double zoom, Object uid) { DBCollection coll = db.getCollection("shared_links"); BasicDBObject inQuery = new BasicDBObject("evtid", id); inQuery.put("lon", lon); inQuery.put("lat", lat); inQuery.put("zoom", zoom); inQuery.put("timestamp", new Date()); inQuery.put("userid", uid); coll.insert(inQuery); ObjectId objId = (ObjectId) inQuery.get("_id"); return objId.toString(); }
From source file:github.macrohuang.orm.mongo.core.MongoDBTemplate.java
License:Apache License
/** * Save an entry to the DB, with manual specify {@link DBChooser}. * /* w ww . j a v a2 s. co m*/ * @see #insert(Object) * @see #findByExample(DBChooser, Object) * @param <T> * @param dbChooser * @param entry * @return The result of save action.<code>true</code> for success, while * <code>false</code> for fail. * @throws MongoDataAccessException */ public <T> String insert(DBChooser dbChooser, T entry) throws MongoDataAccessException { Assert.assertNotNull(entry); Assert.assertNotNull(dbChooser); if (Constants.coreLogEnable) LOGGER.info("Save request received:" + dbChooser + "," + entry); DBCollection collection = getCollection(dbChooser); DBObject object = DBObjectUtil.convertPO2DBObject(entry); if (isOperateSuccess(collection.insert(object))) { DBObjectUtil.setEntryId(object, entry); return object.get(Constants.MONGO_ID).toString(); } else { return null; } }
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 a v a2s . 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;//from ww w . j a v a 2 s . 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:gr.teicm.toulou.SignupResource.java
@POST @Consumes("text/plain") public String postUser(String user) { System.out.println(user);/* ww w . j a va2s. com*/ Gson gson = new Gson(); DBObject dbObjectUser = (DBObject) JSON.parse(user); System.out.println("parsed leei"); MongoClient mongoClient = new MongoClient("localhost", 27017); System.out.println("connected leei"); DB db = mongoClient.getDB("snapchatydb"); System.out.println("fetched db leei"); DBCollection coll = (DBCollection) db.getCollection("user"); System.out.println("fetched collection leei"); coll.insert(dbObjectUser); System.out.println("inserted leei"); return ""; }
From source file:guesslocation.MongoQuery.java
public static void main(String[] args) { {//from w w w. jav a 2 s . c o m try { // Connect to mongodb MongoClient mongo = new MongoClient("localhost", 27017); // get database // if database doesn't exists, mongodb will create it for you DB db = mongo.getDB("test"); // get collection // if collection doesn't exists, mongodb will create it for you DBCollection collection = db.getCollection("twitter"); DBCollection Outcollection = db.getCollection("user_tw"); DBCursor cursor; BasicDBObject query; //------------------------------------ // ( 1 ) collection.find() --> get all document cursor = collection.find(); System.out.println("( 1 ) .find()"); System.out.println("results --> " + cursor.count()); try { BasicDBObject IDquery = new BasicDBObject(); //2015-05-12T15:15:31Z while (cursor.hasNext()) { DBObject data = cursor.next(); Long v_user_Id = (Long) data.get("user_Id"); if (v_user_Id == null) { continue; } IDquery.append("user_Id", v_user_Id); DBCursor IDcursor = Outcollection.find(IDquery); if (IDcursor.hasNext() == false) { BasicDBObject basicObj = GetUserRecord(v_user_Id, data); try { Outcollection.insert(basicObj); } catch (Exception e) { System.err.println("error on insert " + v_user_Id); } basicObj = null; Thread.sleep(100); Outcollection.ensureIndex(new BasicDBObject("user_Id", 1), new BasicDBObject("unique", true)); } IDcursor.close(); IDquery.clear(); } } catch (InterruptedException ex) { Logger.getLogger(MongoQuery.class.getName()).log(Level.SEVERE, null, ex); } finally { cursor.close(); } System.out.println("---------------------------------"); System.exit(0); } catch (UnknownHostException ex) { Logger.getLogger(MongoQuery.class.getName()).log(Level.SEVERE, null, ex); } } }