import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.bson.Document; import com.mongodb.MongoClient; import com.mongodb.MongoCredential; import com.mongodb.ServerAddress; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; public class MongoDAO { private static final String SERVER_URL = ""; private static final String USER = ""; private static final String PASSWORD = ""; private static final String DATABASE = ""; private static final String COLLECTION = ""; private static final String FSCOLLECTION = ""; private MongoCredential credential = MongoCredential.createCredential(USER, database, PASSWORD.toCharArray()); private MongoClient client; public void create(Document document) throws Exception { getCollection().insertOne(document); } public List read(Document filter) throws Exception { final List result = new ArrayList(); FindIterable iterable = getCollection().find(filter); iterable.forEach(new Block() { @Override public void apply(final Document document) { result.add(document); } }); return result; } public void update(Document filter, Document update) throws Exception { getCollection().updateMany(filter, update); } public void updateOne(Document filter, Document update) throws Exception { getCollection().updateOne(filter, update); } public void delete(Document filter) throws Exception { getCollection().deleteMany(filter); } public void deleteOne(Document filter) throws Exception { getCollection().deleteOne(filter); } public InputStream getStream(String id) throws Exception { @SuppressWarnings("deprecation") GridFS gfsPhoto = new GridFS(getClient().getDB(FSCOLLECTION)); GridFSDBFile file = gfsPhoto.findOne(new ObjectId(id)); if (file == null) { return null; } else { return file.getInputStream(); } } private MongoCollection getCollection() throws Exception { MongoDatabase database = getDatabase(); MongoCollection collection = database.getCollection(MongoDAO.COLLECTION); return collection; } private MongoDatabase getDatabase() throws Exception { MongoDatabase database = getClient().getDatabase(MongoDAO.DATABASE); return database; } private MongoClient getClient() throws Exception { if (client == null) { client = new MongoClient(new ServerAddress(SERVER_URL), Arrays.asList(credential)); } return client; } }