Example usage for com.mongodb.client.gridfs.model GridFSFile getFilename

List of usage examples for com.mongodb.client.gridfs.model GridFSFile getFilename

Introduction

In this page you can find the example usage for com.mongodb.client.gridfs.model GridFSFile getFilename.

Prototype

public String getFilename() 

Source Link

Document

The filename

Usage

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

License:Apache License

private JSONObject executeFind(GridFSBucket gridFS, String query, String sortBy, String limit, String skip)
        throws JSONException {
    Document queryObj = Document.parse(query);
    Document sortObj = Document.parse(sortBy);
    int filesLimit = Integer.parseInt(limit);
    int filesSkip = Integer.parseInt(skip);
    // Partial Keys cant be fetched for a file

    MongoCursor<GridFSFile> it = gridFS.find(queryObj).sort(sortObj).skip(filesSkip).limit(filesLimit)
            .iterator();/* w  ww  . j a  va  2s. co m*/

    JSONArray fileList = new JSONArray();
    while (it.hasNext()) {
        GridFSFile fsFile = it.next();

        JSONObject file = new JSONObject();

        file.put("_id", fsFile.getId().asObjectId().getValue());
        file.put("fileName", fsFile.getFilename());
        file.put("length", fsFile.getLength());
        file.put("chunkSize", fsFile.getChunkSize());
        file.put("uploadDate", fsFile.getUploadDate());
        file.put("md5", fsFile.getMD5());
        if (fsFile.getMetadata() != null) {
            file.put("metadata", fsFile.getMetadata());
        }

        fileList.put(file);

    }
    JSONObject result = new JSONObject();
    long count = fileList.length();
    result.put("documents", fileList);
    result.put("editable", true);
    result.put("count", count);
    return result;
}

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

License:Apache License

/**
 * Service implementation for retrieving the specified file stored in GridFS.
 *
 * @param dbName Name of Database/*from   ww  w.ja v a2 s .c o  m*/
 * @param bucketName Name of GridFS Bucket
 * @param _id ObjectId of the file to be retrieved
 * @return Requested multipartfile for viewing or download based on 'download' param.
 */
public File getFile(String dbName, String bucketName, String _id)
        throws ValidationException, DatabaseException, CollectionException {
    if (dbName == null) {
        throw new DatabaseException(ErrorCodes.DB_NAME_EMPTY, "Database Name Is Null");
    }
    if (dbName.equals("")) {
        throw new DatabaseException(ErrorCodes.DB_NAME_EMPTY, "Database Name Empty");
    }
    File tempFile = null;
    try {
        // if (!databaseService.getDbList().contains(dbName)) {
        //   throw new DatabaseException(ErrorCodes.DB_DOES_NOT_EXISTS,

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

        ObjectId objectId = new ObjectId(_id);

        MongoDatabase db = mongoInstance.getDatabase(dbName);

        GridFSBucket gridFS = GridFSBuckets.create(db, bucketName);

        Document id = new Document();

        id.put("_id", objectId);

        GridFSFile fsFile = gridFS.find(id).first();

        if (fsFile != null) {

            String tempDir = System.getProperty("java.io.tmpdir");

            tempFile = new File(tempDir + "/" + fsFile.getFilename());

            FileOutputStream streamToDownloadTo = new FileOutputStream(tempFile);

            gridFS.downloadToStream(objectId, streamToDownloadTo);

            streamToDownloadTo.close();

        }

    } catch (MongoException m) {
        throw new CollectionException(ErrorCodes.GET_COLLECTION_LIST_EXCEPTION, m.getMessage());
    } catch (IOException e) {
        throw new CollectionException(ErrorCodes.GET_COLLECTION_LIST_EXCEPTION, e.getMessage());
    }
    return tempFile;
}

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

License:Apache License

/**
 * Service implementation for dropping a file from GridFS.
 *
 * @param dbName Name of Database// w  ww  . ja va2  s. c o m
 * @param bucketName Name of GridFS Bucket
 * @param _id Object id of file to be deleted
 * @return Status message.
 */
public String deleteFile(String dbName, String bucketName, String _id)
        throws DatabaseException, DocumentException, CollectionException, ValidationException {
    if (dbName == null) {
        throw new DatabaseException(ErrorCodes.DB_NAME_EMPTY, "Database name is null");

    }
    if (dbName.equals("")) {
        throw new DatabaseException(ErrorCodes.DB_NAME_EMPTY, "Database Name Empty");
    }

    if (bucketName == null) {
        throw new CollectionException(ErrorCodes.COLLECTION_NAME_EMPTY, "Bucket name is null");
    }
    if (bucketName.equals("")) {
        throw new CollectionException(ErrorCodes.COLLECTION_NAME_EMPTY, "Bucket Name Empty");
    }

    String result = null;
    GridFSFile gridFSFile = null;
    try {
        // if (!databaseService.getDbList().contains(dbName)) {
        //   throw new DatabaseException(ErrorCodes.DB_DOES_NOT_EXISTS,
        //       "DB [" + dbName + "] DOES NOT EXIST");
        // }
        if (_id == null) {
            throw new DocumentException(ErrorCodes.DOCUMENT_EMPTY, "File is empty");
        }

        ObjectId objectId = new ObjectId(_id);

        MongoDatabase db = mongoInstance.getDatabase(dbName);

        GridFSBucket gridFS = GridFSBuckets.create(db, bucketName);

        Document id = new Document();

        id.put("_id", objectId);

        gridFSFile = gridFS.find(id).first();
        if (gridFSFile == null) {
            throw new DocumentException(ErrorCodes.DOCUMENT_DOES_NOT_EXIST, "Document does not exist !");
        }

        gridFS.delete(objectId);

    } catch (MongoException e) {
        throw new DocumentException(ErrorCodes.DOCUMENT_DELETION_EXCEPTION, e.getMessage());
    }
    result = "File [" + gridFSFile.getFilename() + "] has been deleted.";
    return result;
}

From source file:gridfs.GridFSTour.java

License:Apache License

/**
 * Run this main method to see the output of this quick example.
 *
 * @param args takes an optional single argument for the connection string
 * @throws FileNotFoundException if the sample file cannot be found
 * @throws IOException if there was an exception closing an input stream
 *//*from  w ww.  j a v a 2s  .  c  o m*/
public static void main(final String[] args) throws FileNotFoundException, IOException {
    MongoClient mongoClient;

    if (args.length == 0) {
        // connect to the local database server
        mongoClient = new MongoClient();
    } else {
        mongoClient = new MongoClient(new MongoClientURI(args[0]));
    }

    // get handle to "mydb" database
    MongoDatabase database = mongoClient.getDatabase("mydb");
    database.drop();

    GridFSBucket gridFSBucket = GridFSBuckets.create(database);

    /*
     * UploadFromStream Example
     */
    // Get the input stream
    InputStream streamToUploadFrom = new ByteArrayInputStream("Hello World".getBytes(StandardCharsets.UTF_8));

    // Create some custom options
    GridFSUploadOptions options = new GridFSUploadOptions().chunkSizeBytes(1024)
            .metadata(new Document("type", "presentation"));

    ObjectId fileId = gridFSBucket.uploadFromStream("mongodb-tutorial", streamToUploadFrom, options);
    streamToUploadFrom.close();
    System.out.println("The fileId of the uploaded file is: " + fileId.toHexString());

    /*
     * OpenUploadStream Example
     */

    // Get some data to write
    byte[] data = "Data to upload into GridFS".getBytes(StandardCharsets.UTF_8);

    GridFSUploadStream uploadStream = gridFSBucket.openUploadStream("sampleData");
    uploadStream.write(data);
    uploadStream.close();
    System.out.println("The fileId of the uploaded file is: " + uploadStream.getFileId().toHexString());

    /*
     * Find documents
     */
    gridFSBucket.find().forEach(new Block<GridFSFile>() {
        @Override
        public void apply(final GridFSFile gridFSFile) {
            System.out.println(gridFSFile.getFilename());
        }
    });

    /*
     * Find documents with a filter
     */
    gridFSBucket.find(eq("metadata.contentType", "image/png")).forEach(new Block<GridFSFile>() {
        @Override
        public void apply(final GridFSFile gridFSFile) {
            System.out.println(gridFSFile.getFilename());
        }
    });

    /*
     * DownloadToStream
     */
    FileOutputStream streamToDownloadTo = new FileOutputStream("/tmp/mongodb-tutorial.txt");
    gridFSBucket.downloadToStream(fileId, streamToDownloadTo);
    streamToDownloadTo.close();

    /*
     * DownloadToStreamByName
     */
    streamToDownloadTo = new FileOutputStream("/tmp/mongodb-tutorial.txt");
    GridFSDownloadByNameOptions downloadOptions = new GridFSDownloadByNameOptions().revision(0);
    gridFSBucket.downloadToStreamByName("mongodb-tutorial", streamToDownloadTo, downloadOptions);
    streamToDownloadTo.close();

    /*
     * OpenDownloadStream
     */
    GridFSDownloadStream downloadStream = gridFSBucket.openDownloadStream(fileId);
    int fileLength = (int) downloadStream.getGridFSFile().getLength();
    byte[] bytesToWriteTo = new byte[fileLength];
    downloadStream.read(bytesToWriteTo);
    downloadStream.close();

    System.out.println(new String(bytesToWriteTo, StandardCharsets.UTF_8));

    /*
     * OpenDownloadStreamByName
     */

    downloadStream = gridFSBucket.openDownloadStreamByName("sampleData");
    fileLength = (int) downloadStream.getGridFSFile().getLength();
    bytesToWriteTo = new byte[fileLength];
    downloadStream.read(bytesToWriteTo);
    downloadStream.close();

    System.out.println(new String(bytesToWriteTo, StandardCharsets.UTF_8));

    /*
     * Rename
     */
    gridFSBucket.rename(fileId, "mongodbTutorial");

    /*
     * Delete
     */
    gridFSBucket.delete(fileId);

    database.drop();
}

From source file:org.apache.nifi.processors.mongodb.gridfs.FetchGridFS.java

License:Apache License

private void handleFile(GridFSBucket bucket, ProcessSession session, ProcessContext context, FlowFile parent,
        GridFSFile input, String query) {
    Map<String, String> attrs = new HashMap<>();
    attrs.put(METADATA_ATTRIBUTE, input.getMetadata() != null ? input.getMetadata().toJson() : "{}");
    if (context.getProperty(QUERY_ATTRIBUTE).isSet()) {
        String key = context.getProperty(QUERY_ATTRIBUTE).evaluateAttributeExpressions(parent).getValue();
        attrs.put(key, query);//from  w  w w  .  j  a va 2s  .  c  om
    }
    attrs.put(CoreAttributes.FILENAME.key(), input.getFilename());
    FlowFile output = parent != null ? session.create(parent) : session.create();
    output = session.write(output, out -> bucket.downloadToStream(input.getObjectId(), out));
    output = session.putAllAttributes(output, attrs);
    session.transfer(output, REL_SUCCESS);
    session.getProvenanceReporter().receive(output, getTransitUri(input.getObjectId(), output, context));
}

From source file:org.restheart.handlers.files.GetFileBinaryHandler.java

License:Open Source License

private void sendBinaryContent(final GridFSBucket gridFSBucket, final GridFSFile file,
        final HttpServerExchange exchange) throws IOException {
    LOGGER.trace("Filename = {}", file.getFilename());
    LOGGER.trace("Content length = {}", file.getLength());

    if (file.getMetadata() != null && file.getMetadata().get("contentType") != null) {
        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE,
                file.getMetadata().get("contentType").toString());
    } else if (file.getExtraElements() != null && file.getExtraElements().get("contentType") != null) {
        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE,
                file.getExtraElements().get("contentType").toString());
    } else {/*from w ww . ja  v a  2  s  .c  om*/
        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, APPLICATION_OCTET_STREAM);
    }

    exchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, file.getLength());

    exchange.getResponseHeaders().put(Headers.CONTENT_DISPOSITION,
            String.format("inline; filename=\"%s\"", extractFilename(file)));

    exchange.getResponseHeaders().put(Headers.CONTENT_TRANSFER_ENCODING, CONTENT_TRANSFER_ENCODING_BINARY);

    ResponseHelper.injectEtagHeader(exchange, file.getMetadata());

    exchange.setStatusCode(HttpStatus.SC_OK);

    gridFSBucket.downloadToStream(file.getId().asObjectId().getValue(), exchange.getOutputStream());

    exchange.endExchange();
}

From source file:org.restheart.handlers.files.GetFileBinaryHandler.java

License:Open Source License

private String extractFilename(final GridFSFile dbsfile) {
    return dbsfile.getFilename() != null ? dbsfile.getFilename() : dbsfile.getId().toString();
}