Subversion Repositories SmartDukaan

Rev

Rev 35236 | Rev 35527 | 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));
100
        dbo.put("_id", id);
101
        collection.update(new BasicDBObject("_id", id), dbo, true, false);
102
    }
25380 amit.gupta 103
 
32482 amit.gupta 104
    public JSONObject getItemsByBundleId(long bundleId) throws Exception {
105
        DB db = mongoClient.getDB(CATALOG_DB);
106
        DBCollection collection = db.getCollection(MASTER_DATA);
107
        BasicDBObject obj = new BasicDBObject();
108
        BasicDBObject in_query = new BasicDBObject();
109
        obj.append("skuBundleId", bundleId);
110
        in_query.append("$in", new int[]{1, 2, 3, 4, 5, 6, 7});
111
        obj.append("source_id", in_query);
112
        DBObject result = collection.findOne(obj);
113
        if (result == null) {
114
            throw new Exception();
115
        }
116
        return new JSONObject(JSON.serialize(result));
117
    }
25380 amit.gupta 118
 
32482 amit.gupta 119
    public JSONObject getItemByID(long id) throws Exception {
120
        DB db = mongoClient.getDB(CATALOG_DB);
121
        DBCollection collection = db.getCollection(MASTER_DATA);
122
        BasicDBObject obj = new BasicDBObject();
123
        obj.append("_id", id);
124
        DBObject result = collection.findOne(obj);
125
        if (result == null) {
126
            throw new Exception();
127
        }
128
        return new JSONObject(JSON.serialize(result));
129
    }
22165 amit.gupta 130
 
32482 amit.gupta 131
    public void persistFofoRegInfo(FofoForm ff) {
132
        DB db = mongoClient.getDB(FOFO_DB);
133
        DBCollection collection = db.getCollection(FOFO_FORM_COLLECTION);
134
        if (ff.get_id() == 0) {
135
            BasicDBObject orderBy = new BasicDBObject();
136
            orderBy.put("_id", -1);
137
            DBCursor cursor = collection.find().sort(orderBy).limit(1);
138
            long id = 1l;
139
            while (cursor.hasNext()) {
140
                FofoForm existingFofo = gson.fromJson(cursor.next().toString(), FofoForm.class);
141
                id = existingFofo.get_id() + 1;
142
            }
143
            ff.set_id(id);
144
        }
145
        DBObject dbObject = (DBObject) JSON.parse(gson.toJson(ff));
146
        collection.save(dbObject);
147
    }
22165 amit.gupta 148
 
32482 amit.gupta 149
    public List<FofoForm> getFofoForms(int offset, int limit) {
150
        List<FofoForm> ffList = new ArrayList<FofoForm>();
151
        DB db = mongoClient.getDB(FOFO_DB);
152
        DBCollection collection = db.getCollection(FOFO_FORM_COLLECTION);
153
        BasicDBObject orderBy = new BasicDBObject();
154
        orderBy.put("_id", -1);
155
        DBCursor dbc = collection.find().sort(orderBy).limit(limit).skip(offset);
156
        while (dbc.hasNext()) {
157
            ffList.add(convertJSONToPojo(dbc.next().toString()));
158
        }
159
        return ffList;
160
    }
22165 amit.gupta 161
 
32482 amit.gupta 162
    public String getFofoFormJsonStringByFofoId(int fofoId) {
163
        DB db = mongoClient.getDB(FOFO_DB);
164
        BasicDBObject filter = new BasicDBObject();
165
        filter.append("_id", fofoId);
166
        DBCollection collection = db.getCollection(FOFO_FORM_COLLECTION);
167
        DBObject fofoDbOject = collection.findOne(filter);
168
        if (fofoDbOject != null) {
169
            return fofoDbOject.toString();
170
        } else {
171
            return null;
172
        }
173
    }
22165 amit.gupta 174
 
32482 amit.gupta 175
    public String getFofoFormJsonStringByEmail(String email) {
176
        DB db = mongoClient.getDB(FOFO_DB);
177
        BasicDBObject filter = new BasicDBObject();
178
        filter.append("registeredEmail1", email);
179
        DBCollection collection = db.getCollection(FOFO_FORM_COLLECTION);
180
        DBObject fofoDbOject = collection.findOne(filter);
181
        if (fofoDbOject != null) {
182
            return fofoDbOject.toString();
183
        } else {
184
            return null;
185
        }
186
    }
22165 amit.gupta 187
 
32482 amit.gupta 188
    public String getFofoFormsJsonString() {
189
        DB db = mongoClient.getDB(FOFO_DB);
190
        DBCollection collection = db.getCollection(FOFO_FORM_COLLECTION);
191
        DBCursor cursor = collection.find();
192
        StringBuilder fofoFormsJsonString = new StringBuilder();
193
        fofoFormsJsonString.append("[");
194
        while (cursor.hasNext()) {
195
            fofoFormsJsonString.append(cursor.next().toString());
196
            if (cursor.hasNext()) {
197
                fofoFormsJsonString.append(",");
198
            }
199
        }
200
        fofoFormsJsonString.append("]");
201
        return fofoFormsJsonString.toString();
202
    }
22165 amit.gupta 203
 
32482 amit.gupta 204
    public FofoForm getFofoForm(int fofoId) {
205
        String fofoFormJsonString = getFofoFormJsonStringByFofoId(fofoId);
206
        System.out.println(fofoFormJsonString);
207
        return new Gson().fromJson(fofoFormJsonString, FofoForm.class);
208
        // return convertJSONToPojo(fofoDbOject.toString());
209
    }
22165 amit.gupta 210
 
32482 amit.gupta 211
    public FofoForm getFofoForm(String email) {
212
        String fofoFormJsonString = getFofoFormJsonStringByEmail(email);
213
        System.out.println(fofoFormJsonString);
214
        return new Gson().fromJson(fofoFormJsonString, FofoForm.class);
215
        // return convertJSONToPojo(fofoDbOject.toString());
216
    }
22165 amit.gupta 217
 
32482 amit.gupta 218
    private static FofoForm convertJSONToPojo(String json) {
21545 ashik.ali 219
 
32482 amit.gupta 220
        Type type = new TypeToken<FofoForm>() {
221
        }.getType();
22097 kshitij.so 222
 
32482 amit.gupta 223
        return new Gson().fromJson(json, type);
22097 kshitij.so 224
 
32482 amit.gupta 225
    }
22165 amit.gupta 226
 
32482 amit.gupta 227
    public void updateColumnsById(Map<String, Integer> map, int fofoId) {
228
        DB db = mongoClient.getDB(FOFO_DB);
229
        BasicDBObject filter = new BasicDBObject();
230
        filter.append("_id", fofoId);
231
        DBCollection collection = db.getCollection(FOFO_FORM_COLLECTION);
232
        BasicDBObject updateFields = new BasicDBObject();
233
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
234
            updateFields.append(entry.getKey(), entry.getValue());
235
        }
236
        BasicDBObject newDocument = new BasicDBObject();
237
        newDocument.append("$set", updateFields);
238
        collection.update(filter, newDocument);
239
    }
22165 amit.gupta 240
 
32482 amit.gupta 241
    public List<DBObject> getBrandsToDisplay(int categoryId) {
242
        DB db = mongoClient.getDB(FOFO_DB);
243
        BasicDBObject filter = new BasicDBObject();
244
        filter.append("active", true);
245
        if (categoryId != 0) {
246
            filter.append("categoryId", categoryId);
247
        }
248
        return db.getCollection(FOFO_BRANDS).find(filter).toArray();
249
    }
24031 amit.gupta 250
 
32482 amit.gupta 251
    public List<DBObject> getAllBrandsToDisplay(int categoryId) {
252
        DB db = mongoClient.getDB(FOFO_DB);
253
        BasicDBObject filter = new BasicDBObject();
254
        if (categoryId != 0) {
255
            filter.append("categoryId", categoryId);
256
        }
257
        return db.getCollection(FOFO_BRANDS).find(filter).toArray();
258
    }
26343 tejbeer 259
 
32482 amit.gupta 260
    public List<DBObject> getBannersByType(String bannerType) {
261
        DB db = mongoClient.getDB(FOFO_DB);
262
        BasicDBObject filter = new BasicDBObject();
263
        filter.append("type", bannerType);
264
        BasicDBObject orderBy = new BasicDBObject();
265
        orderBy.put("rank", 1);
266
        return db.getCollection(PROFITMANDI_BANNERS).find(filter).sort(orderBy).toArray();
267
    }
24031 amit.gupta 268
 
32482 amit.gupta 269
    @SuppressWarnings("unchecked")
270
    public List<Document> getSubcategoriesToDisplay() {
271
        MongoDatabase db = mongoClient.getDatabase("Catalog");
272
        System.out.println("Connection to MongoDB database successfully");
273
        MongoCollection<Document> collection = db.getCollection("Deals");
23793 tejbeer 274
 
32482 amit.gupta 275
        Document object = new Document().append("$match", new Document().append("category_id", 6).append("showDeal", 1)
276
                .append("dealRankPoints", new Document("$gt", 0)));
277
        Document ob = new Document("$group",
278
                new Document().append("_id",
279
                                new Document().append("subCategoryId", "$subCategoryId").append("subCategory", "$subCategory"))
280
                        .append("count", new Document("$sum", 1)));
281
        List<Document> pipeline = Arrays.asList(object, ob);
282
        AggregateIterable<Document> cursor = collection.aggregate(pipeline);
24031 amit.gupta 283
 
32482 amit.gupta 284
        List<Document> resultDocuments = new ArrayList<>();
285
        for (Document dbo : cursor) {
286
            System.out.println(dbo.toString());
287
            LOGGER.info("categories" + dbo.toString());
288
            resultDocuments.add(dbo);
289
        }
290
        return resultDocuments;
291
    }
23793 tejbeer 292
 
32482 amit.gupta 293
    public boolean saveRetailerInterestOnFofo(RetailerFofoInterest retailerInterest) {
294
        DB db = mongoClient.getDB(FOFO_DB);
295
        Gson gs = new Gson();
296
        DBCollection fofoInterestCollection = db.getCollection(RETAILER_FOFO_INTEREST);
297
        DBObject dbObject = (DBObject) JSON.parse(gs.toJson(retailerInterest));
298
        fofoInterestCollection.save(dbObject);
299
        return true;
300
    }
23793 tejbeer 301
 
32482 amit.gupta 302
    public boolean hasRetailerShownInterest(int userId) {
303
        DB db = mongoClient.getDB(FOFO_DB);
304
        BasicDBObject filter = new BasicDBObject();
305
        filter.append("userId", userId);
306
        DBCollection fofoInterestCollection = db.getCollection(RETAILER_FOFO_INTEREST);
307
        return fofoInterestCollection.findOne(filter) != null;
308
    }
23793 tejbeer 309
 
32482 amit.gupta 310
    public void persistNotificationCmpInfo(NotificationCampaigns ff) {
311
        DB db = mongoClient.getDB(USER_DB);
312
        DBCollection collection = db.getCollection(NOTIFICATION_CAMPAIGNS);
313
        if (ff.get_id() == 0) {
314
            BasicDBObject orderBy = new BasicDBObject();
315
            orderBy.put("_id", -1);
316
            DBCursor cursor = collection.find().sort(orderBy).limit(1);
317
            long id = 1l;
318
            while (cursor.hasNext()) {
319
                Gson gson = new Gson();
320
                NotificationCampaigns existingFofo = gson.fromJson(cursor.next().toString(),
321
                        NotificationCampaigns.class);
322
                id = existingFofo.get_id() + 1;
323
            }
324
            ff.set_id(id);
325
        }
326
        Gson gs = new Gson();
327
        DBObject dbObject = (DBObject) JSON.parse(gs.toJson(ff));
328
        collection.save(dbObject);
329
    }
24031 amit.gupta 330
 
35390 amit 331
    /**
332
     * Close MongoDB connections to prevent memory leaks on shutdown
333
     */
334
    public void close() {
335
        if (closed) {
336
            return;
337
        }
338
        closed = true;
339
        LOGGER.info("Closing MongoDB connections...");
340
        try {
341
            if (mongoClient != null) {
342
                mongoClient.close();
343
                LOGGER.info("Main MongoClient closed");
344
            }
345
        } catch (Exception e) {
346
            LOGGER.error("Error closing mongoClient", e);
347
        }
348
        try {
349
            if (contentMongoClient != null) {
350
                contentMongoClient.close();
351
                LOGGER.info("Content MongoClient closed");
352
            }
353
        } catch (Exception e) {
354
            LOGGER.error("Error closing contentMongoClient", e);
355
        }
356
    }
357
 
21545 ashik.ali 358
}