@Override @SuppressWarnings("deprecation") public void encode(final BsonWriter writer, final GridFSFile value, final EncoderContext encoderContext) { BsonDocument bsonDocument = new BsonDocument(); bsonDocument.put("_id", value.getId()); bsonDocument.put("filename", new BsonString(value.getFilename())); bsonDocument.put("length", new BsonInt64(value.getLength())); bsonDocument.put("chunkSize", new BsonInt32(value.getChunkSize())); bsonDocument.put("uploadDate", new BsonDateTime(value.getUploadDate().getTime())); if (value.getMD5() != null) { bsonDocument.put("md5", new BsonString(value.getMD5())); } Document metadata = value.getMetadata(); if (metadata != null) { bsonDocument.put("metadata", new BsonDocumentWrapper<Document>(metadata, documentCodec)); } Document extraElements = value.getExtraElements(); if (extraElements != null) { bsonDocument.putAll(new BsonDocumentWrapper<Document>(extraElements, documentCodec)); } bsonDocumentCodec.encode(writer, bsonDocument, encoderContext); }
@Override protected Binary getBinary(InputStream in) throws IOException { try { // save the file to GridFS String inputName = "tmp-" + System.nanoTime(); ObjectId id = gridFSBucket.uploadFromStream(inputName, in); // now we know length and digest GridFSFile inputFile = gridFSBucket.find(Filters.eq(METADATA_PROPERTY_FILENAME, inputName)).first(); String digest = inputFile.getMD5(); // if the digest is already known then reuse it instead GridFSFile dbFile = gridFSBucket.find(Filters.eq(METADATA_PROPERTY_FILENAME, digest)).first(); if (dbFile == null) { // no existing file, set its filename as the digest gridFSBucket.rename(id, digest); } else { // file already existed, no need for the temporary one gridFSBucket.delete(id); } return new GridFSBinary(digest, blobProviderId); } finally { in.close(); } }
@Override @SuppressWarnings("deprecation") public void encode(final BsonWriter writer, final GridFSFile value, final EncoderContext encoderContext) { BsonDocument bsonDocument = new BsonDocument(); bsonDocument.put("_id", value.getId()); bsonDocument.put("filename", new BsonString(value.getFilename())); bsonDocument.put("length", new BsonInt64(value.getLength())); bsonDocument.put("chunkSize", new BsonInt32(value.getChunkSize())); bsonDocument.put("uploadDate", new BsonDateTime(value.getUploadDate().getTime())); if (value.getMD5() != null) { bsonDocument.put("md5", new BsonString(value.getMD5())); } Document metadata = value.getMetadata(); if (metadata != null) { bsonDocument.put("metadata", new BsonDocumentWrapper<Document>(metadata, documentCodec)); } Document extraElements = value.getExtraElements(); if (extraElements != null) { bsonDocument.putAll(new BsonDocumentWrapper<Document>(extraElements, documentCodec)); } bsonDocumentCodec.encode(writer, bsonDocument, encoderContext); }