Subversion Repositories SmartDukaan

Rev

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