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.hangum.tadpole.mongodb.core.test.MongoTestGridFS.java

License:Open Source License

private static void getImage(DB db) throws Exception {
    String newFileName = "mkyong-java-image";
    GridFS gfsPhoto = new GridFS(db, "photo");
    GridFSDBFile imageForOutput = gfsPhoto.findOne(newFileName);
    System.out.println(imageForOutput);

}

From source file:com.imaginea.mongodb.services.GridFSServiceImpl.java

License:Apache License

/**
 * Service implementation for retrieving the specified file stored in GridFS.
 *
 * @param dbName     Name of Database/* w ww  . j ava 2s  .c  om*/
 * @param bucketName Name of GridFS Bucket
 * @param id         ObjectId of the file to be retrieved
 * @returns Requested multipartfile for viewing or download based on 'download' param.
 */
public File getFile(String dbName, String bucketName, String id)
        throws ValidationException, DatabaseException, CollectionException {
    mongoInstance = mongoInstanceProvider.getMongoInstance();

    if (dbName == null) {
        throw new EmptyDatabaseNameException("Database Name Is Null");
    }
    if (dbName.equals("")) {
        throw new EmptyDatabaseNameException("Database Name Empty");
    }
    File tempFile = null;
    try {
        if (!mongoInstance.getDatabaseNames().contains(dbName)) {
            throw new UndefinedDatabaseException(

                    "Database with dbName [ " + dbName + "] does not exist");
        }

        GridFS gridFS = new GridFS(mongoInstance.getDB(dbName), bucketName);
        GridFSDBFile gridFSDBFile = gridFS.findOne(new ObjectId(id));
        String tempDir = System.getProperty("java.io.tmpdir");
        tempFile = new File(tempDir + "/" + gridFSDBFile.getFilename());
        gridFSDBFile.writeTo(tempFile);

    } catch (MongoException m) {
        CollectionException e = new CollectionException(ErrorCodes.GET_COLLECTION_LIST_EXCEPTION,
                "GET_FILE_EXCEPTION", m.getCause());
        throw e;
    } catch (IOException e) {
        CollectionException ce = new CollectionException(ErrorCodes.GET_COLLECTION_LIST_EXCEPTION,
                "GET_FILE_EXCEPTION", e.getCause());
        throw ce;
    }
    return tempFile;
}

From source file:com.imaginea.mongodb.services.GridFSServiceImpl.java

License:Apache License

/**
 * Service implementation for dropping a file from GridFS.
 *
 * @param dbName     Name of Database/*w w  w.  j av a2 s .  co m*/
 * @param bucketName Name of GridFS Bucket
 * @param id         Object id of file to be deleted
 * @returns Status message.
 */
public String deleteFile(String dbName, String bucketName, ObjectId id)
        throws DatabaseException, DocumentException, ValidationException {
    mongoInstance = mongoInstanceProvider.getMongoInstance();
    if (dbName == null) {
        throw new EmptyDatabaseNameException("Database name is null");

    }
    if (dbName.equals("")) {
        throw new EmptyDatabaseNameException("Database Name Empty");
    }

    if (bucketName == null) {
        throw new EmptyCollectionNameException("Bucket name is null");
    }
    if (bucketName.equals("")) {
        throw new EmptyCollectionNameException("Bucket Name Empty");
    }

    String result = null;
    GridFSDBFile gridFSDBFile = null;
    try {
        if (!mongoInstance.getDatabaseNames().contains(dbName)) {
            throw new UndefinedDatabaseException("DB [" + dbName + "] DOES NOT EXIST");
        }
        if (id == null) {
            throw new EmptyDocumentDataException("File is empty");
        }

        GridFS gridFS = new GridFS(mongoInstance.getDB(dbName), bucketName);

        gridFSDBFile = gridFS.findOne(id);

        if (gridFSDBFile == null) {
            throw new UndefinedDocumentException("DOCUMENT_DOES_NOT_EXIST");
        }

        gridFS.remove(id);

    } catch (MongoException e) {
        throw new DeleteDocumentException("FILE_DELETION_EXCEPTION");
    }
    result = "Deleted File : [" + gridFSDBFile.getFilename() + "]";
    return result;
}

From source file:com.spring.tutorial.controllers.DefaultController.java

@RequestMapping(value = "/files/{id}", method = RequestMethod.GET)
public String getFile(@PathVariable("id") String id, ModelMap map, HttpServletRequest request,
        HttpServletResponse response) throws IOException, Exception {

    String _id = request.getSession().getAttribute("id").toString();
    MongoData data = new MongoData();
    GridFS collection = new GridFS(data.getDB(), _id + "_files");

    BasicDBObject query = new BasicDBObject();
    query.put("_id", new ObjectId(id));
    GridFSDBFile file = collection.findOne(query);

    DBCollection metaFileCollection = data.getDB().getCollection(_id + "_files_meta");
    BasicDBObject metaQuery = new BasicDBObject();
    metaQuery.put("file-id", new ObjectId(id));
    DBObject metaFileDoc = metaFileCollection.findOne(metaQuery);
    MongoFile metaFile = new MongoFile(metaFileDoc);

    ServletOutputStream out = response.getOutputStream();
    String mimeType = metaFile.getType();
    response.setContentType(mimeType);//  w w w  .  j a v  a 2  s  .  c om
    response.setContentLength((int) file.getLength());
    String headerKey = "Content-Disposition";

    File f = File.createTempFile(file.getFilename(),
            metaFile.getType().substring(metaFile.getType().indexOf("/") + 1));
    String headerValue = String.format("attachment; filename=\"%s\"", file.getFilename());
    response.setHeader(headerKey, headerValue);
    file.writeTo(f);

    FileInputStream inputStream = new FileInputStream(f);
    byte[] buffer = new byte[4096];
    int bytesRead = -1;

    while (inputStream.read(buffer, 0, 4096) != -1) {
        out.write(buffer, 0, 4096);
    }
    inputStream.close();
    out.flush();
    out.close();

    return "mydrive/temp";
}

From source file:com.test.mavenproject1.Main.java

public static void main(String[] args) throws Exception {
    //Load our image
    byte[] imageBytes = LoadImage("/home/fabrice/Pictures/priv/DSCN3338.JPG");
    //Connect to database
    Mongo mongo = new Mongo("127.0.0.1");
    String dbName = "GridFSTestJava";
    DB db = mongo.getDB(dbName);// w  ww . ja  v a2  s. c o m
    //Create GridFS object
    GridFS fs = new GridFS(db);
    //Save image into database
    GridFSInputFile in = fs.createFile(imageBytes);
    in.save();

    //Find saved image
    GridFSDBFile out = fs.findOne(new BasicDBObject("_id", in.getId()));

    //Save loaded image from database into new image file
    FileOutputStream outputImage = new FileOutputStream("/home/fabrice/Pictures/DSCN3338Copy.JPG");
    out.writeTo(outputImage);
    outputImage.close();
}

From source file:eu.eubrazilcc.lvl.storage.mongodb.MongoDBConnector.java

License:EUPL

/**
 * Gets the version of the <tt>filename</tt> labeled with the {@link #FILE_VERSION_PROP} property.
 * @param gridfs - GridFS client/*from ww w.j  a  v a 2 s  .c om*/
 * @param filename - filename to be searched for in the database
 * @return
 */
private GridFSDBFile getLatestVersion(final GridFS gridfs, final String filename) {
    return gridfs.findOne(new BasicDBObject(FILE_VERSION_PROP, filename.trim()));
}

From source file:eu.eubrazilcc.lvl.storage.mongodb.MongoDBConnector.java

License:EUPL

public GridFSDBFileWrapper readOpenAccessFile(final String secret) {
    checkArgument(isNotBlank(secret), "Uninitialized or invalid secret");
    final String secret2 = secret.trim();
    final DB db = client().getDB(CONFIG_MANAGER.getDbName());
    GridFSDBFileWrapper fileWrapper = null;
    final Set<String> collections = db.getCollectionNames();
    final Iterator<String> it = collections.iterator();
    while (it.hasNext() && fileWrapper == null) {
        final String collection = it.next();
        if (collection.endsWith("." + GRIDFS_FILES_COLLECTION)) {
            final String[] tokens = Splitter.on('.').omitEmptyStrings().trimResults().splitToList(collection)
                    .toArray(new String[2]);
            if (tokens.length >= 2) {
                final String namespace = tokens[tokens.length - 2];
                final GridFS gfsNs = new GridFS(db, namespace);
                final GridFSDBFile file = gfsNs.findOne(new BasicDBObject(FILE_OPEN_ACCESS_LINK_PROP, secret2));
                if (file != null) {
                    fileWrapper = new GridFSDBFileWrapper(namespace, file);
                }/*from w  ww .  java  2 s. c  o m*/
            }
        }
    }
    return fileWrapper;
}

From source file:eu.eubrazilcc.lvl.storage.mongodb.MongoDBConnector.java

License:EUPL

/**
 * Checks whether or not the specified file exists in the database, returning <tt>true</tt> only when the file exists in the 
 * specified namespace./*from   w ww.  ja  v a  2  s.  c om*/
 * @param namespace - (optional) name space to be searched for in the database. When nothing specified, the default bucket is used
 * @param filename - filename to be searched for in the database
 * @return
 */
public boolean fileExists(final @Nullable String namespace, final String filename) {
    checkArgument(isNotBlank(filename), "Uninitialized or invalid filename");
    final DB db = client().getDB(CONFIG_MANAGER.getDbName());
    final GridFS gfsNs = isNotBlank(namespace) ? new GridFS(db, namespace.trim()) : new GridFS(db);
    return gfsNs.findOne(filename.trim()) != null;
}

From source file:fr.wseduc.gridfs.GridFSPersistor.java

License:Apache License

private void getFile(Message<Buffer> message, JsonObject json) {
    JsonObject query = json.getObject("query");
    if (query == null) {
        return;/*from ww  w . j av  a  2s.c  o m*/
    }
    GridFS fs = new GridFS(db, bucket);
    try {
        GridFSDBFile f = fs.findOne(jsonToDBObject(query));
        if (f == null) {
            replyError(message, "File not found with query : " + query.encode());
            return;
        }
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        f.writeTo(os);
        message.reply(new Buffer(os.toByteArray()));
    } catch (IOException | MongoException e) {
        container.logger().error(e.getMessage(), e);
        JsonObject j = new JsonObject().putString("status", "error").putString("message", e.getMessage());
        try {
            message.reply(new Buffer(j.encode().getBytes("UTF-8")));
        } catch (UnsupportedEncodingException e1) {
            container.logger().error(e1.getMessage(), e1);
        }
    }
}

From source file:fr.wseduc.gridfs.GridFSPersistor.java

License:Apache License

private void copyFile(Message<Buffer> message, JsonObject json) {
    JsonObject query = json.getObject("query");
    if (query == null) {
        return;/*w  w  w . jav a  2s . c  o  m*/
    }
    GridFS fs = new GridFS(db, bucket);
    try {
        GridFSDBFile f = fs.findOne(jsonToDBObject(query));
        if (f == null) {
            replyError(message, "File not found with query : " + query.encode());
            return;
        }
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        f.writeTo(os);
        JsonObject j = new JsonObject();
        j.putString("content-type", f.getContentType());
        j.putString("filename", f.getFilename());
        persistFile(message, os.toByteArray(), j);
    } catch (IOException | MongoException e) {
        replyError(message, e.getMessage());
    }
}