com.thematchbox.db.MongoDBConnection Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of TheMatchBox-Common Show documentation
Show all versions of TheMatchBox-Common Show documentation
This project contains some common utilities used in different projects from theMatchBox.
package com.thematchbox.db;
/* Copyright 2015 theMatchBox
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import com.mongodb.DB;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSFile;
import com.mongodb.gridfs.GridFSInputFile;
import org.bson.types.ObjectId;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class MongoDBConnection {
public final DB db;
private final GridFS gridFS;
protected MongoDBConnection(DB db) {
this.db = db;
gridFS = new GridFS(db);
}
public GridFSDBFile findFile(ObjectId fileId) throws MongoDBException {
return gridFS.find(fileId);
}
public ObjectId writeFile(InputStream inputStream) throws MongoDBException {
GridFSInputFile file = gridFS.createFile(inputStream, true);
file.save();
return (ObjectId) file.getId();
}
public ObjectId writeImage(BufferedImage image, String format) throws MongoDBException {
try {
GridFSInputFile file = gridFS.createFile();
try (OutputStream outputStream = file.getOutputStream()) {
ImageIO.write(image, format, outputStream);
}
return (ObjectId) file.getId();
} catch (IOException e) {
throw new MongoDBException(e.getMessage(), e);
}
}
public void deleteFile(ObjectId id) throws MongoDBException {
gridFS.remove(id);
}
}