Subversion Repositories SmartDukaan

Rev

Rev 10232 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

package in.shop2020.serving.controllers;

import in.shop2020.datalogger.EventType;
import in.shop2020.model.v1.catalog.CatalogService.Client;
import in.shop2020.model.v1.catalog.CatalogServiceException;
import in.shop2020.serving.cache.EhcacheWrapper;
import in.shop2020.serving.services.ContentServingService;
import in.shop2020.serving.utils.SnippetType;
import in.shop2020.thrift.clients.CatalogClient;
import in.shop2020.utils.DataLogger;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.ehcache.CacheManager;

import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.thrift.TException;

/**
 * 
 * @author chandranshu
 *
 */
@SuppressWarnings("serial")
public class HomeController extends BaseController {

        private static Logger logger = Logger.getLogger(Class.class);
        private static final String BEST_DEALS_CACHE_KEY = "home_best_deals_snippet";
        private static final String BEST_SELLERS_CACHE_KEY = "home_best_sellers_snippet";
        private static final String LATEST_ARRIVALS_CACHE_KEY = "home_latest_arrivals_snippet";
        private static final String HOME_PAGE_CACHE_KEY = "home_page_cache_snippets";

        
        private List<String> bestDealSnippets = null;
        private List<String> bestSellerSnippets = null;
        private List<String> latestArrivalSnippets = null;

        public HomeController(){
                super();
        }

        /**
         * Renders the home page. Loads the snippets for best deals, best sellers
         * and latest arrivals if they haven't been loaded already.
         * 
         * @return Name of the view to render.
         * @throws SecurityException
         * @throws IOException
         */
        @Action("/")
        public String index() throws SecurityException, IOException {
                logger.debug("userinfo:" + userinfo.toString());
                logger.info("Rendering the home page");
                setSnippets();
                DataLogger.logData(EventType.HOME_PAGE, getSessionId(), userinfo.getUserId(), userinfo.getEmail());
                return "index";
        }

        /**
         * Renders the home page but always loads the snippets for best deals, best
         * sellers and latest arrivals unconditionally. Should be used to reset the
         * snippets.
         * 
         * @return Name of the view to render.
         * @throws SecurityException
         * @throws IOException
         */
        @Action("/refresh-home")
        public String destroy() throws SecurityException, IOException{
                logger.info("Reloading best deals, best sellers and latest arrivals");
                EhcacheWrapper<String, List<String>> homeSnippetCache = new EhcacheWrapper<String, List<String>>(
                                EhcacheWrapper.HOME_PAGE_SNIPPET_CACHE_NAME, CacheManager.create());
                homeSnippetCache.removeAll();
                setSnippets();
                return "index";
        }

        public List<String> getBestDealSnippets(){
                return bestDealSnippets; 
        }

        public List<String> getBestSellerSnippets(){
                return bestSellerSnippets; 
        }

        public List<String> getLatestArrivalSnippets(){
                return latestArrivalSnippets;
        }

        /**
         * Loads the snippets for best deals, best sellers and latest arrivals
         * into memory.
         */
        private void setSnippets() {
                EhcacheWrapper<String,Map<String, List<String>>> homeSnippetCache = new EhcacheWrapper<String,Map<String, List<String>>>(
                                EhcacheWrapper.HOME_PAGE_SNIPPET_CACHE_NAME, CacheManager.create());
                //logger.info("Source id "+sourceId);
                Map<String, List<String>> homePageSnippets = homeSnippetCache.get(HOME_PAGE_CACHE_KEY);

                if(homePageSnippets == null) {
                        homePageSnippets = new HashMap<String, List<String>>();
                        List<Long> bestDealCatalogIds = null;
                        List<Long> bestSellerCatalogIds = null;
                        List<Long> latestArrivalCatalogIds = null;

                        int bestSellerCount = 4;
                        int latestArrivalCount = 4;
                        try {
                                CatalogClient catalogServiceClient = new CatalogClient();
                                Client client = catalogServiceClient.getClient();
                                //Get top 4 best deals 
                                bestDealCatalogIds = client.getBestDealsCatalogIds(0, 4, null, -1);

                                //Get top 8 best sellers b'coz 4 of them may overlap with best deals.
                                bestSellerCatalogIds = client.getBestSellersCatalogIds(0, 8, null, -1);
                                bestSellerCatalogIds.removeAll(bestDealCatalogIds);
                                if(bestSellerCatalogIds.size() < bestSellerCount)
                                        bestSellerCount = bestSellerCatalogIds.size();

                                //Get top 12 latest arrivals b'coz 4 of them may overlap with best deals
                                //while another 4 may overlap with best sellers.
                                latestArrivalCatalogIds = client.getLatestArrivalsCatalogIds(0, 12, null, Arrays.asList(new Long[]{ 10006L, 10010L, 10050L}));
                                latestArrivalCatalogIds.removeAll(bestDealCatalogIds);
                                latestArrivalCatalogIds.removeAll(bestSellerCatalogIds.subList(0, bestSellerCount)); //We're only considering the first 4 best sellers for removal.
                                if(latestArrivalCatalogIds.size() < latestArrivalCount)
                                        latestArrivalCount = latestArrivalCatalogIds.size();

                        } catch (CatalogServiceException e) {
                                logger.error("Error while fetching data from the catalog service", e);
                        } catch (TException e) {
                                logger.error("Error while fetching data from the catalog service", e);
                        } catch (Exception e) {
                                logger.error("Unexpected exception", e);
                        }
                        bestDealSnippets = getSnippets(bestDealCatalogIds);
                        bestSellerSnippets = getSnippets(bestSellerCatalogIds.subList(0, bestSellerCount));
                        latestArrivalSnippets = getSnippets(latestArrivalCatalogIds.subList(0, latestArrivalCount));
                        homePageSnippets.put(BEST_DEALS_CACHE_KEY, bestDealSnippets);
                        homePageSnippets.put(BEST_SELLERS_CACHE_KEY, bestSellerSnippets);
                        homePageSnippets.put(LATEST_ARRIVALS_CACHE_KEY, latestArrivalSnippets);
                        homeSnippetCache.put(HOME_PAGE_CACHE_KEY, homePageSnippets);
                        logger.info("Populated home snippet cache");
                        return;
                }
                
                bestDealSnippets = homePageSnippets.get(BEST_DEALS_CACHE_KEY);
                bestSellerSnippets = homePageSnippets.get(BEST_SELLERS_CACHE_KEY);
                latestArrivalSnippets = homePageSnippets.get(LATEST_ARRIVALS_CACHE_KEY);
                logger.info("Returning snippets from cache");
        }

        /**
         * Returns a list of snippets to be used on the home page corresponding to
         * the given catalog ids. The snippets are in the same order as the ids in
         * the input list. In case a snippet is not found for an entity, this method
         * simply logs the problem and moves on.
         * 
         * @param catalogIds
         *            Ids of the entities which we want to show.
         * @return The snippet corresponding to each catalog entity
         */
        private List<String> getSnippets(List<Long> catalogIds) {
                List<String> snippets = new ArrayList<String>();
                if(catalogIds == null)
                        return snippets;
                for(Long item: catalogIds){
                        snippets.add(ContentServingService.getSnippet(SnippetType.HOME_SNIPPET, item+"", sourceId));
                }
                return snippets;
        }



        @Override
        public String getHeaderSnippet() {
                String url = request.getQueryString();
                if (url == null) {
                        url = "";
                } else {
                        url = "?" + url;
                }
                url = request.getRequestURI() + url;
                return pageLoader.getHeaderHtml(userinfo.isLoggedIn(), userinfo.getEmail(),userinfo.getTotalItems(), url , 0, true, userinfo.isPrivateDealUser());
        }
        @Override
        public String getCartWidgetSnippet() {
                return pageLoader.getCartWidgetSnippet(userinfo.getTotalItems(), userinfo.getTotalAmount(),0, activeBanners.get("side-banner"),sideBannersMap);
        }
}