Java Code Examples for com.mongodb.client.gridfs.GridFSBucket
阿新 • • 發佈:2019-01-02
Mongo
- Java Code Examples for com.mongodb.client.gridfs.GridFSBucket
- 以下是顯示如何使用com.mongodb.client.gridfs.GridFSBucket的示例。
- Example 1
- Example 2
- Example 3
- Example 4
- Example 5
- Example 6
- Example 7
- Example 8
- Example 9
- Example 10
- Example 11
- Example 12
- Example 13
- Example 14
- Example 15
- Example 16
- Example 17
- Example 18
- Example 19
- Example 20
- Example 21
- Example 22
- Example 23
- Example 24
- Example 25
- Example 26
- Example 27
- Example 28
- Example 29
- Example 30
- Example31
- Example32
- Example33
- Example34
- Example35
- Example36
- Example37
- Example38
- Example39
- That's all. Thank you!
Java Code Examples for com.mongodb.client.gridfs.GridFSBucket
以下是顯示如何使用com.mongodb.client.gridfs.GridFSBucket的示例。
Example 1
/**
* Create a file in GridFS with the given filename and write
* some random data to it.
* @param filename the name of the file to create
* @param size the number of random bytes to write
* @param vertx the Vert.x instance
* @param handler a handler that will be called when the file
* has been written
*/
private void prepareData(String filename, int size, Vertx vertx,
Handler<AsyncResult<String>> handler) {
vertx.<String>executeBlocking(f -> {
try (MongoClient client = new MongoClient(mongoConnector.serverAddress)) {
MongoDatabase db = client.getDatabase(MongoDBTestConnector.MONGODB_DBNAME);
GridFSBucket gridFS = GridFSBuckets.create(db);
try (GridFSUploadStream os = gridFS.openUploadStream(filename)) {
for (int i = 0; i < size; ++i) {
os.write((byte)(i & 0xFF));
}
}
}
f.complete(filename);
}, handler);
}
Example 2
@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);
}
Example 3
@Override
public InputStream getAssociatedDocumentStream(String uniqueId, String fileName) {
GridFSBucket gridFS = createGridFSConnection();
GridFSFile file = gridFS.find(new Document(ASSOCIATED_METADATA + "." + FILE_UNIQUE_ID_KEY, getGridFsId(uniqueId, fileName))).first();
if (file == null) {
return null;
}
InputStream is = gridFS.openDownloadStream(file.getObjectId());
;
Document metadata = file.getMetadata();
if (metadata.containsKey(COMPRESSED_FLAG)) {
boolean compressed = (boolean) metadata.remove(COMPRESSED_FLAG);
if (compressed) {
is = new InflaterInputStream(is);
}
}
return is;
}
Example 4
private void uploadStream(SmofGridRef ref, String name, InputStream stream) {
final String bucketName = ref.getBucketName();
final ObjectId id;
final GridFSBucket bucket;
Preconditions.checkNotNull(bucketName, "No bucket specified");
final GridFSUploadOptions options = new GridFSUploadOptions().metadata(ref.getMetadata());
bucket = pool.getBucket(bucketName);
id = bucket.uploadFromStream(name, stream, options);
ref.setId(id);
}
Example 5
@Override
public InputStream download(SmofGridRef ref) {
final String bucketName = ref.getBucketName();
final ObjectId id = ref.getId();
Preconditions.checkArgument(id != null, "No download source found");
Preconditions.checkArgument(bucketName != null, "No bucket specified");
final GridFSBucket bucket = pool.getBucket(bucketName);
return bucket.openDownloadStream(id);
}
Example 6
@Override
public void drop(SmofGridRef ref) {
final String bucketName = ref.getBucketName();
final ObjectId id = ref.getId();
Preconditions.checkArgument(id != null, "No download source found");
Preconditions.checkArgument(bucketName != null, "No bucket specified");
final GridFSBucket bucket = pool.getBucket(bucketName);
bucket.delete(id);
}
Example 7
private void deleteLog(Date olderThan) {
MongoCollection<Log> logCollection = mongoService.getMongoClient().getDatabase(database).getCollection(collection, Log.class);
Bson filter = Filters.lt("timeStamp", olderThan);
logCollection.find(filter).forEach((Block<? super Log>) log -> {
log.getLogFiles().forEach(logFile -> {
GridFSBucket gridFSBucket = GridFSBuckets.create(mongoService.getMongoClient().getDatabase(database), logFile.getBucket());
gridFSBucket.delete(logFile.getFileObjectId());
});
});
DeleteResult deleteResult = logCollection.deleteMany(filter);
}
Example 8
public BucketStreamResource(MongoDatabase database, String bucket, ObjectId objectId) {
super((StreamSource) () -> {
GridFSBucket gridFSBucket = GridFSBuckets.create(database, bucket);
return gridFSBucket.openDownloadStream(objectId);
}, gridFSFile(database, bucket, objectId).getFilename());
this.database = database;
this.bucket = bucket;
this.objectId = objectId;
}
Example 9
/**
* Connect to MongoDB and get the GridFS chunk size
* @param vertx the Vert.x instance
* @param handler a handler that will be called with the chunk size
*/
private void getChunkSize(Vertx vertx, Handler<AsyncResult<Integer>> handler) {
vertx.<Integer>executeBlocking(f -> {
try (MongoClient client = new MongoClient(mongoConnector.serverAddress)) {
MongoDatabase db = client.getDatabase(MongoDBTestConnector.MONGODB_DBNAME);
GridFSBucket gridFS = GridFSBuckets.create(db);
f.complete(gridFS.getChunkSizeBytes());
}
}, handler);
}
Example 10
@Override
protected void prepareData(TestContext context, Vertx vertx, String path,
Handler<AsyncResult<String>> handler) {
String filename = PathUtils.join(path, ID);
vertx.<String>executeBlocking(f -> {
try (MongoClient client = new MongoClient(mongoConnector.serverAddress)) {
MongoDatabase db = client.getDatabase(MongoDBTestConnector.MONGODB_DBNAME);
GridFSBucket gridFS = GridFSBuckets.create(db);
byte[] contents = CHUNK_CONTENT.getBytes(StandardCharsets.UTF_8);
gridFS.uploadFromStream(filename, new ByteArrayInputStream(contents));
f.complete(filename);
}
}, handler);
}
Example 11
@Override
protected void validateAfterStoreDelete(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();
context.assertTrue(Iterables.isEmpty(files));
}
f.complete();
}, handler);
}
Example 12
protected void initDB(String dbName) {
//set up the persistence layer
//Connect to the local MongoDB instance
MongoClient m = new MongoClient();
//get the DB with the given Name
MongoDatabase chatDB = m.getDatabase(dbName);
//initialize our collections
DocumentCollections.init(this, chatDB);
//set up GridFs for storing files
GridFSBucket fs = GridFSBuckets.create(chatDB,"persistedPages");
//the base class UIEngine needs the gridFS for
//persisting sessions
super.initDB(chatDB, fs);
}
Example 13
@Override
public OperationResult deleteFile(
final Database db,
final String dbName,
final String bucketName,
final BsonValue fileId,
final String requestEtag,
final boolean checkEtag) {
final String bucket = extractBucketName(bucketName);
GridFSBucket gridFSBucket = GridFSBuckets.create(
db.getDatabase(dbName),
bucket);
GridFSFile file = gridFSBucket
.find(eq("_id", fileId))
.limit(1).iterator().tryNext();
if (file == null) {
return new OperationResult(HttpStatus.SC_NOT_FOUND);
} else if (checkEtag) {
Object oldEtag = file.getMetadata().get("_etag");
if (oldEtag != null) {
if (requestEtag == null) {
return new OperationResult(HttpStatus.SC_CONFLICT, oldEtag);
} else if (!Objects.equals(oldEtag.toString(), requestEtag)) {
return new OperationResult(
HttpStatus.SC_PRECONDITION_FAILED, oldEtag);
}
}
}
gridFSBucket.delete(fileId);
return new OperationResult(HttpStatus.SC_NO_CONTENT);
}
Example 14
@Override
public void handleRequest(
HttpServerExchange exchange,
RequestContext context)
throws Exception {
if (context.isInError()) {
next(exchange, context);
return;
}
LOGGER.trace("GET " + exchange.getRequestURL());
final String bucket = extractBucketName(context.getCollectionName());
GridFSBucket gridFSBucket = GridFSBuckets.create(
MongoDBClientSingleton.getInstance().getClient()
.getDatabase(context.getDBName()),
bucket);
GridFSFile dbsfile = gridFSBucket
.find(eq("_id", context.getDocumentId()))
.limit(1).iterator().tryNext();
if (dbsfile == null) {
fileNotFound(context, exchange);
} else if (!checkEtag(exchange, dbsfile)) {
sendBinaryContent(context, gridFSBucket, dbsfile, exchange);
}
next(exchange, context);
}
Example 15
@Override
public void deleteAllDocuments() {
GridFSBucket gridFS = createGridFSConnection();
gridFS.drop();
MongoDatabase db = mongoClient.getDatabase(database);
MongoCollection<Document> coll = db.getCollection(rawCollectionName);
coll.deleteMany(new Document());
}
Example 16
@Override
public List<AssociatedDocument> getAssociatedDocuments(String uniqueId, FetchType fetchType) throws Exception {
GridFSBucket gridFS = createGridFSConnection();
List<AssociatedDocument> assocDocs = new ArrayList<>();
if (!FetchType.NONE.equals(fetchType)) {
GridFSFindIterable files = gridFS.find(new Document(ASSOCIATED_METADATA + "." + DOCUMENT_UNIQUE_ID_KEY, uniqueId));
for (GridFSFile file : files) {
AssociatedDocument ad = loadGridFSToAssociatedDocument(gridFS, file, fetchType);
assocDocs.add(ad);
}
}
return assocDocs;
}
Example 17
@Override
public AssociatedDocument getAssociatedDocument(String uniqueId, String fileName, FetchType fetchType) throws Exception {
GridFSBucket gridFS = createGridFSConnection();
if (!FetchType.NONE.equals(fetchType)) {
GridFSFile file = gridFS.find(new Document(ASSOCIATED_METADATA + "." + FILE_UNIQUE_ID_KEY, getGridFsId(uniqueId, fileName))).first();
if (null != file) {
return loadGridFSToAssociatedDocument(gridFS, file, fetchType