Subversion Repositories SmartDukaan

Rev

Rev 35527 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
21723 ashik.ali 1
package com.spice.profitmandi.dao.repository.dtr;
21545 ashik.ali 2
 
22097 kshitij.so 3
import com.google.gson.Gson;
4
import com.google.gson.reflect.TypeToken;
32482 amit.gupta 5
import com.mongodb.*;
23793 tejbeer 6
import com.mongodb.client.AggregateIterable;
7
import com.mongodb.client.MongoCollection;
8
import com.mongodb.client.MongoDatabase;
21545 ashik.ali 9
import com.mongodb.util.JSON;
24011 tejbeer 10
import com.spice.profitmandi.dao.entity.dtr.NotificationCampaigns;
25380 amit.gupta 11
import com.spice.profitmandi.dao.model.ContentPojo;
22097 kshitij.so 12
import com.spice.profitmandi.dao.model.FofoForm;
22496 amit.gupta 13
import com.spice.profitmandi.dao.model.RetailerFofoInterest;
32482 amit.gupta 14
import org.apache.logging.log4j.LogManager;
15
import org.apache.logging.log4j.Logger;
16
import org.bson.Document;
17
import org.json.JSONObject;
21545 ashik.ali 18
 
32482 amit.gupta 19
import java.lang.reflect.Type;
35236 amit 20
import java.util.ArrayList;
21
import java.util.Arrays;
36437 aman 22
import java.util.HashMap;
35236 amit 23
import java.util.List;
24
import java.util.Map;
32482 amit.gupta 25
 
21545 ashik.ali 26
public class Mongo {
22384 amit.gupta 27
 
32482 amit.gupta 28
    private static final Logger LOGGER = LogManager.getLogger(Mongo.class);
21545 ashik.ali 29
 
32482 amit.gupta 30
    private static final String CONTENT = "CONTENT";
35390 amit 31
    private volatile boolean closed = false;
32482 amit.gupta 32
    private static final String SITE_CONTENT = "siteContent";
33
    private static final String CATALOG_DB = "Catalog";
34
    private static final String MASTER_DATA = "MasterData";
35
    private static final String FOFO_DB = "Fofo";
36
    private static final String FOFO_BRANDS = "brands";
37
    private static final String PROFITMANDI_BANNERS = "banners";
38
    private static final String RETAILER_FOFO_INTEREST = "RetailerFofoInterest";
39
    private static final String FOFO_FORM_COLLECTION = "RegistrationForm";
40
    private static final String NOTIFICATION_CAMPAIGNS = "notificationcampaigns";
41
    private static final String USER_DB = "User";
42
    private static final int MONGO_PORT = 27017;
25380 amit.gupta 43
 
32482 amit.gupta 44
    private static final Gson gson = new Gson();
22165 amit.gupta 45
 
32482 amit.gupta 46
    private MongoClient mongoClient;
47
    private MongoClient contentMongoClient;
24995 amit.gupta 48
 
32482 amit.gupta 49
    public Mongo(String mongoHost, String contentMongoHost) {
50
        try {
51
            LOGGER.info("mongoHost => {}, contentMongoHost {} ", mongoHost, contentMongoHost);
52
            mongoClient = new MongoClient(mongoHost, MONGO_PORT);
53
            contentMongoClient = new MongoClient(contentMongoHost, MONGO_PORT);
54
        } catch (Exception e) {
55
            e.printStackTrace();
56
        }
57
    }
22162 amit.gupta 58
 
32482 amit.gupta 59
    public ContentPojo getEntityById(long id) throws Exception {
60
        DB db = contentMongoClient.getDB(CONTENT);
61
        DBCollection collection = db.getCollection(SITE_CONTENT);
62
        BasicDBObject obj = new BasicDBObject();
63
        obj.append("_id", id);
64
        DBObject result = collection.findOne(obj);
65
        if (result == null) {
66
            throw new Exception();
67
        }
68
        //LOGGER.info(result.toMap());
69
        ContentPojo cp = gson.fromJson(new BasicDBObject(result.toMap()).toJson(), ContentPojo.class);
70
        if (cp.getDefaultImageUrl() != null) {
71
            cp.setDefaultImageUrl(cp.getDefaultImageUrl().replaceAll("saholic", "smartdukaan"));
72
        }
24031 amit.gupta 73
 
32482 amit.gupta 74
        //LOGGER.info("cp" + cp);
29351 tejbeer 75
 
32482 amit.gupta 76
        return cp;
77
    }
29351 tejbeer 78
 
36437 aman 79
    public Map<Long, ContentPojo> getEntitiesByIds(List<Long> ids) {
80
        Map<Long, ContentPojo> result = new HashMap<>();
81
        if (ids == null || ids.isEmpty()) return result;
82
        DB db = contentMongoClient.getDB(CONTENT);
83
        DBCollection collection = db.getCollection(SITE_CONTENT);
84
        BasicDBObject query = new BasicDBObject("_id", new BasicDBObject("$in", ids));
85
        DBCursor cursor = collection.find(query);
86
        while (cursor.hasNext()) {
87
            DBObject doc = cursor.next();
88
            try {
89
                long docId = ((Number) doc.get("_id")).longValue();
90
                ContentPojo cp = gson.fromJson(new BasicDBObject(doc.toMap()).toJson(), ContentPojo.class);
91
                if (cp.getDefaultImageUrl() != null) {
92
                    cp.setDefaultImageUrl(cp.getDefaultImageUrl().replaceAll("saholic", "smartdukaan"));
93
                }
94
                result.put(docId, cp);
95
            } catch (Exception e) {
96
                // skip malformed entries
97
            }
98
        }
99
        cursor.close();
100
        return result;
101
    }
102
 
32482 amit.gupta 103
    public ContentPojo getEntityByName(String name) throws Exception {
104
        //LOGGER.info("Name --- {}", name);
105
        DB db = contentMongoClient.getDB(CONTENT);
106
        DBCollection collection = db.getCollection(SITE_CONTENT);
107
        BasicDBObject obj = new BasicDBObject();
108
        obj.append("title", name);
109
        DBObject result = collection.findOne();
110
        if (result == null) {
111
            throw new Exception();
112
        }
113
        return gson.fromJson(new BasicDBObject(result.toMap()).toJson(), ContentPojo.class);
114
    }
22165 amit.gupta 115
 
32482 amit.gupta 116
    public void persistEntity(ContentPojo contentPojo) {
117
        DB db = contentMongoClient.getDB(CONTENT);
118
        DBCollection collection = db.getCollection(SITE_CONTENT);
119
        insertOrUpdateById(collection, contentPojo.getId(), contentPojo);
22384 amit.gupta 120
 
32482 amit.gupta 121
    }
25380 amit.gupta 122
 
32482 amit.gupta 123
    private static <T> void insertOrUpdateById(DBCollection collection, long id, T obj) {
124
        DBObject dbo = BasicDBObject.parse(gson.toJson(obj));
35527 ranu 125
        LOGGER.info("dbo {}", dbo);
32482 amit.gupta 126
        dbo.put("_id", id);
35527 ranu 127
        Object result = collection.update(new BasicDBObject("_id", id), dbo, true, false);
128
        LOGGER.info("result mongo {}", result);
32482 amit.gupta 129
    }
25380 amit.gupta 130
 
32482 amit.gupta 131
    public JSONObject getItemsByBundleId(long bundleId) throws Exception {
132
        DB db = mongoClient.getDB(CATALOG_DB);
133
        DBCollection collection = db.getCollection(MASTER_DATA);
134
        BasicDBObject obj = new BasicDBObject();
135
        BasicDBObject in_query = new BasicDBObject();
136
        obj.append("skuBundleId", bundleId);
137
        in_query.append("$in", new int[]{1, 2, 3, 4, 5, 6, 7});
138
        obj.append("source_id", in_query);
139
        DBObject result = collection.findOne(obj);
140
        if (result == null) {
141
            throw new Exception();
142
        }
143
        return new JSONObject(JSON.serialize(result));
144
    }
25380 amit.gupta 145
 
32482 amit.gupta 146
    public JSONObject getItemByID(long id) throws Exception {
147
        DB db = mongoClient.getDB(CATALOG_DB);
148
        DBCollection collection = db.getCollection(MASTER_DATA);
149
        BasicDBObject obj = new BasicDBObject();
150
        obj.append("_id", id);
151
        DBObject result = collection.findOne(obj);
152
        if (result == null) {
153
            throw new Exception();
154
        }
155
        return new JSONObject(JSON.serialize(result));
156
    }
22165 amit.gupta 157
 
32482 amit.gupta 158
    public void persistFofoRegInfo(FofoForm ff) {
159
        DB db = mongoClient.getDB(FOFO_DB);
160
        DBCollection collection = db.getCollection(FOFO_FORM_COLLECTION);
161
        if (ff.get_id() == 0) {
162
            BasicDBObject orderBy = new BasicDBObject();
163
            orderBy.put("_id", -1);
164
            DBCursor cursor = collection.find().sort(orderBy).limit(1);
165
            long id = 1l;
166
            while (cursor.hasNext()) {
167
                FofoForm existingFofo = gson.fromJson(cursor.next().toString(), FofoForm.class);
168
                id = existingFofo.get_id() + 1;
169
            }
170
            ff.set_id(id);
171
        }
172
        DBObject dbObject = (DBObject) JSON.parse(gson.toJson(ff));
173
        collection.save(dbObject);
174
    }
22165 amit.gupta 175
 
32482 amit.gupta 176
    public List<FofoForm> getFofoForms(int offset, int limit) {
177
        List<FofoForm> ffList = new ArrayList<FofoForm>();
178
        DB db = mongoClient.getDB(FOFO_DB);
179
        DBCollection collection = db.getCollection(FOFO_FORM_COLLECTION);
180
        BasicDBObject orderBy = new BasicDBObject();
181
        orderBy.put("_id", -1);
182
        DBCursor dbc = collection.find().sort(orderBy).limit(limit).skip(offset);
183
        while (dbc.hasNext()) {
184
            ffList.add(convertJSONToPojo(dbc.next().toString()));
185
        }
186
        return ffList;
187
    }
22165 amit.gupta 188
 
32482 amit.gupta 189
    public String getFofoFormJsonStringByFofoId(int fofoId) {
190
        DB db = mongoClient.getDB(FOFO_DB);
191
        BasicDBObject filter = new BasicDBObject();
192
        filter.append("_id", fofoId);
193
        DBCollection collection = db.getCollection(FOFO_FORM_COLLECTION);
194
        DBObject fofoDbOject = collection.findOne(filter);
195
        if (fofoDbOject != null) {
196
            return fofoDbOject.toString();
197
        } else {
198
            return null;
199
        }
200
    }
22165 amit.gupta 201
 
32482 amit.gupta 202
    public String getFofoFormJsonStringByEmail(String email) {
203
        DB db = mongoClient.getDB(FOFO_DB);
204
        BasicDBObject filter = new BasicDBObject();
205
        filter.append("registeredEmail1", email);
206
        DBCollection collection = db.getCollection(FOFO_FORM_COLLECTION);
207
        DBObject fofoDbOject = collection.findOne(filter);
208
        if (fofoDbOject != null) {
209
            return fofoDbOject.toString();
210
        } else {
211
            return null;
212
        }
213
    }
22165 amit.gupta 214
 
32482 amit.gupta 215
    public String getFofoFormsJsonString() {
216
        DB db = mongoClient.getDB(FOFO_DB);
217
        DBCollection collection = db.getCollection(FOFO_FORM_COLLECTION);
218
        DBCursor cursor = collection.find();
219
        StringBuilder fofoFormsJsonString = new StringBuilder();
220
        fofoFormsJsonString.append("[");
221
        while (cursor.hasNext()) {
222
            fofoFormsJsonString.append(cursor.next().toString());
223
            if (cursor.hasNext()) {
224
                fofoFormsJsonString.append(",");
225
            }
226
        }
227
        fofoFormsJsonString.append("]");
228
        return fofoFormsJsonString.toString();
229
    }
22165 amit.gupta 230
 
32482 amit.gupta 231
    public FofoForm getFofoForm(int fofoId) {
232
        String fofoFormJsonString = getFofoFormJsonStringByFofoId(fofoId);
233
        System.out.println(fofoFormJsonString);
234
        return new Gson().fromJson(fofoFormJsonString, FofoForm.class);
235
        // return convertJSONToPojo(fofoDbOject.toString());
236
    }
22165 amit.gupta 237
 
32482 amit.gupta 238
    public FofoForm getFofoForm(String email) {
239
        String fofoFormJsonString = getFofoFormJsonStringByEmail(email);
240
        System.out.println(fofoFormJsonString);
241
        return new Gson().fromJson(fofoFormJsonString, FofoForm.class);
242
        // return convertJSONToPojo(fofoDbOject.toString());
243
    }
22165 amit.gupta 244
 
32482 amit.gupta 245
    private static FofoForm convertJSONToPojo(String json) {
21545 ashik.ali 246
 
32482 amit.gupta 247
        Type type = new TypeToken<FofoForm>() {
248
        }.getType();
22097 kshitij.so 249
 
32482 amit.gupta 250
        return new Gson().fromJson(json, type);
22097 kshitij.so 251
 
32482 amit.gupta 252
    }
22165 amit.gupta 253
 
32482 amit.gupta 254
    public void updateColumnsById(Map<String, Integer> map, int fofoId) {
255
        DB db = mongoClient.getDB(FOFO_DB);
256
        BasicDBObject filter = new BasicDBObject();
257
        filter.append("_id", fofoId);
258
        DBCollection collection = db.getCollection(FOFO_FORM_COLLECTION);
259
        BasicDBObject updateFields = new BasicDBObject();
260
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
261
            updateFields.append(entry.getKey(), entry.getValue());
262
        }
263
        BasicDBObject newDocument = new BasicDBObject();
264
        newDocument.append("$set", updateFields);
265
        collection.update(filter, newDocument);
266
    }
22165 amit.gupta 267
 
32482 amit.gupta 268
    public List<DBObject> getBrandsToDisplay(int categoryId) {
269
        DB db = mongoClient.getDB(FOFO_DB);
270
        BasicDBObject filter = new BasicDBObject();
271
        filter.append("active", true);
272
        if (categoryId != 0) {
273
            filter.append("categoryId", categoryId);
274
        }
275
        return db.getCollection(FOFO_BRANDS).find(filter).toArray();
276
    }
24031 amit.gupta 277
 
32482 amit.gupta 278
    public List<DBObject> getAllBrandsToDisplay(int categoryId) {
279
        DB db = mongoClient.getDB(FOFO_DB);
280
        BasicDBObject filter = new BasicDBObject();
281
        if (categoryId != 0) {
282
            filter.append("categoryId", categoryId);
283
        }
284
        return db.getCollection(FOFO_BRANDS).find(filter).toArray();
285
    }
26343 tejbeer 286
 
32482 amit.gupta 287
    public List<DBObject> getBannersByType(String bannerType) {
288
        DB db = mongoClient.getDB(FOFO_DB);
289
        BasicDBObject filter = new BasicDBObject();
290
        filter.append("type", bannerType);
291
        BasicDBObject orderBy = new BasicDBObject();
292
        orderBy.put("rank", 1);
293
        return db.getCollection(PROFITMANDI_BANNERS).find(filter).sort(orderBy).toArray();
294
    }
24031 amit.gupta 295
 
32482 amit.gupta 296
    @SuppressWarnings("unchecked")
297
    public List<Document> getSubcategoriesToDisplay() {
298
        MongoDatabase db = mongoClient.getDatabase("Catalog");
299
        System.out.println("Connection to MongoDB database successfully");
300
        MongoCollection<Document> collection = db.getCollection("Deals");
23793 tejbeer 301
 
32482 amit.gupta 302
        Document object = new Document().append("$match", new Document().append("category_id", 6).append("showDeal", 1)
303
                .append("dealRankPoints", new Document("$gt", 0)));
304
        Document ob = new Document("$group",
305
                new Document().append("_id",
306
                                new Document().append("subCategoryId", "$subCategoryId").append("subCategory", "$subCategory"))
307
                        .append("count", new Document("$sum", 1)));
308
        List<Document> pipeline = Arrays.asList(object, ob);
309
        AggregateIterable<Document> cursor = collection.aggregate(pipeline);
24031 amit.gupta 310
 
32482 amit.gupta 311
        List<Document> resultDocuments = new ArrayList<>();
312
        for (Document dbo : cursor) {
313
            System.out.println(dbo.toString());
314
            LOGGER.info("categories" + dbo.toString());
315
            resultDocuments.add(dbo);
316
        }
317
        return resultDocuments;
318
    }
23793 tejbeer 319
 
32482 amit.gupta 320
    public boolean saveRetailerInterestOnFofo(RetailerFofoInterest retailerInterest) {
321
        DB db = mongoClient.getDB(FOFO_DB);
322
        Gson gs = new Gson();
323
        DBCollection fofoInterestCollection = db.getCollection(RETAILER_FOFO_INTEREST);
324
        DBObject dbObject = (DBObject) JSON.parse(gs.toJson(retailerInterest));
325
        fofoInterestCollection.save(dbObject);
326
        return true;
327
    }
23793 tejbeer 328
 
32482 amit.gupta 329
    public boolean hasRetailerShownInterest(int userId) {
330
        DB db = mongoClient.getDB(FOFO_DB);
331
        BasicDBObject filter = new BasicDBObject();
332
        filter.append("userId", userId);
333
        DBCollection fofoInterestCollection = db.getCollection(RETAILER_FOFO_INTEREST);
334
        return fofoInterestCollection.findOne(filter) != null;
335
    }
23793 tejbeer 336
 
32482 amit.gupta 337
    public void persistNotificationCmpInfo(NotificationCampaigns ff) {
338
        DB db = mongoClient.getDB(USER_DB);
339
        DBCollection collection = db.getCollection(NOTIFICATION_CAMPAIGNS);
340
        if (ff.get_id() == 0) {
341
            BasicDBObject orderBy = new BasicDBObject();
342
            orderBy.put("_id", -1);
343
            DBCursor cursor = collection.find().sort(orderBy).limit(1);
344
            long id = 1l;
345
            while (cursor.hasNext()) {
346
                Gson gson = new Gson();
347
                NotificationCampaigns existingFofo = gson.fromJson(cursor.next().toString(),
348
                        NotificationCampaigns.class);
349
                id = existingFofo.get_id() + 1;
350
            }
351
            ff.set_id(id);
352
        }
353
        Gson gs = new Gson();
354
        DBObject dbObject = (DBObject) JSON.parse(gs.toJson(ff));
355
        collection.save(dbObject);
356
    }
24031 amit.gupta 357
 
35390 amit 358
    /**
359
     * Close MongoDB connections to prevent memory leaks on shutdown
360
     */
361
    public void close() {
362
        if (closed) {
363
            return;
364
        }
365
        closed = true;
366
        LOGGER.info("Closing MongoDB connections...");
367
        try {
368
            if (mongoClient != null) {
369
                mongoClient.close();
370
                LOGGER.info("Main MongoClient closed");
371
            }
372
        } catch (Exception e) {
373
            LOGGER.error("Error closing mongoClient", e);
374
        }
375
        try {
376
            if (contentMongoClient != null) {
377
                contentMongoClient.close();
378
                LOGGER.info("Content MongoClient closed");
379
            }
380
        } catch (Exception e) {
381
            LOGGER.error("Error closing contentMongoClient", e);
382
        }
383
    }
384
 
21545 ashik.ali 385
}