Subversion Repositories SmartDukaan

Rev

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