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);
}
}
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();
}
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);
}
}
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);
}
}
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);
}
Aggregations