List of usage examples for com.mongodb DBCollection insert
public WriteResult insert(final List<? extends DBObject> documents, final InsertOptions insertOptions)
Insert documents into a collection.
From source file:UnitTest3.java
License:Open Source License
public static int testgridfs() { long time1;/* ww w . jav a 2 s .c om*/ long time2; long time3; long time4; try { MongoClient mongo = new MongoClient("localhost", 27017); DB db = mongo.getDB("JFileDB"); // TODO JFileMetaDataTable should be in MetaDB database DBCollection collection = db.getCollection("JFileMetaDataTable"); String newFileName = "com.dilmus.scabi.testdata.in.App.class"; File jFile = new File("/home/anees/workspace/testdata/in/App.class"); // create a JFileTable namespace GridFS gfsj = new GridFS(db, "JFileTable"); // get file from local drive GridFSInputFile gfsFile = gfsj.createFile(jFile); // set a new filename for identify purpose gfsFile.setFilename(newFileName); gfsFile.setContentType("class"); // jar, zip, war // save the image file into mongoDB gfsFile.save(); // Let's create a new JSON document with some "metadata" information BasicDBObject info = new BasicDBObject(); info.put("DBHost", "localhost"); info.put("DBPort", "27017"); info.put("JFileName", newFileName); info.put("JFileID", gfsFile.getId()); info.put("JFileMD5", gfsFile.getMD5()); collection.insert(info, WriteConcern.ACKNOWLEDGED); // print the result DBCursor cursor = gfsj.getFileList(); while (cursor.hasNext()) { System.out.println(cursor.next()); } DBCursor cursor2 = collection.find(); while (cursor2.hasNext()) { System.out.println(cursor2.next()); } // get file by it's filename GridFSDBFile jForOutput = gfsj.findOne(newFileName); // save it into a new image file jForOutput.writeTo("/home/anees/workspace/testdata/out/AppOut.class"); // remove the file from mongoDB // gfsj.remove(gfsj.findOne(newFileName)); System.out.println("Done"); mongo.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (MongoException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return 0; }
From source file:calliope.core.database.MongoConnection.java
License:Open Source License
/** * PUT a new json file to the database/* w ww. j a v a 2s . co m*/ * @param collName the name of the collection * @param json the json to put there * @return the server response */ @Override public String addToDb(String collName, String json) throws DbException { try { DBObject doc = (DBObject) JSON.parse(json); connect(); DBCollection coll = getCollectionFromName(collName); if (doc.containsField(JSONKeys._ID)) { Object id = doc.get(JSONKeys._ID); DBObject query = new BasicDBObject(JSONKeys._ID, id); if (query != null) { WriteResult result = coll.update(query, doc, true, false); return result.toString(); } else throw new Exception("Failed to update object " + id); } else { WriteResult result = coll.insert(doc, WriteConcern.ACKNOWLEDGED); // return the new document's id ObjectId id = (ObjectId) doc.get("_id"); JSONObject jDoc = (JSONObject) JSONValue.parse(result.toString()); jDoc.put("_id", id.toString()); return jDoc.toJSONString(); } } catch (Exception e) { throw new DbException(e); } }
From source file:com.andreig.jetty.WriteServlet.java
License:GNU General Public License
@Override protected void doPut(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { log.fine("doPut()"); if (!can_write(req)) { res.sendError(SC_UNAUTHORIZED);//from www. j av a 2s . c o m return; } 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; } } 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; ArrayList<DBObject> ar = new ArrayList<DBObject>(); try { r = new BufferedReader(new InputStreamReader(is)); String data; while ((data = r.readLine()) != null) { if (data != null) { DBObject o; try { o = (DBObject) JSON.parse(data); ar.add(o); } catch (JSONParseException e) { error(res, SC_BAD_REQUEST, Status.get("can not parse data")); return; } } } } finally { if (r != null) r.close(); } if (ar.size() == 0) { error(res, SC_BAD_REQUEST, Status.get("can not parse data")); return; } WriteResult wr = col.insert(ar, write_concern); // search if (do_search) { String fn = col.getFullName(); List<String> flds = Config.search_index_fields.get(fn); if (flds != null && flds.size() > 0) { Search _writer = search.get_writer(); try { for (DBObject o : ar) { boolean commit = false; Document doc = new Document(); for (String fld : flds) { String val = (String) o.get(fld); if (val == null) continue; Search.add_searchable_s(doc, fld, val); commit = true; } if (commit) { ObjectId id = (ObjectId) o.get("_id"); String sid = id.toStringMongod(); Search.add_storable(doc, "_id", sid); Search.add_searchable_s(doc, "_dbid_", fn); _writer.commit(doc); } } } catch (ClassCastException e) { error(res, SC_BAD_REQUEST, Status.get("searchable fields must be type String")); return; } catch (CorruptIndexException e) { error(res, SC_BAD_REQUEST, Status.get("Search corrupt index" + e)); return; } } } // return operation status if (do_return) { out_str(req, wr.toString()); if (wr.getError() == null) { res.setStatus(SC_BAD_REQUEST); return; } } res.setStatus(SC_CREATED); }
From source file:com.cyslab.craftvm.rest.mongo.WriteServlet.java
License:GNU General Public License
@Override protected void doPut(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { log.trace("doPut()"); if (!can_write(req)) { res.sendError(SC_UNAUTHORIZED);//w w w . j av a 2s . c o m return; } 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; } } 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; ArrayList<DBObject> ar = new ArrayList<DBObject>(); try { r = new BufferedReader(new InputStreamReader(is)); String data; while ((data = r.readLine()) != null) { if (data != null) { DBObject o; try { o = (DBObject) JSON.parse(data); ar.add(o); } catch (JSONParseException e) { error(res, SC_BAD_REQUEST, Status.get("can not parse data")); return; } } } } finally { if (r != null) r.close(); } if (ar.size() == 0) { error(res, SC_BAD_REQUEST, Status.get("can not parse data")); return; } WriteResult wr = col.insert(ar, write_concern); // search if (do_search) { String fn = col.getFullName(); List<String> flds = Config.search_index_fields.get(fn); if (flds != null && flds.size() > 0) { Search _writer = search.get_writer(); try { for (DBObject o : ar) { boolean commit = false; Document doc = new Document(); for (String fld : flds) { String val = (String) o.get(fld); if (val == null) continue; _writer.add_searchable_s(doc, fld, val); commit = true; } if (commit) { ObjectId id = (ObjectId) o.get("_id"); String sid = id.toStringMongod(); _writer.add_storable(doc, "_id", sid); _writer.add_searchable_s(doc, "_dbid_", fn); _writer.commit(doc); } } } catch (ClassCastException e) { error(res, SC_BAD_REQUEST, Status.get("searchable fields must be type String")); return; } catch (CorruptIndexException e) { error(res, SC_BAD_REQUEST, Status.get("Search corrupt index" + e)); return; } } } // return operation status if (do_return) { out_str(req, wr.toString()); if (wr.getError() == null) { res.setStatus(SC_BAD_REQUEST); return; } } res.setStatus(SC_CREATED); }
From source file:com.health.smart.util.MongoC.java
public static void insert(String collection, String document) throws Exception { DBCollection coll = getClient().getDB(database).getCollection(collection); coll.insert((DBObject) JSON.parse(document), WriteConcern.ACKNOWLEDGED); }
From source file:com.health.smart.util.MongoC.java
public static void insert(String collection, DBObject document) throws Exception { DBCollection coll = getClient().getDB(database).getCollection(collection); coll.insert(document, WriteConcern.ACKNOWLEDGED); }
From source file:com.ibm.sae.LoadDreamHomeDB.java
/***************************************************************/ private static void loadCounters(DB db) { System.out.println("LoadDreamHomeDB:loadCounters begins"); DBCollection coll = db.getCollection("dhCounterColl"); System.out.println("LoadDreamHomeDB:loadCounters collection"); coll.drop();/* w w w .j a va2s. c om*/ System.out.println("LoadDreamHomeDB:loadCounters after drop"); DBObject countersDoc = new BasicDBObject("_id", "notificationId").append("seq", 5000); WriteResult wr = coll.insert(countersDoc, WriteConcern.ACKNOWLEDGED); countersDoc = new BasicDBObject("_id", "clientId").append("seq", 4000); wr = coll.insert(countersDoc, WriteConcern.ACKNOWLEDGED); countersDoc = new BasicDBObject("_id", "propertyId").append("seq", 2000); wr = coll.insert(countersDoc, WriteConcern.ACKNOWLEDGED); countersDoc = new BasicDBObject("_id", "agentId").append("seq", 1000); wr = coll.insert(countersDoc, WriteConcern.ACKNOWLEDGED); countersDoc = new BasicDBObject("_id", "officeId").append("seq", 3000); wr = coll.insert(countersDoc, WriteConcern.ACKNOWLEDGED); System.out.println("LoadDreamHomeDB:loadNotificationCounters ends"); }
From source file:com.ibm.sae.LoadDreamHomeDB.java
/***************************************************************/ private static void loadClient(DB db, DBCollection coll) { System.out.println("LoadDreamHomeDB:loadClient begins"); coll.drop();//from www .j a v a 2 s . c o m List<DBObject> comments = new ArrayList<DBObject>(); List<DBObject> suggestedProperties = new ArrayList<DBObject>(); DBObject commentDoc = new BasicDBObject("comment", "This is a beautiful home"); comments.add(commentDoc); DBObject propertyDoc = new BasicDBObject("propertyId", 1999).append("propertyState", 0) .append("askingPrice", 689900.45).append("rating", 0).append("comments", comments); suggestedProperties.add(propertyDoc); DBObject clientDoc = new BasicDBObject("clientId", 3999) .append("clientName", new BasicDBObject("clientFN", "Richard").append("clientLN", "Hendrix")) .append("clientInfo", new BasicDBObject("address", "101 Valley Street").append("city", "Glendale") .append("state", "California").append("zip", "67854")) .append("agentId", 1001).append("suggestedProperties", suggestedProperties) .append("minAskingPrice", 500000.00).append("maxAskingPrice", 700000.00); WriteResult wr = coll.insert(clientDoc, WriteConcern.ACKNOWLEDGED); System.out.println("LoadDreamHomeDB:loadClient ends"); }
From source file:com.ibm.sae.LoadDreamHomeDB.java
/***************************************************************/ private static void loadAgent(DB db, DBCollection coll) { System.out.println("LoadDreamHomeDB:loadAgent begins"); coll.drop();// w w w .ja va2s .com List<DBObject> properties = new ArrayList<DBObject>(); DBObject propertyDoc = new BasicDBObject("propertyId", 2000).append("clientId", 4000) .append("propertyState", 0); properties.add(propertyDoc); DBObject agentDoc = new BasicDBObject("agentId", 999) .append("agentData", new BasicDBObject("agentFN", "Dinesh").append("agentLN", "Chugtai") .append("agentLicense", "CAL-34917")) .append("officeId", 3000).append("properties", properties); WriteResult wr = coll.insert(agentDoc, WriteConcern.ACKNOWLEDGED); System.out.println("LoadDreamHomeDB:loadAgent ends"); }
From source file:com.ibm.sae.LoadDreamHomeDB.java
/***************************************************************/ private static void loadNotification(DB db, DBCollection coll) { System.out.println("LoadDreamHomeDB:loadNotification begins"); coll.drop();/*from ww w. ja v a2 s. c o m*/ DBObject notificationDoc = new BasicDBObject("notificationId", 4999).append("agentId", 1000) .append("clientId", 4000); WriteResult wr = coll.insert(notificationDoc, WriteConcern.ACKNOWLEDGED); System.out.println("LoadDreamHomeDB:loadNotification ends"); }