Example usage for com.mongodb.gridfs GridFS getFileList

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

Introduction

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

Prototype

public DBCursor getFileList() 

Source Link

Document

Gets the list of files stored in this gridfs, sorted by filename.

Usage

From source file:UnitTest3.java

License:Open Source License

public static int testgridfs() {

    long time1;/*from www.ja v a2s .  com*/
    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

/**
 * List all the documents in a Mongo collection
 * @param collName the name of the collection
 * @return a String array of document keys
 * @throws AeseException //from www .j  a  v  a 2  s. co m
 */
@Override
public String[] listCollection(String collName) throws AeseException {
    if (!collName.equals(Database.CORPIX)) {
        try {
            connect();
        } catch (Exception e) {
            throw new AeseException(e);
        }
        DBCollection coll = getCollectionFromName(collName);
        BasicDBObject keys = new BasicDBObject();
        keys.put(JSONKeys.DOCID, 1);
        DBCursor cursor = coll.find(new BasicDBObject(), keys);
        System.out.println("Found " + cursor.count() + " documents");
        cursor.count();
        if (cursor.length() > 0) {
            String[] docs = new String[cursor.length()];
            Iterator<DBObject> iter = cursor.iterator();
            int i = 0;
            while (iter.hasNext())
                docs[i++] = (String) iter.next().get(JSONKeys.DOCID);
            return docs;
        } else {
            return new String[0];
        }
    } else {
        GridFS gfs = new GridFS(db, collName);
        DBCursor curs = gfs.getFileList();
        int i = 0;
        List<DBObject> list = curs.toArray();
        HashSet<String> set = new HashSet<String>();
        Iterator<DBObject> iter = list.iterator();
        while (iter.hasNext()) {
            String name = (String) iter.next().get("filename");
            set.add(name);
        }
        String[] docs = new String[set.size()];
        set.toArray(docs);
        return docs;
    }
}

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);// w  w w  .  j av a 2 s. co  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.card.loop.xyz.dao.LearningElementDAO.java

public ArrayList<DBObject> listAll(String collection) throws UnknownHostException {
    ArrayList<DBObject> list = new ArrayList<DBObject>();
    Mongo mongo = new Mongo(AppConfig.mongodb_host, AppConfig.mongodb_port);
    DB db = mongo.getDB(AppConfig.DATABASE_LOOP);
    GridFS le_gfs = new GridFS(db, collection);
    DBCursor cursor = le_gfs.getFileList();
    System.out.println(le_gfs.getFileList() + "");
    while (cursor.hasNext()) {
        list.add(cursor.next());//from w w  w  .java  2s.c o  m
    }
    return list;
}

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);/*  w w w . j  a  va  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();
        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.hangum.tadpole.mongodb.core.query.MongoDBQuery.java

License:Open Source License

/**
 * gridFS/* w ww . j a  v  a2  s .  co  m*/
 * 
 * @param userDB
 * @param strBucket
 * @param strFileName
 * @param intSkip
 * @param intLimit
 * @return
 * @throws Exception
 */
public static DBCursor getGridFS(UserDBDAO userDB, String strBucket, String strFileName, int intSkip,
        int intLimit) throws Exception {
    DB mongoDb = findDB(userDB);
    GridFS gridFs = null;

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

    if ("".equals(strFileName)) {
        return gridFs.getFileList().skip(intSkip).limit(intLimit);
    } else {
        DBObject queryObj = new BasicDBObject();
        Pattern regex = Pattern.compile(".*" + strFileName + "*");
        queryObj.put("filename", regex);

        return gridFs.getFileList(queryObj).skip(intSkip).limit(intLimit);
    }
}

From source file:com.hangum.tadpole.mongodb.core.test.MongoTestGridFS.java

License:Open Source License

private static void allList(DB db) throws Exception {
    System.out.println("##[all GridFs list] [start]######################");

    GridFS gridFs = new GridFS(db);
    DBCursor dbCursor = gridFs.getFileList();
    for (DBObject dbObject : dbCursor) {
        System.out.println(dbObject);
    }/* www.  j  ava2 s.  c om*/

    System.out.println("##[all GridFs list] [end]######################");
}

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];//  w  w  w. j  a  v a2 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";

    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:org.bananaforscale.cormac.dao.gridfs.GridFsDataServiceImpl.java

License:Apache License

/**
 * Returns all the files in a bucket./*www  .  ja va 2 s.co m*/
 *
 * @param databaseName the database
 * @param bucketName the bucket
 * @return the files in the bucket
 * @throws DatasourceException
 * @throws NotFoundException
 */
@Override
public List<String> getAll(String databaseName, String bucketName)
        throws DatasourceException, NotFoundException {
    try {
        if (!databaseExists(databaseName)) {
            throw new NotFoundException("The database doesn't exist in the datasource");
        }
        if (!bucketExists(databaseName, bucketName)) {
            throw new NotFoundException("The bucket doesn't exist in the database");
        }
        DB mongoDatabase = mongoClient.getDB(databaseName);
        GridFS gfsBucket = new GridFS(mongoDatabase, bucketName);
        DBCursor cursor = gfsBucket.getFileList();
        Iterator<DBObject> curIter = cursor.iterator();
        List<String> fileList = new ArrayList<>();
        while (curIter.hasNext()) {
            DBObject current = curIter.next();
            fileList.add(JSON.serialize(current));
        }
        return fileList;
    } catch (MongoException ex) {
        logger.error("An error occured while retrieving file list", ex);
        throw new DatasourceException("An error occured while retrieving file list");
    }

}

From source file:org.bananaforscale.cormac.dao.gridfs.GridFsDataServiceImpl.java

License:Apache License

/**
 * Removes all files in a bucket./*from www  .ja  v  a 2 s .c o m*/
 *
 * @param databaseName the database
 * @param bucketName the bucket
 * @return a status message with the outcome of the operation
 * @throws DatasourceException
 * @throws NotFoundException
 */
@Override
public boolean removeAll(String databaseName, String bucketName) throws DatasourceException, 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); // TODO: determine behavior if bucket doesnt exist
        DBCursor cursor = gfsBucket.getFileList();
        Iterator<DBObject> curIter = cursor.iterator();
        while (curIter.hasNext()) {
            DBObject current = curIter.next();
            gfsBucket.remove(current);
        }
        return true;
    } catch (MongoException ex) {
        logger.error("An error occured while removing files", ex);
        throw new DatasourceException("An error occured while removing files");
    }
}