List of usage examples for com.mongodb.gridfs GridFSDBFile writeTo
public long writeTo(final OutputStream out) throws IOException
From source file:UnitTest3.java
License:Open Source License
public static int testgridfs() { long time1;//from w w w. ja v a 2 s .co 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:MediaUI.java
License:Open Source License
private void SaveWidgetSelected(SelectionEvent evt) { System.out.println("Save.widgetSelected, event=" + evt); //TODO add your code for Save.widgetSelected if (mediaDisplayController.haveMediaDisplayed == false) return;// w w w .j av a 2 s . c o m FileDialog saveFile = new FileDialog(getShell(), SWT.SAVE); saveFile.open(); String filepath = saveFile.getFilterPath(); String fileName = saveFile.getFileName(); // System.out.println(filepath+"\\"+fileName); filepath = filepath + "\\" + fileName + "." + profileData.getMetadataCopy().type; GridFSDBFile gridFSDBFile = galleryTable.getGridFSDBFile(); try { File outputfile = new File(filepath); gridFSDBFile.writeTo(outputfile); } catch (Exception e) { e.printStackTrace(); } }
From source file:cn.vlabs.clb.server.ui.frameservice.document.handler.GetDocContentHandler.java
License:Apache License
private void writeFileContentToResponse(GridFSDBFile dbfile, HttpServletRequest request, HttpServletResponse response) {/*from www . jav a2s .c o m*/ OutputStream os = null; try { long start = System.currentTimeMillis(); response.setCharacterEncoding("utf-8"); response.setContentLength((int) dbfile.getLength()); response.setContentType("application/x-download"); String filename = dbfile.getFilename(); if (filename == null) { filename = "file" + dbfile.getId(); } LOG.debug(dbfile.getFilename() + "," + dbfile.getLength()); String headerValue = ResponseHeaderUtils.buildResponseHeader(request, filename, true); response.setHeader("Content-Disposition", headerValue); response.setHeader("Content-Length", dbfile.getLength() + ""); os = response.getOutputStream(); dbfile.writeTo(os); long end = System.currentTimeMillis(); LOG.info("Read doc content using stream mode for doc [" + filename + "], use time " + (end - start) + "ms"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(os); } }
From source file:cn.vlabs.clb.server.ui.frameservice.image.handler.GetImageContentHandler.java
License:Apache License
private void writeFileContentToResponse(GridFSDBFile dbfile, HttpServletRequest request, HttpServletResponse response) {/*from w w w.j a v a 2 s .c o m*/ OutputStream os = null; try { long start = System.currentTimeMillis(); response.setCharacterEncoding("utf-8"); response.setContentLength((int) dbfile.getLength()); response.setContentType("application/x-download"); String filename = dbfile.getFilename(); if (filename == null) { filename = "file" + dbfile.getId(); } String headerValue = ResponseHeaderUtils.buildResponseHeader(request, filename, true); response.setHeader("Content-Disposition", headerValue); response.setHeader("Content-Length", dbfile.getLength() + ""); os = response.getOutputStream(); dbfile.writeTo(os); long end = System.currentTimeMillis(); LOG.info("Read image content using stream mode for image [" + dbfile.getId() + "], use time " + (end - start) + "ms"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(os); } }
From source file:cn.vlabs.clb.server.ui.frameservice.pdf.handler.GetPdfContentHandler.java
License:Apache License
private void writePdfContentToResponse(GridFSDBFile dbfile, HttpServletRequest request, HttpServletResponse response) {/* w w w. ja va2s. c o m*/ OutputStream os = null; try { response.setContentLength((int) dbfile.getLength()); response.setContentType("application/x-download"); String filename = dbfile.getFilename(); String headerValue = ResponseHeaderUtils.buildResponseHeader(request, filename, true); response.setHeader("Content-Disposition", headerValue); response.setHeader("Content-Length", dbfile.getLength() + ""); os = response.getOutputStream(); dbfile.writeTo(os); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (os != null) { IOUtils.closeQuietly(os); } } }
From source file:cn.vlabs.clb.server.ui.frameservice.trivial.TrivialFacade.java
License:Apache License
public File writeZipFileToTempFile(GridFSDBFile gfile) { checkAndCreateTempDir();//w ww . j ava 2s.com File tmpZipFile = new File( zipOutputDir + File.separator + "temp_" + System.currentTimeMillis() + "_" + gfile.getFilename()); try { gfile.writeTo(tmpZipFile); } catch (IOException e) { e.printStackTrace(); } return tmpZipFile; }
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 w ww .j ava 2s .c o m 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.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 w w . j a v a 2 s. c om 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.bugull.mongo.fs.UploadedFileServlet.java
License:Apache License
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (!StringUtil.isEmpty(password)) { String p = request.getParameter("password"); if (StringUtil.isEmpty(p) || !p.equals(password)) { return; }//from w w w . j av a2 s. c om } String uri = request.getRequestURI(); int second = uri.indexOf(SLASH, 1); uri = uri.substring(second); int last = uri.lastIndexOf(SLASH); String filename = uri.substring(last + 1); DBObject query = new BasicDBObject(BuguFS.FILENAME, filename); query.put(ImageUploader.DIMENSION, null); //note: this is necessary! String bucketName = GridFS.DEFAULT_BUCKET; int first = uri.indexOf(SLASH); if (first != last) { String sub = uri.substring(first + 1, last); String[] arr = sub.split(SLASH); for (int i = 0; i < arr.length; i += 2) { if (arr[i].equals(BuguFS.BUCKET)) { bucketName = arr[i + 1]; } else { query.put(arr[i], arr[i + 1]); } } } //check if the bucket is allowed to access by this servlet if (!StringUtil.isEmpty(allowBucket) && !allowBucket.equalsIgnoreCase(bucketName)) { return; } if (!StringUtil.isEmpty(forbidBucket) && forbidBucket.equalsIgnoreCase(bucketName)) { return; } BuguFS fs = BuguFSFactory.getInstance().create(bucketName); GridFSDBFile f = fs.findOne(query); if (f == null) { return; } OutputStream os = response.getOutputStream(); int fileLength = (int) f.getLength(); String ext = StringUtil.getExtention(filename); response.setContentType(getContentType(ext)); String range = request.getHeader("Range"); //normal http request, no "range" in header. if (StringUtil.isEmpty(range)) { response.setStatus(HttpServletResponse.SC_OK); response.setContentLength(fileLength); if (needCache(ext)) { String modifiedSince = request.getHeader("If-Modified-Since"); DateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.ENGLISH); df.setTimeZone(TimeZone.getTimeZone("GMT")); Date uploadDate = f.getUploadDate(); String lastModified = df.format(uploadDate); if (modifiedSince != null) { Date modifiedDate = null; Date sinceDate = null; try { modifiedDate = df.parse(lastModified); sinceDate = df.parse(modifiedSince); } catch (ParseException ex) { logger.error("Can not parse the Date", ex); } if (modifiedDate.compareTo(sinceDate) <= 0) { response.setStatus(304); //Not Modified return; } } long maxAge = 365L * 24L * 60L * 60L; //one year, in seconds response.setHeader("Cache-Control", "max-age=" + maxAge); response.setHeader("Last-Modified", lastModified); response.setDateHeader("Expires", uploadDate.getTime() + maxAge * 1000L); } else { response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); } f.writeTo(os); } //has "range" in header else { range = range.substring("bytes=".length()); if (StringUtil.isEmpty(range)) { return; } int begin = 0; int end = fileLength - 1; boolean onlyLast = range.startsWith("-"); String[] rangeArray = range.split("-"); if (rangeArray.length == 1) { if (onlyLast) { begin = fileLength - Integer.parseInt(rangeArray[0]); } else { begin = Integer.parseInt(rangeArray[0]); } } else if (rangeArray.length == 2) { begin = Integer.parseInt(rangeArray[0]); end = Integer.parseInt(rangeArray[1]); } response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); int contentLength = end - begin + 1; response.setContentLength(contentLength); response.setHeader("Content-Range", "bytes " + begin + "-" + end + "/" + contentLength); InputStream is = f.getInputStream(); is.skip(begin); int read = -1; int bufferSize = (int) f.getChunkSize(); byte[] buffer = new byte[bufferSize]; int remain = contentLength; int readSize = Math.min(bufferSize, remain); while ((read = is.read(buffer, 0, readSize)) != -1) { os.write(buffer, 0, read); remain -= read; if (remain <= 0) { break; } readSize = Math.min(bufferSize, remain); } StreamUtil.safeClose(is); } StreamUtil.safeClose(os); }
From source file:com.crec.demo.GeneralController.java
/** * PDF??/*from w w w . j a v a2s . c om*/ * @author niyn * @param file_name ??4855.pdf??4855 */ @RequestMapping("/download") public void download(@RequestParam String file_name, HttpServletResponse res) throws Exception { OutputStream os = res.getOutputStream(); try { res.reset(); res.setHeader("Content-Disposition", "attachment;filename=" + new String((file_name + ".pdf").getBytes(), "iso-8859-1")); res.setContentType("application/octet-stream"); MongoDirver md = new MongoDirver(); GridFSDBFile gfFile = md.downloadPDF(file_name, null); if (gfFile != null) { gfFile.writeTo(os); } else { res.getWriter().println(""); } os.flush(); } finally { if (os != null) { os.close(); } } }