List of usage examples for com.mongodb.gridfs GridFSDBFile writeTo
public long writeTo(final OutputStream out) throws IOException
From source file:io.liveoak.mongo.gridfs.GridFSBlobResource.java
License:Open Source License
@Override public void readContent(RequestContext ctx, BinaryContentSink sink) throws Exception { GridFS gridfs = getUserspace().getGridFS(); // TODO - maybe use netty directly here? // TODO - BinaryContentSink should flush to socket (pipeline channel), not queue to memory // get tmp file File tmpFile = getTempFile(); // sync copy from db to tmp file first - no async API GridFSDBFile file = gridfs.findOne(new BasicDBObject("_id", fileInfo().getId())); file.writeTo(tmpFile); // async copy from local tmp file to sink getRoot().vertx().fileSystem().open(tmpFile.getPath(), (result) -> { if (result.succeeded()) { AsyncFile asyncFile = result.result(); asyncFile.dataHandler((buffer) -> { sink.accept(buffer.getByteBuf()); });/*from w w w .ja v a 2 s.c o m*/ asyncFile.endHandler((end) -> { sink.close(); asyncFile.close(); tmpFile.delete(); }); } else { sink.close(); tmpFile.delete(); } }); }
From source file:it.marcoberri.mbfasturl.action.QrCode.java
License:Apache License
/** * /* ww w . ja v a 2s . c o m*/ * @param request * @param response * @throws ServletException * @throws IOException */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final String fast = request.getPathInfo().replace("/", ""); Url u = null; try { u = ds.find(Url.class, "fast", fast).get(); } catch (final Exception e) { Commons.log.fatal("Url " + request.getPathInfo() + " not found", e); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } final LogQrcode logQrcode = getHeader(request); logQrcode.setUrlId(u.getId()); logQrcode.setUrl(u.getUrl()); logQrcode.setFast(fast); ds.save(logQrcode); final ObjectId qrcode_id = u.getQrcodeMedium(); final GridFS fs = MongoConnectionHelper.getGridFS(); GridFSDBFile file = fs.findOne(qrcode_id); if (file == null) { try { u = Commons.generateQrcodes(u); ds.save(u); } catch (final WriterException ex) { Commons.log.error(ex.getMessage(), ex); } } file = fs.findOne(qrcode_id); if (file == null) { Commons.log.fatal("Qrcode " + request.getPathInfo() + " not found second find"); return; } file.writeTo(response.getOutputStream()); response.setContentType(file.getContentType()); response.setContentLength((int) file.getLength()); response.getOutputStream().flush(); response.getOutputStream().close(); }
From source file:ktrack.repository.DogNamesRepositoryImpl.java
License:Apache License
@Override public byte[] getImage(String imageFileId) { try {// w w w .j a va 2s.c o m GridFSDBFile imageFile = getGridFSDBFile(imageFileId); if (imageFile != null) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); imageFile.writeTo(baos); return baos.toByteArray(); } } catch (IOException exception) { // TODO: Log error! } return null; }
From source file:mx.org.cedn.avisosconagua.engine.FileDelivery.java
License:Open Source License
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from www . j av a 2 s . com*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String[] uriParts = request.getRequestURI().split("/"); GridFS gridfs = MongoInterface.getInstance().getGridFS(uriParts[1]); GridFSDBFile fileForOutput = gridfs.findOne(uriParts[2]); response.setContentType(fileForOutput.getContentType()); response.setContentLength((int) fileForOutput.getLength()); try (OutputStream os = response.getOutputStream()) { fileForOutput.writeTo(os); os.flush(); } }
From source file:mx.org.cedn.avisosconagua.mongo.HtmlZipGenerator.java
License:Open Source License
/** * Generates the ZIP file of the HTMl advice. *//*w w w . j a v a 2s.c o m*/ public void generate() { try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { String localFolder = "./" + adviceID + "/"; ZipOutputStream zout = new ZipOutputStream(baos); zout.setLevel(9); zout.putNextEntry(new ZipEntry(name)); zout.write(html.generate(true).getBytes("ISO8859-1")); //zout.putNextEntry(new ZipEntry(localFolder)); if (html.getPrincipalFile() != null) { GridFS gridfs = MongoInterface.getInstance().getImagesFS(); GridFSDBFile imageForOutput = gridfs.findOne(html.getPrincipalFile()); zout.putNextEntry(new ZipEntry(prefix + "_1" + html.getPrincipalFile().substring(html.getPrincipalFile().lastIndexOf(".")))); //localFolder + imageForOutput.writeTo(zout); } if (html.getPronosticoFile() != null) { GridFS gridfs = MongoInterface.getInstance().getImagesFS(); GridFSDBFile imageForOutput = gridfs.findOne(html.getPronosticoFile()); zout.putNextEntry(new ZipEntry(prefix + "_2" + html.getPrincipalFile().substring(html.getPrincipalFile().lastIndexOf(".")))); //localFolder + imageForOutput.writeTo(zout); } zout.putNextEntry(new ZipEntry(prefix + "_f.gif")); InputStream fin = HtmlZipGenerator.class.getResourceAsStream("/fondo.gif"); byte[] buff = new byte[8192]; int lenght; while ((lenght = fin.read(buff)) > -1) { zout.write(buff, 0, lenght); } // ArrayList<String> lista = MongoInterface.getInstance().listFilesFromAdvice(adviceID); // for (String filename : lista) { // GridFS gridfs = MongoInterface.getInstance().getImagesFS(); // GridFSDBFile imageForOutput = gridfs.findOne(filename); // String fnpart[] = filename.split(":"); // zout.putNextEntry(new ZipEntry(localFolder + fnpart[1])); // imageForOutput.writeTo(zout); // } zout.close(); GridFS fs = MongoInterface.getInstance().getGeneratedFS(); fs.remove(nameZip); GridFSInputFile infile = fs.createFile(baos.toByteArray()); infile.setContentType("application/zip"); infile.setFilename(nameZip); infile.save(); isOK = true; } catch (IOException ioe) { ioe.printStackTrace(); } }
From source file:net.kamradtfamily.mongorest.GridfsServlet.java
License:GNU General Public License
@Override protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { log.fine("doGet()"); 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];/*from www. jav a 2 s. com*/ 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(); 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:net.tbnr.gearz.arena.Arena.java
License:Open Source License
public final void loadWorld() throws GearzException, ZipException, IOException { GridFSDBFile one = Arena.bucket.findOne(new ObjectId(this.worldId)); if (one == null) throw new GearzException("Failed to load world - not found"); String worldName = RandomUtils.getRandomString(16); File zipHandle = new File(Gearz.getInstance().getDataFolder(), RandomUtils.getRandomString(16) + ".gWorld"); one.writeTo(zipHandle); File world = new File(Bukkit.getWorldContainer(), worldName); if (!world.mkdir()) throw new GearzException("Could not create world directory!"); ZipFile zippedWorld = new ZipFile(zipHandle); zippedWorld.extractAll(world.getPath()); this.world = WorldCreator.name(worldName).createWorld(); this.world.setTime(0); this.world.setStorm(false); this.world.setAutoSave(false); for (LivingEntity e : this.world.getLivingEntities()) { if (e instanceof Player) { continue; }/* w w w .j a v a 2s . co m*/ e.remove(); } for (Item e : this.world.getEntitiesByClass(Item.class)) { e.remove(); } this.world.setGameRuleValue("doDaylightCycle", "false"); this.world.setGameRuleValue("doMobLoot", "true"); this.world.setGameRuleValue("commandBlockOutput", "true"); this.world.setGameRuleValue("doMobSpawning", "true"); this.world.setGameRuleValue("keepInventory", "false"); }
From source file:net.tooan.ynpay.third.mongodb.fs.UploadedFileServlet.java
License:Apache License
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String url = request.getRequestURI(); int second = url.indexOf(SLASH, 1); url = url.substring(second);//from w w w. j av a 2 s . c om int last = url.lastIndexOf(SLASH); String filename = url.substring(last + 1); DBObject query = new BasicDBObject(BuguFS.FILENAME, filename); query.put(ImageUploader.DIMENSION, null); String bucketName = BuguFS.DEFAULT_BUCKET; int first = url.indexOf(SLASH); if (first != last) { String sub = url.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 = new BuguFS(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; String[] rangeArray = range.split("-"); if (rangeArray.length == 1) { 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:org.aw20.mongoworkbench.command.GridFSGetFileCommand.java
License:Open Source License
@Override public void execute() throws Exception { MongoClient mdb = MongoFactory.getInst().getMongo(sName); if (mdb == null) throw new Exception("no server selected"); if (sDb == null) throw new Exception("no database selected"); MongoFactory.getInst().setActiveDB(sDb); DB db = mdb.getDB(sDb);/*from www .java 2 s. co m*/ GridFS gfs = new GridFS(db, sColl.substring(0, sColl.lastIndexOf("."))); GridFSDBFile gridFSDBFile = gfs.find(id); gridFSDBFile.writeTo(saveFile); setMessage("fileSaved=" + saveFile + "; size=" + saveFile.length()); }
From source file:org.bananaforscale.cormac.dao.gridfs.GridFsDataServiceImpl.java
License:Apache License
/** * Returns the file with the given file name. * * @param databaseName the database/* ww w . j a va2 s. com*/ * @param bucketName the bucket * @param fileName the file name * @return the file in with the given file name * @throws DatasourceException * @throws IOException * @throws NotFoundException */ @Override public FileEnvelope getByFileName(String databaseName, String bucketName, String fileName) throws DatasourceException, IOException, NotFoundException { try { if (!databaseExists(databaseName)) { throw new NotFoundException("The database doesn't exist in the datasource"); } DB mongoDatabase = mongoClient.getDB(databaseName); GridFS gfsBucket = new GridFS(mongoDatabase, bucketName); GridFSDBFile gfsFile = gfsBucket.findOne(fileName); if (gfsFile == null) { throw new NotFoundException("The file doesnt exist"); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); gfsFile.writeTo(baos); return new FileEnvelope(baos.toByteArray(), gfsFile.getContentType(), fileName); } catch (MongoException ex) { logger.error("An error occured while retrieving the file", ex); throw new DatasourceException("An error occured while retrieving the file"); } }