Example usage for com.mongodb.gridfs GridFS findOne

List of usage examples for com.mongodb.gridfs GridFS findOne

Introduction

In this page you can find the example usage for com.mongodb.gridfs GridFS findOne.

Prototype

public GridFSDBFile findOne(final DBObject query) 

Source Link

Document

Finds one file matching the given query.

Usage

From source file:fr.wseduc.resizer.GridFsFileAccess.java

License:Apache License

@Override
public void read(String src, Handler<ImageFile> handler) {
    String[] path = parsePath(src);
    if (path == null || path.length != 2) {
        handler.handle(null);/* w w  w  .j  a  va  2 s . c  o m*/
        return;
    }
    GridFS fs = new GridFS(db, path[0]);
    GridFSDBFile f = fs.findOne(pathToDbObject(path[1]));
    if (f != null) {
        handler.handle(new ImageFile(f.getInputStream(), f.getFilename(), f.getContentType()));
    } else {
        handler.handle(null);
    }
}

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);/*from w  w  w . j ava  2 s.  com*/

    // 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());
            });
            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

/**
 * /*w w w  .ja  va 2  s  . c  om*/
 * @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:me.yyam.mongodbutils.MongoDbOperater.java

/**
 * GridFS// w  w  w. j av  a 2 s .  c o  m
 * @param dbName ???
 * @param fsName GridFS???fsnull?
 * @param fsFileName GridFS??
 * @param fileName ???fsFileName??fsFileName??
 * @return ???
 * @throws FileNotFoundException
 * @throws IOException 
 */
public File downloadFsFile(String dbName, String fsName, String fsFileName, String fileName)
        throws FileNotFoundException, IOException {
    if (StringUtils.isBlank(fileName)) {
        fileName = fsFileName;
    }
    File saveFile = new File(fileName);
    if (saveFile.isDirectory()) {
        fileName = saveFile.getPath() + "/" + fsFileName;
    }
    DB db = mongoClient.getDB(dbName);
    if (fsName == null) {
        fsName = "fs";
    }
    GridFS fs = new GridFS(db, fsName);
    GridFSDBFile gfile = fs.findOne(fsFileName);
    if (gfile == null) {
        throw new FileNotFoundException("gridfs" + fsFileName);
    }
    InputStream input = gfile.getInputStream();
    try {
        File f = new File(fileName);
        if (!f.exists()) {
            f.createNewFile();
        }
        OutputStream output = new FileOutputStream(f);
        byte[] bytes = new byte[1024];
        int read = 0;
        while ((read = input.read(bytes)) != -1) {
            output.write(bytes, 0, read);
        }
        output.flush();
        output.close();
        return f;
    } finally {
        input.close();
    }

}

From source file:me.yyam.mongodbutils.MongoDbOperater.java

public byte[] getFsFileBytes(String dbName, String fsName, String fsFileName)
        throws FileNotFoundException, IOException {
    DB db = mongoClient.getDB(dbName);/*from w  w  w  . j a v  a 2  s  . c o m*/
    if (fsName == null) {
        fsName = "fs";
    }
    GridFS fs = new GridFS(db, fsName);
    GridFSDBFile gfile = fs.findOne(fsFileName);
    if (gfile == null) {
        throw new FileNotFoundException("gridfs" + fsFileName);
    }
    InputStream input = gfile.getInputStream();
    try {
        byte[] b = new byte[(int) gfile.getLength()];
        int readCount = 0;
        while (true) {
            int count = input.read(b, readCount, 255);
            if (count <= 0) {
                break;
            }
            readCount += count;
        }
        return b;
    } finally {
        input.close();
    }

}

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.//  w  w  w. j  ava  2s  . c  o  m
 *
 * @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.
 *///from   ww  w .  j  a  v  a2  s. com
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:mytubermiserver.mongo.GridFileSystem.java

public InputStream receiveVideo(String fileName) throws UnknownHostException, MongoException, IOException {
    Mongo mongo = new Mongo(hostAddress, portAddress);
    DB db = mongo.getDB("MyTube");

    // create a "video" namespace
    GridFS gfsPhoto = new GridFS(db, "video");

    // get image file by it's filename
    GridFSDBFile videoForOutput = gfsPhoto.findOne(fileName);
    return videoForOutput.getInputStream();

}

From source file:net.kamradtfamily.mongorest.GridfsServlet.java

License:GNU General Public License

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    log.fine("doPost()");

    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];/*w ww  .  j ava  2  s.  co  m*/
            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;
    while ((n = is.read(data, 0, len)) > 0) {
        os.write(data, 0, n);
    }
    os.close();

    is.close();

    out_json(req, Status.OK);

}

From source file:net.kamradtfamily.mongorest.GridfsServlet.java

License:GNU General Public License

@Override
protected void doPut(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    log.fine("doPut()");

    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];/*from   w  w w . j a  v a2s. c om*/
            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];
    int n;
    while ((n = is.read(data, 0, len)) > 0) {
        os.write(data, 0, n);
    }
    os.flush();
    os.close();

    is.close();

    out_json(req, Status.OK);

}