List of usage examples for com.mongodb.gridfs GridFS findOne
public GridFSDBFile findOne(final DBObject query)
From source file:UnitTest3.java
License:Open Source License
public static int testgridfs() { long time1;//from ww w . ja va 2s . c o m 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.db.MongoConnection.java
License:Open Source License
/** * Get an image from the database//ww w. ja v a 2 s . com * @param collName the collection name * @param docID the docid of the corpix * @return the image data */ @Override public byte[] getImageFromDb(String collName, String docID) { try { connect(); GridFS gfs = new GridFS(db, collName); GridFSDBFile file = gfs.findOne(docID); if (file != null) { InputStream ins = file.getInputStream(); long dataLen = file.getLength(); // this only happens if it is > 2 GB if (dataLen > Integer.MAX_VALUE) throw new AeseException("file too big (size=" + dataLen + ")"); byte[] data = new byte[(int) dataLen]; int offset = 0; while (offset < dataLen) { int len = ins.available(); offset += ins.read(data, offset, len); } return data; } else throw new FileNotFoundException(docID); } catch (Exception e) { e.printStackTrace(System.out); return null; } }
From source file:calliope.db.MongoConnection.java
License:Open Source License
/** * Delete an image from the database/*from ww w .ja v a 2s. c om*/ * @param collName the collection name e.g. "corpix" * @param docID the image's docid path * @throws AeseException */ @Override public void removeImageFromDb(String collName, String docID) throws AeseException { try { GridFS gfs = new GridFS(db, collName); GridFSDBFile file = gfs.findOne(docID); if (file == null) throw new FileNotFoundException("file " + collName + "/" + docID + " not found"); gfs.remove(file); } catch (Exception e) { throw new AeseException(e); } }
From source file:calliope.db.MongoConnection.java
License:Open Source License
/** * Test a Mongo connection by putting, deleting, getting a JSON * file and an image./* w w w . java 2 s. co m*/ * @return a String indicating how many tests succeeded */ @Override public String test() { StringBuilder sb = new StringBuilder(); try { byte[] imageData = Base64.decodeBase64(testImage); connect(); String response = putToDb("test", "data/text", testJson); if (checkResponse(response)) { response = getFromDb("test", "data/text"); if (!checkResponse(response)) sb.append("failed put/get test for plain json\n"); else { response = removeFromDb("test", "data/text"); if (!checkResponse(response)) sb.append("failed to remove plain json\n"); } } putImageToDb("corpix", "data/image", imageData); byte[] data = getImageFromDb("corpix", "data/image"); if (data == null || data.length != imageData.length) sb.append("failed put/get test for image\n"); else removeImageFromDb("corpix", "data/image"); DBObject query = new BasicDBObject(JSONKeys.DOCID, "data/image"); GridFS gfs = new GridFS(db, "corpix"); GridFSDBFile file = gfs.findOne(query); if (file != null) sb.append("removed failed for image\n"); } catch (Exception e) { e.printStackTrace(System.out); } return sb.toString(); }
From source file:com.andreig.jetty.GridfsServlet.java
License:GNU General Public License
@SuppressWarnings("unused") @Override//from w w w .j ava 2s . co m protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { log.fine("doPost()"); if (!can_write(req)) { res.sendError(SC_UNAUTHORIZED); return; } InputStream tmp = req.getInputStream(); InputStream is = new BufferedInputStream(tmp); String db_name = req.getParameter("dbname"); String bucket_name = req.getParameter("bucketname"); if (db_name == null || bucket_name == null) { String names[] = req2mongonames(req); if (names != null) { db_name = names[0]; bucket_name = names[1]; } if (db_name == null) { error(res, SC_BAD_REQUEST, Status.get("param name missing")); return; } } if (bucket_name == null) bucket_name = "fs"; String file_name = req.getParameter("filename"); if (file_name == null) { error(res, SC_BAD_REQUEST, Status.get("param name missing")); return; } DB db = mongo.getDB(db_name); String fs_cache_key = db_name + bucket_name; GridFS fs = fs_cache.get(fs_cache_key); if (fs == null) { fs = new GridFS(db, bucket_name); fs_cache.put(fs_cache_key, fs); } GridFSDBFile db_file_old = fs.findOne(file_name); if (db_file_old == null) { error(res, SC_NOT_FOUND, Status.get("file doe not exists, use PUT")); return; } String ct = req.getContentType(); GridFSInputFile db_file = fs.createFile(file_name); if (ct != null) db_file.setContentType(ct); OutputStream os = db_file.getOutputStream(); final int len = 4096; byte data[] = new byte[len]; int n = 0, bytesno = 0; while ((n = is.read(data, 0, len)) > 0) { os.write(data, 0, n); bytesno += n; } os.close(); if (is != null) is.close(); out_json(req, Status.OK); }
From source file:com.andreig.jetty.GridfsServlet.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);// w w w . j a v a 2 s. co m return; } InputStream tmp = req.getInputStream(); InputStream is = new BufferedInputStream(tmp); String db_name = req.getParameter("dbname"); String bucket_name = req.getParameter("bucketname"); if (db_name == null || bucket_name == null) { String names[] = req2mongonames(req); if (names != null) { db_name = names[0]; bucket_name = names[1]; } if (db_name == null) { error(res, SC_BAD_REQUEST, Status.get("param name missing")); return; } } if (bucket_name == null) bucket_name = "fs"; String file_name = req.getParameter("filename"); if (file_name == null) { error(res, SC_BAD_REQUEST, Status.get("param name missing")); return; } DB db = mongo.getDB(db_name); String fs_cache_key = db_name + bucket_name; GridFS fs = fs_cache.get(fs_cache_key); if (fs == null) { fs = new GridFS(db, bucket_name); fs_cache.put(fs_cache_key, fs); } GridFSDBFile db_file_old = fs.findOne(file_name); if (db_file_old != null) { error(res, SC_BAD_REQUEST, Status.get("file already exists, use POST")); return; } String ct = req.getContentType(); GridFSInputFile db_file = fs.createFile(file_name); if (ct != null) db_file.setContentType(ct); OutputStream os = db_file.getOutputStream(); final int len = 4096; byte data[] = new byte[len]; @SuppressWarnings("unused") int n = 0, bytesno = 0; while ((n = is.read(data, 0, len)) > 0) { os.write(data, 0, n); bytesno += n; } os.flush(); os.close(); if (is != null) is.close(); out_json(req, Status.OK); }
From source file:com.andreig.jetty.GridfsServlet.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);//from ww w. j a va 2 s . c om return; } String db_name = req.getParameter("dbname"); String bucket_name = req.getParameter("bucketname"); if (db_name == null || bucket_name == null) { String names[] = req2mongonames(req); if (names != null) { db_name = names[0]; bucket_name = names[1]; } if (db_name == null) { error(res, SC_BAD_REQUEST, Status.get("param name missing")); return; } } if (bucket_name == null) bucket_name = "fs"; DB db = mongo.getDB(db_name); String fs_cache_key = db_name + bucket_name; GridFS fs = fs_cache.get(fs_cache_key); if (fs == null) { fs = new GridFS(db, bucket_name); fs_cache.put(fs_cache_key, fs); } // 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; } } String op = req.getParameter("op"); if (op == null) op = "get"; StringBuilder buf = tl.get(); // reset buf buf.setLength(0); // list if ("get".equals(op)) { String file_name = req.getParameter("filename"); if (file_name == null) { error(res, SC_BAD_REQUEST, Status.get("param name missing")); return; } GridFSDBFile db_file = fs.findOne(file_name); if (db_file == null) { error(res, SC_NOT_FOUND, Status.get("file does not exists")); return; } res.setContentLength((int) db_file.getLength()); String ct = db_file.getContentType(); if (ct != null) res.setContentType(ct); OutputStream os = res.getOutputStream(); @SuppressWarnings("unused") long l; while ((l = db_file.writeTo(os)) > 0) ; os.flush(); os.close(); } // list else if ("list".equals(op)) { DBCursor c = fs.getFileList(); if (c == null) { error(res, SC_NOT_FOUND, Status.get("no documents found")); return; } int no = 0; buf.append("["); while (c.hasNext()) { DBObject o = c.next(); JSON.serialize(o, buf); buf.append(","); no++; } if (no > 0) buf.setCharAt(buf.length() - 1, ']'); else buf.append(']'); out_str(req, buf.toString(), "application/json"); } // info else if ("info".equals(op)) { String file_name = req.getParameter("filename"); if (file_name == null) { error(res, SC_BAD_REQUEST, Status.get("param name missing")); return; } GridFSDBFile db_file = fs.findOne(file_name); if (db_file == null) { error(res, SC_NOT_FOUND, Status.get("no documents found")); return; } buf.append("{"); buf.append(String.format("\"ContentType\":%s,", db_file.getContentType())); buf.append(String.format("\"Length\":%d,", db_file.getLength())); buf.append(String.format("\"MD5\":%s", db_file.getMD5())); buf.append("}"); out_str(req, buf.toString(), "application/json"); } else res.sendError(SC_BAD_REQUEST); }
From source file:com.bluedragon.mongo.gridfs.FindOne.java
License:Open Source License
public cfData execute(cfSession _session, cfArgStructData argStruct) throws cfmRunTimeException { // Get the necessary Mongo references DB db = getDB(_session, argStruct);// w w w. j a v a 2 s. c o m GridFS gridfs = getGridFS(_session, argStruct, db); // Get the file information String filename = getNamedStringParam(argStruct, "filename", null); if (filename != null) { return toStruct(gridfs.findOne(filename)); } else { String _id = getNamedStringParam(argStruct, "_id", null); if (_id != null) { return toStruct(gridfs.findOne(new ObjectId(_id))); } else { cfData mTmp = getNamedParam(argStruct, "query", null); if (mTmp != null) return toStruct(gridfs.findOne(getDBObject(mTmp))); } } throwException(_session, "Please specify file, _id or a query"); return null; }
From source file:com.bluedragon.mongo.gridfs.Get.java
License:Open Source License
public cfData execute(cfSession _session, cfArgStructData argStruct) throws cfmRunTimeException { // Get the necessary Mongo references DB db = getDB(_session, argStruct);/*from w ww.j a va 2 s. c o m*/ GridFS gridfs = getGridFS(_session, argStruct, db); String filepath = getNamedStringParam(argStruct, "filepath", null); // Get the file information String filename = getNamedStringParam(argStruct, "filename", null); GridFSDBFile file = null; if (filename != null) { file = gridfs.findOne(filename); } else { String _id = getNamedStringParam(argStruct, "_id", null); if (_id != null) { file = gridfs.findOne(new ObjectId(_id)); } else { cfData mTmp = getNamedParam(argStruct, "query", null); if (mTmp != null) file = gridfs.findOne(getDBObject(mTmp)); } } if (file == null) return cfBooleanData.FALSE; /* * if the return object is either a file or a variable */ if (filepath != null) { boolean overwrite = getNamedBooleanParam(argStruct, "overwrite", true); File jFile = new File(filepath); if (jFile.exists() && !overwrite) throwException(_session, "File:" + filepath + " already exists"); else jFile.delete(); BufferedOutputStream bos = null; try { bos = new BufferedOutputStream(new FileOutputStream(jFile)); file.writeTo(bos); bos.flush(); } catch (IOException e) { throwException(_session, "File:" + filepath + " caused: " + e.getMessage()); } finally { try { if (bos != null) bos.close(); } catch (IOException e) { } } } else { try { ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.getLength()); file.writeTo(bos); bos.flush(); String mimetype = file.getContentType(); if (mimetype != null && mimetype.indexOf("text") > -1) return new cfStringData(bos.toByteArray()); else return new cfBinaryData(bos.toByteArray()); } catch (IOException e) { throwException(_session, e.getMessage()); } } return cfBooleanData.TRUE; }
From source file:com.card.loop.xyz.dao.LearningElementDAO.java
public GridFSDBFile getSingleLE(String id, String collection) throws UnknownHostException { Mongo mongo = new Mongo(AppConfig.mongodb_host, AppConfig.mongodb_port); DB db = mongo.getDB(AppConfig.DATABASE_LOOP); GridFS le_gfs = new GridFS(db, collection); // GridFSDBFile le_output = le_gfs.findOne(new ObjectId(id)); GridFSDBFile le_output = le_gfs.findOne(new ObjectId(id)); System.out.println(le_output); return le_output; }