3 import java.util.Collection;
6 import java.util.function.Function;
7 import java.util.stream.Collectors;
8 import java.util.stream.Stream;
9 import java.util.stream.StreamSupport;
11 import org.bson.Document;
12 import org.junit.rules.ExternalResource;
14 import com.mongodb.MongoClient;
15 import com.mongodb.client.MongoCollection;
16 import com.mongodb.client.MongoDatabase;
18 import dst.ass1.doc.impl.DocumentServiceFactory;
19 import dst.ass1.jpa.util.Constants;
21 // DO NOT MODIFY THIS CLASS.
24 * The MongoService class is used as a JUnit rule, that fulfills the same tasks as the ORMService in ass1-jpa, and works
27 public class MongoService extends ExternalResource {
29 private IDocumentTestData testData;
30 private boolean insertTestData;
31 private boolean clearTestData;
33 private MongoClient mongoClient;
34 private MongoDatabase mongoDatabase;
36 private IDocumentServiceFactory documentServiceFactory;
37 private IDocumentRepository documentRepository;
38 private IDocumentQuery documentQuery;
40 public MongoService() {
41 this(null, false, true);
44 public MongoService(IDocumentTestData testData) {
45 this(testData, true, true);
48 public MongoService(IDocumentTestData testData, boolean insertTestData, boolean clearTestData) {
49 this.testData = testData;
50 this.insertTestData = insertTestData;
51 this.clearTestData = clearTestData;
54 public MongoClient getMongoClient() {
58 public MongoDatabase getMongoDatabase() {
62 public IDocumentServiceFactory getDocumentServiceFactory() {
63 return documentServiceFactory;
66 public IDocumentRepository getDocumentRepository() {
67 return documentRepository;
70 public IDocumentQuery getDocumentQuery() {
75 protected void before() throws Throwable {
78 if (insertTestData && testData != null) {
84 protected void after() {
94 private void setUpMongo() {
95 mongoClient = new MongoClient("127.0.0.1");
96 mongoDatabase = mongoClient.getDatabase(Constants.MONGO_DB_NAME);
98 documentServiceFactory = new DocumentServiceFactory();
99 documentRepository = documentServiceFactory.createDocumentRepository();
101 if (documentRepository == null) {
102 throw new IllegalStateException("DocumentRepository returned from factory is null");
105 documentQuery = documentServiceFactory.createDocumentQuery(mongoDatabase);
108 private void tearDownMongo() {
112 private void insertData(IDocumentTestData testData) throws Exception {
113 testData.insertTestData(getMongoDatabase());
116 private void clearData() {
117 getMongoDatabase().drop();
120 public static Stream<Document> stream(MongoCollection<Document> collection) {
121 return StreamSupport.stream(collection.find().spliterator(), false);
124 public static <T> Map<T, Document> idMap(MongoCollection<Document> collection, Function<Document, T> idFunction) {
125 return stream(collection).collect(Collectors.toMap(idFunction, Function.identity()));