Subversion Repositories SmartDukaan

Rev

Rev 35390 | View as "text/plain" | Blame | Compare with Previous | Last modification | View Log | RSS feed

package com.spice.profitmandi.dao.repository.dtr;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mongodb.*;
import com.mongodb.client.AggregateIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.util.JSON;
import com.spice.profitmandi.dao.entity.dtr.NotificationCampaigns;
import com.spice.profitmandi.dao.model.ContentPojo;
import com.spice.profitmandi.dao.model.FofoForm;
import com.spice.profitmandi.dao.model.RetailerFofoInterest;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bson.Document;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class Mongo {

    private static final Logger LOGGER = LogManager.getLogger(Mongo.class);

    private static final String CONTENT = "CONTENT";
    private volatile boolean closed = false;
    private static final String SITE_CONTENT = "siteContent";
    private static final String CATALOG_DB = "Catalog";
    private static final String MASTER_DATA = "MasterData";
    private static final String FOFO_DB = "Fofo";
    private static final String FOFO_BRANDS = "brands";
    private static final String PROFITMANDI_BANNERS = "banners";
    private static final String RETAILER_FOFO_INTEREST = "RetailerFofoInterest";
    private static final String FOFO_FORM_COLLECTION = "RegistrationForm";
    private static final String NOTIFICATION_CAMPAIGNS = "notificationcampaigns";
    private static final String USER_DB = "User";
    private static final int MONGO_PORT = 27017;

    private static final Gson gson = new Gson();

    private MongoClient mongoClient;
    private MongoClient contentMongoClient;

    public Mongo(String mongoHost, String contentMongoHost) {
        try {
            LOGGER.info("mongoHost => {}, contentMongoHost {} ", mongoHost, contentMongoHost);
            mongoClient = new MongoClient(mongoHost, MONGO_PORT);
            contentMongoClient = new MongoClient(contentMongoHost, MONGO_PORT);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public ContentPojo getEntityById(long id) throws Exception {
        DB db = contentMongoClient.getDB(CONTENT);
        DBCollection collection = db.getCollection(SITE_CONTENT);
        BasicDBObject obj = new BasicDBObject();
        obj.append("_id", id);
        DBObject result = collection.findOne(obj);
        if (result == null) {
            throw new Exception();
        }
        //LOGGER.info(result.toMap());
        ContentPojo cp = gson.fromJson(new BasicDBObject(result.toMap()).toJson(), ContentPojo.class);
        if (cp.getDefaultImageUrl() != null) {
            cp.setDefaultImageUrl(cp.getDefaultImageUrl().replaceAll("saholic", "smartdukaan"));
        }

        //LOGGER.info("cp" + cp);

        return cp;
    }

    public ContentPojo getEntityByName(String name) throws Exception {
        //LOGGER.info("Name --- {}", name);
        DB db = contentMongoClient.getDB(CONTENT);
        DBCollection collection = db.getCollection(SITE_CONTENT);
        BasicDBObject obj = new BasicDBObject();
        obj.append("title", name);
        DBObject result = collection.findOne();
        if (result == null) {
            throw new Exception();
        }
        return gson.fromJson(new BasicDBObject(result.toMap()).toJson(), ContentPojo.class);
    }

    public void persistEntity(ContentPojo contentPojo) {
        DB db = contentMongoClient.getDB(CONTENT);
        DBCollection collection = db.getCollection(SITE_CONTENT);
        insertOrUpdateById(collection, contentPojo.getId(), contentPojo);

    }

    private static <T> void insertOrUpdateById(DBCollection collection, long id, T obj) {
        DBObject dbo = BasicDBObject.parse(gson.toJson(obj));
        LOGGER.info("dbo {}", dbo);
        dbo.put("_id", id);
        Object result = collection.update(new BasicDBObject("_id", id), dbo, true, false);
        LOGGER.info("result mongo {}", result);
    }

    public JSONObject getItemsByBundleId(long bundleId) throws Exception {
        DB db = mongoClient.getDB(CATALOG_DB);
        DBCollection collection = db.getCollection(MASTER_DATA);
        BasicDBObject obj = new BasicDBObject();
        BasicDBObject in_query = new BasicDBObject();
        obj.append("skuBundleId", bundleId);
        in_query.append("$in", new int[]{1, 2, 3, 4, 5, 6, 7});
        obj.append("source_id", in_query);
        DBObject result = collection.findOne(obj);
        if (result == null) {
            throw new Exception();
        }
        return new JSONObject(JSON.serialize(result));
    }

    public JSONObject getItemByID(long id) throws Exception {
        DB db = mongoClient.getDB(CATALOG_DB);
        DBCollection collection = db.getCollection(MASTER_DATA);
        BasicDBObject obj = new BasicDBObject();
        obj.append("_id", id);
        DBObject result = collection.findOne(obj);
        if (result == null) {
            throw new Exception();
        }
        return new JSONObject(JSON.serialize(result));
    }

    public void persistFofoRegInfo(FofoForm ff) {
        DB db = mongoClient.getDB(FOFO_DB);
        DBCollection collection = db.getCollection(FOFO_FORM_COLLECTION);
        if (ff.get_id() == 0) {
            BasicDBObject orderBy = new BasicDBObject();
            orderBy.put("_id", -1);
            DBCursor cursor = collection.find().sort(orderBy).limit(1);
            long id = 1l;
            while (cursor.hasNext()) {
                FofoForm existingFofo = gson.fromJson(cursor.next().toString(), FofoForm.class);
                id = existingFofo.get_id() + 1;
            }
            ff.set_id(id);
        }
        DBObject dbObject = (DBObject) JSON.parse(gson.toJson(ff));
        collection.save(dbObject);
    }

    public List<FofoForm> getFofoForms(int offset, int limit) {
        List<FofoForm> ffList = new ArrayList<FofoForm>();
        DB db = mongoClient.getDB(FOFO_DB);
        DBCollection collection = db.getCollection(FOFO_FORM_COLLECTION);
        BasicDBObject orderBy = new BasicDBObject();
        orderBy.put("_id", -1);
        DBCursor dbc = collection.find().sort(orderBy).limit(limit).skip(offset);
        while (dbc.hasNext()) {
            ffList.add(convertJSONToPojo(dbc.next().toString()));
        }
        return ffList;
    }

    public String getFofoFormJsonStringByFofoId(int fofoId) {
        DB db = mongoClient.getDB(FOFO_DB);
        BasicDBObject filter = new BasicDBObject();
        filter.append("_id", fofoId);
        DBCollection collection = db.getCollection(FOFO_FORM_COLLECTION);
        DBObject fofoDbOject = collection.findOne(filter);
        if (fofoDbOject != null) {
            return fofoDbOject.toString();
        } else {
            return null;
        }
    }

    public String getFofoFormJsonStringByEmail(String email) {
        DB db = mongoClient.getDB(FOFO_DB);
        BasicDBObject filter = new BasicDBObject();
        filter.append("registeredEmail1", email);
        DBCollection collection = db.getCollection(FOFO_FORM_COLLECTION);
        DBObject fofoDbOject = collection.findOne(filter);
        if (fofoDbOject != null) {
            return fofoDbOject.toString();
        } else {
            return null;
        }
    }

    public String getFofoFormsJsonString() {
        DB db = mongoClient.getDB(FOFO_DB);
        DBCollection collection = db.getCollection(FOFO_FORM_COLLECTION);
        DBCursor cursor = collection.find();
        StringBuilder fofoFormsJsonString = new StringBuilder();
        fofoFormsJsonString.append("[");
        while (cursor.hasNext()) {
            fofoFormsJsonString.append(cursor.next().toString());
            if (cursor.hasNext()) {
                fofoFormsJsonString.append(",");
            }
        }
        fofoFormsJsonString.append("]");
        return fofoFormsJsonString.toString();
    }

    public FofoForm getFofoForm(int fofoId) {
        String fofoFormJsonString = getFofoFormJsonStringByFofoId(fofoId);
        System.out.println(fofoFormJsonString);
        return new Gson().fromJson(fofoFormJsonString, FofoForm.class);
        // return convertJSONToPojo(fofoDbOject.toString());
    }

    public FofoForm getFofoForm(String email) {
        String fofoFormJsonString = getFofoFormJsonStringByEmail(email);
        System.out.println(fofoFormJsonString);
        return new Gson().fromJson(fofoFormJsonString, FofoForm.class);
        // return convertJSONToPojo(fofoDbOject.toString());
    }

    private static FofoForm convertJSONToPojo(String json) {

        Type type = new TypeToken<FofoForm>() {
        }.getType();

        return new Gson().fromJson(json, type);

    }

    public void updateColumnsById(Map<String, Integer> map, int fofoId) {
        DB db = mongoClient.getDB(FOFO_DB);
        BasicDBObject filter = new BasicDBObject();
        filter.append("_id", fofoId);
        DBCollection collection = db.getCollection(FOFO_FORM_COLLECTION);
        BasicDBObject updateFields = new BasicDBObject();
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            updateFields.append(entry.getKey(), entry.getValue());
        }
        BasicDBObject newDocument = new BasicDBObject();
        newDocument.append("$set", updateFields);
        collection.update(filter, newDocument);
    }

    public List<DBObject> getBrandsToDisplay(int categoryId) {
        DB db = mongoClient.getDB(FOFO_DB);
        BasicDBObject filter = new BasicDBObject();
        filter.append("active", true);
        if (categoryId != 0) {
            filter.append("categoryId", categoryId);
        }
        return db.getCollection(FOFO_BRANDS).find(filter).toArray();
    }

    public List<DBObject> getAllBrandsToDisplay(int categoryId) {
        DB db = mongoClient.getDB(FOFO_DB);
        BasicDBObject filter = new BasicDBObject();
        if (categoryId != 0) {
            filter.append("categoryId", categoryId);
        }
        return db.getCollection(FOFO_BRANDS).find(filter).toArray();
    }

    public List<DBObject> getBannersByType(String bannerType) {
        DB db = mongoClient.getDB(FOFO_DB);
        BasicDBObject filter = new BasicDBObject();
        filter.append("type", bannerType);
        BasicDBObject orderBy = new BasicDBObject();
        orderBy.put("rank", 1);
        return db.getCollection(PROFITMANDI_BANNERS).find(filter).sort(orderBy).toArray();
    }

    @SuppressWarnings("unchecked")
    public List<Document> getSubcategoriesToDisplay() {
        MongoDatabase db = mongoClient.getDatabase("Catalog");
        System.out.println("Connection to MongoDB database successfully");
        MongoCollection<Document> collection = db.getCollection("Deals");

        Document object = new Document().append("$match", new Document().append("category_id", 6).append("showDeal", 1)
                .append("dealRankPoints", new Document("$gt", 0)));
        Document ob = new Document("$group",
                new Document().append("_id",
                                new Document().append("subCategoryId", "$subCategoryId").append("subCategory", "$subCategory"))
                        .append("count", new Document("$sum", 1)));
        List<Document> pipeline = Arrays.asList(object, ob);
        AggregateIterable<Document> cursor = collection.aggregate(pipeline);

        List<Document> resultDocuments = new ArrayList<>();
        for (Document dbo : cursor) {
            System.out.println(dbo.toString());
            LOGGER.info("categories" + dbo.toString());
            resultDocuments.add(dbo);
        }
        return resultDocuments;
    }

    public boolean saveRetailerInterestOnFofo(RetailerFofoInterest retailerInterest) {
        DB db = mongoClient.getDB(FOFO_DB);
        Gson gs = new Gson();
        DBCollection fofoInterestCollection = db.getCollection(RETAILER_FOFO_INTEREST);
        DBObject dbObject = (DBObject) JSON.parse(gs.toJson(retailerInterest));
        fofoInterestCollection.save(dbObject);
        return true;
    }

    public boolean hasRetailerShownInterest(int userId) {
        DB db = mongoClient.getDB(FOFO_DB);
        BasicDBObject filter = new BasicDBObject();
        filter.append("userId", userId);
        DBCollection fofoInterestCollection = db.getCollection(RETAILER_FOFO_INTEREST);
        return fofoInterestCollection.findOne(filter) != null;
    }

    public void persistNotificationCmpInfo(NotificationCampaigns ff) {
        DB db = mongoClient.getDB(USER_DB);
        DBCollection collection = db.getCollection(NOTIFICATION_CAMPAIGNS);
        if (ff.get_id() == 0) {
            BasicDBObject orderBy = new BasicDBObject();
            orderBy.put("_id", -1);
            DBCursor cursor = collection.find().sort(orderBy).limit(1);
            long id = 1l;
            while (cursor.hasNext()) {
                Gson gson = new Gson();
                NotificationCampaigns existingFofo = gson.fromJson(cursor.next().toString(),
                        NotificationCampaigns.class);
                id = existingFofo.get_id() + 1;
            }
            ff.set_id(id);
        }
        Gson gs = new Gson();
        DBObject dbObject = (DBObject) JSON.parse(gs.toJson(ff));
        collection.save(dbObject);
    }

    /**
     * Close MongoDB connections to prevent memory leaks on shutdown
     */
    public void close() {
        if (closed) {
            return;
        }
        closed = true;
        LOGGER.info("Closing MongoDB connections...");
        try {
            if (mongoClient != null) {
                mongoClient.close();
                LOGGER.info("Main MongoClient closed");
            }
        } catch (Exception e) {
            LOGGER.error("Error closing mongoClient", e);
        }
        try {
            if (contentMongoClient != null) {
                contentMongoClient.close();
                LOGGER.info("Content MongoClient closed");
            }
        } catch (Exception e) {
            LOGGER.error("Error closing contentMongoClient", e);
        }
    }

}