Search in sources :

Example 6 with GridFSBucket

use of com.mongodb.client.gridfs.GridFSBucket in project mongo-java-driver by mongodb.

the class UnifiedGridFSHelper method executeUpload.

public OperationResult executeUpload(final BsonDocument operation) {
    GridFSBucket bucket = entities.getBucket(operation.getString("object").getValue());
    BsonDocument arguments = operation.getDocument("arguments");
    String filename = null;
    byte[] bytes = null;
    GridFSUploadOptions options = new GridFSUploadOptions();
    for (Map.Entry<String, BsonValue> cur : arguments.entrySet()) {
        switch(cur.getKey()) {
            case "filename":
                filename = cur.getValue().asString().getValue();
                break;
            case "source":
                bytes = Hex.decode(cur.getValue().asDocument().getString("$$hexBytes").getValue());
                break;
            case "chunkSizeBytes":
                options.chunkSizeBytes(cur.getValue().asInt32().getValue());
                break;
            case "disableMD5":
                break;
            case "metadata":
                options.metadata(asDocument(cur.getValue().asDocument()));
                break;
            default:
                throw new UnsupportedOperationException("Unsupported argument: " + cur.getKey());
        }
    }
    requireNonNull(filename);
    requireNonNull(bytes);
    try {
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        BsonObjectId id = new BsonObjectId(bucket.uploadFromStream(filename, bais, options));
        if (operation.containsKey("saveResultAsEntity")) {
            entities.addResult(operation.getString("saveResultAsEntity").getValue(), id);
        }
        return OperationResult.of(id);
    } catch (Exception e) {
        return OperationResult.of(e);
    }
}
Also used : GridFSBucket(com.mongodb.client.gridfs.GridFSBucket) BsonDocument(org.bson.BsonDocument) ByteArrayInputStream(java.io.ByteArrayInputStream) BsonString(org.bson.BsonString) Map(java.util.Map) BsonObjectId(org.bson.BsonObjectId) GridFSUploadOptions(com.mongodb.client.gridfs.model.GridFSUploadOptions) BsonValue(org.bson.BsonValue)

Example 7 with GridFSBucket

use of com.mongodb.client.gridfs.GridFSBucket in project mongo-java-driver by mongodb.

the class GridFSTour method main.

/**
 * 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
 */
public static void main(final String[] args) throws FileNotFoundException, IOException {
    MongoClient mongoClient;
    if (args.length == 0) {
        // connect to the local database server
        mongoClient = MongoClients.create();
    } else {
        mongoClient = MongoClients.create(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.getObjectId().toHexString());
    /*
         * Find documents
         */
    gridFSBucket.find().forEach(new Consumer<GridFSFile>() {

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

        @Override
        public void accept(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");
    GridFSDownloadOptions downloadOptions = new GridFSDownloadOptions().revision(0);
    gridFSBucket.downloadToStream("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.openDownloadStream("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();
}
Also used : ObjectId(org.bson.types.ObjectId) GridFSUploadStream(com.mongodb.client.gridfs.GridFSUploadStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) GridFSFile(com.mongodb.client.gridfs.model.GridFSFile) Document(org.bson.Document) GridFSBucket(com.mongodb.client.gridfs.GridFSBucket) MongoClient(com.mongodb.client.MongoClient) ByteArrayInputStream(java.io.ByteArrayInputStream) GridFSDownloadStream(com.mongodb.client.gridfs.GridFSDownloadStream) FileOutputStream(java.io.FileOutputStream) GridFSDownloadOptions(com.mongodb.client.gridfs.model.GridFSDownloadOptions) MongoDatabase(com.mongodb.client.MongoDatabase) GridFSUploadOptions(com.mongodb.client.gridfs.model.GridFSUploadOptions)

Example 8 with GridFSBucket

use of com.mongodb.client.gridfs.GridFSBucket in project vcell by virtualcell.

the class VCMongoDbDriver method getBLOB.

public byte[] getBLOB(ObjectId objectId) {
    try {
        if (m == null) {
            String mongoDbHost = PropertyLoader.getRequiredProperty(PropertyLoader.mongodbHostInternal);
            // default 27017
            int mongoDbPort = Integer.parseInt(PropertyLoader.getRequiredProperty(PropertyLoader.mongodbPortInternal));
            m = new MongoClient(mongoDbHost, mongoDbPort);
        }
        ByteArrayOutputStream streamToDownloadTo = new ByteArrayOutputStream();
        MongoDatabase db = m.getDatabase(mongoDbDatabaseName);
        GridFSBucket gridFSBucket = GridFSBuckets.create(db);
        gridFSBucket.downloadToStream(objectId, streamToDownloadTo);
        byte[] blob = streamToDownloadTo.toByteArray();
        return blob;
    } catch (Exception e) {
        e.printStackTrace(System.out);
        try {
            if (m != null) {
                m.close();
            }
        } catch (Exception e2) {
            e2.printStackTrace(System.out);
        } finally {
            m = null;
        }
        throw new RuntimeException("failed to retrieve BLOB with ObjectId " + objectId.toHexString() + ": " + e.getMessage(), e);
    }
}
Also used : GridFSBucket(com.mongodb.client.gridfs.GridFSBucket) MongoClient(com.mongodb.MongoClient) ByteArrayOutputStream(org.apache.commons.io.output.ByteArrayOutputStream) MongoException(com.mongodb.MongoException) MongoDatabase(com.mongodb.client.MongoDatabase)

Example 9 with GridFSBucket

use of com.mongodb.client.gridfs.GridFSBucket in project vcell by virtualcell.

the class VCMongoDbDriver method storeBLOB.

public ObjectId storeBLOB(String blobName, String blobType, byte[] blob) {
    try {
        // send to MongoDB
        if (m == null) {
            String mongoDbHost = PropertyLoader.getRequiredProperty(PropertyLoader.mongodbHostInternal);
            // default 27017
            int mongoDbPort = Integer.parseInt(PropertyLoader.getRequiredProperty(PropertyLoader.mongodbPortInternal));
            m = new MongoClient(mongoDbHost, mongoDbPort);
        }
        MongoDatabase db = m.getDatabase(mongoDbDatabaseName);
        GridFSBucket gridFSBucket = GridFSBuckets.create(db);
        Document metadata = new Document();
        metadata.put("type", blobType);
        long msgTime = System.currentTimeMillis();
        metadata.put("inserttime", msgTime);
        metadata.put("inserttime_nice", new Date(msgTime).toString());
        GridFSUploadOptions options = new GridFSUploadOptions().chunkSizeBytes(1024).metadata(metadata);
        ByteArrayInputStream in = new ByteArrayInputStream(blob);
        ObjectId fileId = gridFSBucket.uploadFromStream(blobName, in, options);
        return fileId;
    } catch (Exception e) {
        e.printStackTrace(System.out);
        try {
            if (m != null) {
                m.close();
            }
        } catch (Exception e2) {
            e2.printStackTrace(System.out);
        } finally {
            m = null;
        }
        throw new RuntimeException("failed to store BLOB named " + blobName + ": " + e.getMessage(), e);
    }
}
Also used : ObjectId(org.bson.types.ObjectId) Document(org.bson.Document) Date(java.util.Date) MongoException(com.mongodb.MongoException) GridFSBucket(com.mongodb.client.gridfs.GridFSBucket) MongoClient(com.mongodb.MongoClient) ByteArrayInputStream(java.io.ByteArrayInputStream) MongoDatabase(com.mongodb.client.MongoDatabase) GridFSUploadOptions(com.mongodb.client.gridfs.model.GridFSUploadOptions)

Example 10 with GridFSBucket

use of com.mongodb.client.gridfs.GridFSBucket in project georocket by georocket.

the class MongoDBStoreTest method validateAfterStoreAdd.

@Override
protected void validateAfterStoreAdd(TestContext context, Vertx vertx, String path, Handler<AsyncResult<Void>> handler) {
    vertx.executeBlocking(f -> {
        try (MongoClient client = new MongoClient(mongoConnector.serverAddress)) {
            MongoDatabase db = client.getDatabase(MongoDBTestConnector.MONGODB_DBNAME);
            GridFSBucket gridFS = GridFSBuckets.create(db);
            GridFSFindIterable files = gridFS.find();
            GridFSFile file = files.first();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            gridFS.downloadToStream(file.getFilename(), baos);
            String contents = new String(baos.toByteArray(), StandardCharsets.UTF_8);
            context.assertEquals(CHUNK_CONTENT, contents);
        }
        f.complete();
    }, handler);
}
Also used : GridFSBucket(com.mongodb.client.gridfs.GridFSBucket) MongoClient(com.mongodb.MongoClient) GridFSFile(com.mongodb.client.gridfs.model.GridFSFile) GridFSFindIterable(com.mongodb.client.gridfs.GridFSFindIterable) ByteArrayOutputStream(java.io.ByteArrayOutputStream) MongoDatabase(com.mongodb.client.MongoDatabase)

Aggregations

GridFSBucket (com.mongodb.client.gridfs.GridFSBucket)14 MongoDatabase (com.mongodb.client.MongoDatabase)9 MongoClient (com.mongodb.MongoClient)8 ByteArrayInputStream (java.io.ByteArrayInputStream)5 BsonDocument (org.bson.BsonDocument)5 GridFSUploadOptions (com.mongodb.client.gridfs.model.GridFSUploadOptions)4 BsonString (org.bson.BsonString)4 MongoException (com.mongodb.MongoException)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 BsonValue (org.bson.BsonValue)3 ObjectId (org.bson.types.ObjectId)3 GridFSFindIterable (com.mongodb.client.gridfs.GridFSFindIterable)2 GridFSUploadStream (com.mongodb.client.gridfs.GridFSUploadStream)2 GridFSDownloadOptions (com.mongodb.client.gridfs.model.GridFSDownloadOptions)2 GridFSFile (com.mongodb.client.gridfs.model.GridFSFile)2 InputStream (java.io.InputStream)2 BsonObjectId (org.bson.BsonObjectId)2 Document (org.bson.Document)2 MongoClient (com.mongodb.client.MongoClient)1 GridFSDownloadStream (com.mongodb.client.gridfs.GridFSDownloadStream)1