Reputation: 33
Mongo Java driver: 3.6.0. Java: 1.8
I have a file saved in GridFs and when I try to open a download stream as MongoDb documentation says, I receive a cast exception.
Open download stream
ObjectId fileId; //The id of a file uploaded to GridFS, initialize to valid file id
GridFSDownloadStream downloadStream = gridFSBucket.openDownloadStream(fileId);
int fileLength = (int) downloadStream.getGridFSFile().getLength();
byte[] bytesToWriteTo = new byte[fileLength];
downloadStream.read(bytesToWriteTo); // >>>>>> Line failing
downloadStream.close();
Caused by: java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.Integer
at org.bson.Document.getInteger(Document.java:170) ~[bson-3.6.0.jar:na]
at com.mongodb.client.gridfs.GridFSDownloadStreamImpl.getChunk(GridFSDownloadStreamImpl.java:221) ~[mongodb-driver-3.6.0.jar:na]
at com.mongodb.client.gridfs.GridFSDownloadStreamImpl.getBuffer(GridFSDownloadStreamImpl.java:275) ~[mongodb-driver-3.6.0.jar:na]
at com.mongodb.client.gridfs.GridFSDownloadStreamImpl.read(GridFSDownloadStreamImpl.java:100) ~[mongodb-driver-3.6.0.jar:na]
at com.mongodb.client.gridfs.GridFSDownloadStreamImpl.read(GridFSDownloadStreamImpl.java:90) ~[mongodb-driver-3.6.0.jar:na]
at com.xxx.proyect.service.conf.service.PdfService.getPdf(PdfService.java:63) ~[module-pdfs-1.8.0-SNAPSHOT.jar:na]
... 83 common frames omitted
Upvotes: 0
Views: 413
Reputation: 33
It looks like the problem is a different version uploading and downloading the file. I uploaded a file with NoSQLBooter to a Grid Bucket and I was trying to download it by sw with mongo java driver 3.6.0. It seems NoSQLBooster saves some field in a different way than driver, so driver is not able to open it.
My solution: I implemented a method to upload the file in order to be the same driver uploading and downloading and it worked!!!
public InsertPdfResponse addPdf(String userCode,
String filename,
MultipartFile file){
byte[] bytesToWriteTo;
GridFSUploadStream uploadStream = null;
try {
GridFSUploadOptions options = new GridFSUploadOptions()
.chunkSizeBytes(358400)
.metadata(new Document("author", userCode));
uploadStream = gridFSBucket.openUploadStream(filename, options);
byte[] data = file.getBytes();
uploadStream.write(data);
uploadStream.close();
return InsertPdfResponse.builder().inserted(true).build();
}
I had some problems downloading the file after this solution. File was downloaded, but only the first page in the pdf was correct and the others blank. I read it is because of the way I was reading bytes so I changed download service method a little bit.
public byte[] getPdf(String userCode, String filename) {
byte[] bytesToWriteTo;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
gridFSBucket.downloadToStream(filename, bos);
return bos.toByteArray();
}
Upvotes: 1