Example usage for com.mongodb.gridfs GridFS createFile

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

Introduction

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

Prototype

public GridFSInputFile createFile(final InputStream in, final String filename) 

Source Link

Document

Creates a file entry.

Usage

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

License:Apache License

/**
 * Service implementation for uploading a file to GridFS.
 *
 * @param dbName      Name of Database/*from w  w w.  j  av  a2 s  .  c o m*/
 * @param bucketName  Name of GridFS Bucket
 * @param formData    formDataBodyPart of the uploaded file
 * @param inputStream inputStream of the uploaded file
 * @param dbInfo      Mongo Db Configuration provided by user to connect to.
 * @returns Success message with additional file details such as name, size,
 * download url & deletion url as JSON Array string.
 */
public JSONArray insertFile(String dbName, String bucketName, String dbInfo, InputStream inputStream,
        FormDataBodyPart formData)
        throws DatabaseException, CollectionException, 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");
    }

    JSONArray result = new JSONArray();
    FormDataContentDisposition fileData = formData.getFormDataContentDisposition();
    try {
        if (!mongoInstance.getDatabaseNames().contains(dbName)) {
            throw new UndefinedDatabaseException("DB [" + dbName + "] DOES NOT EXIST");
        }

        GridFS gridFS = new GridFS(mongoInstance.getDB(dbName), bucketName);
        GridFSInputFile fsInputFile = gridFS.createFile(inputStream, fileData.getFileName());
        fsInputFile.setContentType(formData.getMediaType().toString());
        fsInputFile.save();
        JSONObject obj = new JSONObject();
        obj.put("name", fsInputFile.getFilename());
        obj.put("size", fsInputFile.getLength());
        obj.put("url", String.format("services/%s/%s/gridfs/getfile?id=%s&download=%s&dbInfo=%s&ts=%s", dbName,
                bucketName, fsInputFile.getId().toString(), false, dbInfo, new Date()));
        obj.put("delete_url", String.format("services/%s/%s/gridfs/dropfile?id=%s&dbInfo=%s&ts=%s", dbName,
                bucketName, fsInputFile.getId().toString(), dbInfo, new Date().getTime()));
        obj.put("delete_type", "GET");
        result.put(obj);

    } catch (Exception e) {
        CollectionException ce = new CollectionException(ErrorCodes.UPLOAD_FILE_EXCEPTION,
                "UPLOAD_FILE_EXCEPTION", e.getCause());
        throw ce;
    }
    return result;
}

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

License:Apache License

/**
 * Saves a file to the database by file name. This is used during a form upload. We use tika to
 * determine the content type./* ww w .  ja  v a  2  s.  co m*/
 *
 * TODO: Refactor this mess
 *
 * @param databaseName the name of the database
 * @param bucketName the name of the bucket
 * @param fileName the name of the file
 * @param overwrite whether to overwrite an existing file with the same name
 * @param stream the file byte stream
 * @return the Mongo ID of the file
 * @throws DatasourceException
 * @throws ExistsException
 * @throws NotFoundException
 */
@Override
public String addByForm(String databaseName, String bucketName, String fileName, boolean overwrite,
        InputStream stream) throws DatasourceException, ExistsException, NotFoundException {
    String fileId = null;
    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) {
            // the file does not exist -- create
            GridFSInputFile dbFile = gfsBucket.createFile(stream, fileName);
            dbFile.setContentType(tika.detect(fileName));
            dbFile.save();
            fileId = dbFile.getId().toString();
        } else {
            // the file exists
            if (overwrite) {
                // overwrite the existing file
                gfsBucket.remove(gfsFile);
                GridFSInputFile inputFile = gfsBucket.createFile(stream, fileName);
                inputFile.setContentType(tika.detect(fileName));
                inputFile.save();
                fileId = inputFile.getId().toString();
            } else {
                throw new ExistsException("The file already exists in the bucket");
            }
        }
    } catch (MongoException ex) {
        logger.error("Could not persist entity to bucket", ex);
        throw new DatasourceException("Could not persist file to bucket");
    }
    if (fileId == null || fileId.isEmpty()) {
        throw new DatasourceException("Could not persist file to bucket");
    }
    return fileId;
}

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

License:Apache License

/**
 * Saves a document to the database by file name. If the document already exists this request
 * will be dropped and the existing file will not be overwritten.
 *
 * @param databaseName the database//  www.j a  v  a2 s  .c  o  m
 * @param bucketName the bucket
 * @param fileName the file name
 * @param inputStream the binary payload
 * @return the identifier of the file
 * @throws DatasourceException
 * @throws ExistsException
 * @throws NotFoundException
 */
@Override
public String addByFileName(String databaseName, String bucketName, String fileName, InputStream inputStream)
        throws DatasourceException, ExistsException, 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);
        if (gfsBucket.findOne(fileName) != null) {
            throw new ExistsException("The file already exists");
        }
        GridFSInputFile inputFile = gfsBucket.createFile(inputStream, fileName);
        inputFile.setContentType(tika.detect(fileName));
        inputFile.save();
        return inputFile.getId().toString();
    } catch (MongoException ex) {
        logger.error("An error occured while adding the file", ex);
        throw new DatasourceException("An error occured while adding the file");
    }
}

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

License:Apache License

/**
 * Updates a file in the database. If the file exists in the database it will be updated. If the
 * file doesn't exist it will be created.
 *
 * @param databaseName the database//from  ww  w.  java  2  s.  c  om
 * @param bucketName the bucket
 * @param fileName the file name
 * @param inputStream the binary payload
 * @return the identifier of the file
 * @throws DatasourceException
 * @throws NotFoundException
 */
@Override
public String updateByFileName(String databaseName, String bucketName, String fileName, InputStream inputStream)
        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);
        GridFSDBFile gfsFile = gfsBucket.findOne(fileName);
        if (gfsFile == null) {
            GridFSInputFile inputFile = gfsBucket.createFile(inputStream, fileName);
            inputFile.setContentType(tika.detect(fileName));
            inputFile.save();
            return inputFile.getId().toString();
        } else {
            gfsBucket.remove(gfsFile);
            GridFSInputFile inputFile = gfsBucket.createFile(inputStream, fileName);
            inputFile.setContentType(tika.detect(fileName));
            inputFile.save();
            return inputFile.getId().toString();
        }
    } catch (MongoException ex) {
        logger.error("An error occured while updating the file", ex);
        throw new DatasourceException("An error occured while updating the file");
    }
}

From source file:tango.mongo.ImageManager.java

License:Open Source License

private void transferFiles(String queryField, ObjectId queryValue, GridFS gfsSource, GridFS gfsDestination) {
    BasicDBObject query = new BasicDBObject(queryField, queryValue);
    List<GridFSDBFile> files = gfsSource.find(query); // FIXME charge tout en mmoire?
    for (GridFSDBFile file : files) {
        GridFSInputFile gfi = gfsDestination.createFile(file.getInputStream(), file.getFilename());
        gfi.put(queryField, queryValue);
        gfi.put("fileIdx", file.get("fileIdx"));
        gfi.put("fileType", file.get("fileType"));
        gfi.put("pixelDepth", file.get("pixelDepth"));
        gfi.put("unit", file.get("unit"));
        gfi.save();//from ww  w . ja v a 2  s  .  c o  m
        if (gfi != null)
            try {
                gfi.getOutputStream().close();
            } catch (IOException ex) {
                Logger.getLogger(ImageManager.class.getName()).log(Level.SEVERE, null, ex);
            }
    }
    gfsSource.remove(query);
}