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:com.card.loop.xyz.dao.LearningElementDAO.java

public ArrayList<String> getKeywords(String md5, String collection) throws UnknownHostException {
    Mongo mongo = new Mongo(AppConfig.mongodb_host, AppConfig.mongodb_port);
    DB db = mongo.getDB(AppConfig.DATABASE_LOOP);
    ArrayList<String> list = new ArrayList<>();
    GridFS le_gfs = new GridFS(db, collection);
    GridFSDBFile le_output = le_gfs.findOne(new BasicDBObject("md5", md5));
    ListIterator<Object> trustedList = ((BasicDBList) le_output.get("keywords")).listIterator();

    while (trustedList.hasNext()) {
        Object nextItem = trustedList.next();
        list.add(nextItem.toString());/*from www.  ja va 2s .  c o m*/
    }
    return list;
}

From source file:com.cognifide.aet.vs.artifacts.ArtifactsDAOMongoDBImpl.java

License:Apache License

@Override
public Artifact getArtifact(DBKey dbKey, String objectID) {
    Artifact artifact = null;//from   w  w w. j a v a 2s . co m

    GridFS gfs = getGridFS(dbKey);
    if (gfs != null) {
        BasicDBObject query = new BasicDBObject();
        query.put(ID_FIELD_NAME, new ObjectId(objectID));
        GridFSDBFile file = gfs.findOne(query);
        if (file != null) {
            artifact = new Artifact(file.getInputStream(), file.getContentType());
        }
    }
    return artifact;
}

From source file:com.cyslab.craftvm.rest.mongo.GridfsServlet.java

License:GNU General Public License

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

    log.trace("doPost()");

    if (!can_write(req)) {
        res.sendError(SC_UNAUTHORIZED);/*from   ww w  . j av  a  2s  .  c  o  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_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.cyslab.craftvm.rest.mongo.GridfsServlet.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);//from  w w  w  .j  av a  2 s  . c  om
        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];
    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.cyslab.craftvm.rest.mongo.GridfsServlet.java

License:GNU General Public License

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

    log.trace("doGet()");

    if (!can_read(req)) {
        res.sendError(SC_UNAUTHORIZED);//www .  ja v a  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();
        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.englishtown.vertx.GridFSModule.java

License:Open Source License

public void getFile(Message<JsonObject> message, JsonObject jsonObject) {

    ObjectId objectId = getObjectId(message, jsonObject, "id");
    if (objectId == null) {
        return;//  w  w w. ja v a2  s .  co m
    }

    // Optional bucket, default is "fs"
    String bucket = jsonObject.getString("bucket", GridFS.DEFAULT_BUCKET);
    GridFS files = new GridFS(db, bucket);

    GridFSDBFile file = files.findOne(objectId);
    if (file == null) {
        sendError(message, "File does not exist: " + objectId.toString());
        return;
    }

    JsonObject fileInfo = new JsonObject().putString("filename", file.getFilename())
            .putString("contentType", file.getContentType()).putNumber("length", file.getLength())
            .putNumber("chunkSize", file.getChunkSize())
            .putNumber("uploadDate", file.getUploadDate().getTime());

    DBObject metadata = file.getMetaData();
    if (metadata != null) {
        fileInfo.putObject("metadata", new JsonObject(JSON.serialize(metadata)));
    }

    // Send file info
    sendOK(message, fileInfo);

}

From source file:com.fileoperations.CopyClass.java

public Boolean forSingleFile() {
    try {//w w w . j  a  v  a  2 s  .  c om
        if (name.contains(".")) {

            BasicDBObject query = new BasicDBObject();
            query.put("_id", parentPath + pathMerger + name);
            DBCursor cursor = collection.find(query);

            if (cursor.hasNext()) {
                BasicDBObject checknewquery = new BasicDBObject();
                checknewquery.put("_id", newPath + pathMerger + name);
                DBCursor tempCursor = collection.find(checknewquery);
                if (tempCursor.hasNext()) {
                    return false;
                }
                DBObject copyFile = cursor.next();
                GridFS fileDB = new GridFS(mymongo.getDB(), userCollectionName);
                InputStream data = fileDB.findOne(query).getInputStream();

                BasicDBObject document = new BasicDBObject();
                document.append("_id", newPath + pathMerger + name);
                document.append("folder", "0");
                document.append("parent", newPath);
                document.append("name", name);
                document.append("type", copyFile.get("type").toString());
                collection.insert(document);
                GridFSInputFile inputFile = fileDB.createFile(data);
                inputFile.setId(newPath + pathMerger + name);
                inputFile.put("path", newPath);
                inputFile.setFilename(name);
                inputFile.save();
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    } finally {
        mymongo.closeConnection();
    }
}

From source file:com.fileoperations.RenameFolder.java

public Boolean forSingleFile() {
    try {//from  w w w  .  ja va 2s. c o  m
        if (oldName.contains(".")) {

            BasicDBObject query = new BasicDBObject();
            query.put("_id", parentPath + pathMerger + oldName);
            DBCursor cursor = collection.find(query);

            if (cursor.hasNext()) {
                DBObject renameFile = cursor.next();
                BasicDBObject checknewquery = new BasicDBObject();
                checknewquery.put("_id", parentPath + pathMerger + newName + renameFile.get("type").toString());
                DBCursor tempCursor = collection.find(checknewquery);
                if (tempCursor.hasNext()) {
                    return false;
                }

                GridFS file = new GridFS(mymongo.getDB(), userCollectionName);
                InputStream data = file.findOne(query).getInputStream();

                BasicDBObject document = new BasicDBObject();
                document.append("_id", parentPath + pathMerger + newName + renameFile.get("type").toString());
                document.append("folder", "0");
                document.append("parent", parentPath);
                document.append("name", newName + renameFile.get("type").toString());
                document.append("type", renameFile.get("type").toString());
                collection.insert(document);
                GridFSInputFile inputFile = file.createFile(data);
                inputFile.setId(parentPath + pathMerger + newName + renameFile.get("type").toString());
                inputFile.put("path", parentPath);
                inputFile.setFilename(newName + renameFile.get("type").toString());
                inputFile.save();
                file.remove(file.findOne(query));
                collection.remove(renameFile);
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    } finally {
        mymongo.closeConnection();
    }
}

From source file:com.hangum.tadpole.mongodb.core.query.MongoDBQuery.java

License:Open Source License

/**
 * get gridfs data/*from   w  w  w.  ja va  2s.c o m*/
 * 
 * @param userDB
 * @param _id
 * @return 
 * @throws Exception
 */
public static byte[] getGridFS(UserDBDAO userDB, String strBucket, String _id) throws Exception {
    DB mongoDb = findDB(userDB);
    GridFS gridFs = null;

    if ("".equals(strBucket))
        gridFs = new GridFS(mongoDb);
    else
        gridFs = new GridFS(mongoDb, strBucket);

    GridFSDBFile gridFSFile = gridFs.findOne(new ObjectId(_id));
    InputStream is = gridFSFile.getInputStream();
    return IOUtils.toByteArray(is);
}

From source file:com.hangum.tadpole.mongodb.core.query.MongoDBQuery.java

License:Open Source License

/**
 * delte gridfs// w w w  .j a v  a 2 s .c om
 * 
 * @param userDB
 * @param _id
 * @throws Exception
 */
public static void dleteGridFs(UserDBDAO userDB, String strBucket, String _id) throws Exception {
    DB mongoDb = findDB(userDB);
    GridFS gridFs = null;

    if ("".equals(strBucket))
        gridFs = new GridFS(mongoDb);
    else
        gridFs = new GridFS(mongoDb, strBucket);

    gridFs.remove(gridFs.findOne(new ObjectId(_id)));

}