package eu.mikroskeem.mongohackery; import com.mongodb.MongoClient; import com.mongodb.client.MongoDatabase; import com.mongodb.client.gridfs.GridFSBucket; import com.mongodb.client.gridfs.GridFSBuckets; import com.mongodb.client.gridfs.model.GridFSUploadOptions; import org.bson.Document; import org.bson.types.ObjectId; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.util.stream.Collectors; import static com.mongodb.client.model.Filters.eq; public class Main { public static void main(String... args){ new Main(); } public Main(){ MongoClient client = new MongoClient(); MongoDatabase leTest = client.getDatabase("leTest"); GridFSBucket gridfs = GridFSBuckets.create(leTest, "files"); /* * Ransom data * Should use file here actually */ InputStream is = new ByteArrayInputStream("topkek".getBytes()); /* Remove (if present) */ try { gridfs.delete(gridfs.find(eq("filename", "topkek")).first().getId()); } catch(NullPointerException ignored){} /* Insert */ GridFSUploadOptions options = new GridFSUploadOptions() .chunkSizeBytes(1024) .metadata(new Document("contentType", "text/plain")); /* * NOTE: 'contentType' isn't standard! It is here, because I want to see * It is there, because I tend to use it with GridFS */ ObjectId id = gridfs.uploadFromStream("topkek", is, options); System.out.println(id); /* Now read */ InputStream os = gridfs.openDownloadStream(gridfs.find(eq("filename", "topkek")).first().getId()); String res = new BufferedReader(new InputStreamReader(os)) .lines().collect(Collectors.joining("\n")); System.out.println(res); /* Remove */ gridfs.delete(gridfs.find(eq("filename", "topkek")).first().getId()); } }