Subversion Repositories SmartDukaan

Rev

Rev 4882 | Rev 5001 | 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.logistics.DeliveryType;
import in.shop2020.logistics.LogisticsService;
import in.shop2020.model.v1.catalog.Item;
import in.shop2020.model.v1.user.UserContextService.Client;
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.thrift.clients.LogisticsClient;
import in.shop2020.thrift.clients.PromotionClient;
import in.shop2020.thrift.clients.UserClient;
import in.shop2020.utils.DataLogger;

import java.io.IOException;
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.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.gson.Gson;

/**
 * 
 * @author rajveer
 *
 */

@Results({
    @Result(name = "show", location = "entity-show.vm"),
    @Result(name = "redirect", location = "${redirectUrl}", type = "redirect")
})
public class EntityController extends BaseController {
                
        private static final long serialVersionUID = 1L;
        private static Logger log = Logger.getLogger(Class.class);
        
        private static final String PRODUCT_PROERTIES_SNIPPET_KEY = "PRODUCT_PROPERTIES";
        private static final String PRODUCT_SUMMARY_SNIPPET_KEY = "PRODUCT_SUMMARY";
        private static final String PRODUCT_SLIDEGUIDE_KEY = "SLIDEGUIDE";
    
        private String id;
        private String redirectUrl;
        private long productId;
        private boolean isMobile = false;
        
        private Map<String, Double> discounts = null;
        private Map<String, String> snippets;
        
        public EntityController(){
                super();
        }

        // GET /*/1000001
        @Actions({
                @Action("/mobile-phones"),
                @Action("/mobile-accessories"),
                @Action("/tablets"),
                @Action("/laptops"),
                @Action("/entity")
        })
    public String show() throws SecurityException, IOException, JSONException {
        log.info("id=" + id);

        String entityUrl = "";
        String metaKeywords = "";
        String metaDescription = "";
        String pageTitle = "";
        String productName = "";
        String categoryName = "";
        String categoryUrl = "";
        String displayAccessories = "FALSE";
        String breadCrumb = "";
        try {
            setSnippets();
            htmlSnippets.put("PRODUCT_PROPERTIES", snippets.get(PRODUCT_PROERTIES_SNIPPET_KEY));
            JSONObject productPropertiesInJson = new JSONObject(htmlSnippets.get("PRODUCT_PROPERTIES"));
            entityUrl = productPropertiesInJson.getString("entityUrl");
            metaDescription = productPropertiesInJson.getString("metaDescription");
            metaKeywords = productPropertiesInJson.getString("metaKeywords");
            pageTitle = productPropertiesInJson.getString("title");
            productName = productPropertiesInJson.getString("name");
            categoryName = productPropertiesInJson.getString("categoryName");
            categoryUrl = productPropertiesInJson.getString("categoryUrl");
            displayAccessories = productPropertiesInJson.getString("displayAccessories");
            breadCrumb = productPropertiesInJson.getString("breadCrumb");
        }
        catch (JSONException e) {
            log.error("Unable to parse product properties JSON", e);
            try {
                CatalogClient catalogClientService = new CatalogClient();
                in.shop2020.model.v1.catalog.InventoryService.Client client = catalogClientService.getClient();
                
                Item item = client.getItemsByCatalogId(productId).get(0);
                redirectUrl = "/" + item.getBrand().toLowerCase().replace(" ", "-");
            } catch (Exception e1) {
                log.error("Unable to get items by catalog id", e1);
                redirectUrl = "/";
            }
            log.info(redirectUrl);
            return "redirect";
       }
        String currentUrl = request.getRequestURL().toString();
        
        if (!currentUrl.contains(entityUrl)) {
            redirectUrl = entityUrl;
            return "redirect";
        }
        
        //Extracting base url
        String rootUrl = currentUrl.split("/")[2];
        
        htmlSnippets.put("PRODUCT_SUMMARY", snippets.get(PRODUCT_SUMMARY_SNIPPET_KEY));
        htmlSnippets.put("PRODUCT_ID", productId + "");
        htmlSnippets.put("PRODUCT_NAME", productName);
        htmlSnippets.put("CATEGORY_NAME", categoryName);
        htmlSnippets.put("CATEGORY_URL", categoryUrl);
        htmlSnippets.put("PRODUCT_URL", currentUrl);
        htmlSnippets.put("ROOT_URL", "http://" + rootUrl);
                htmlSnippets.put("SLIDE_GUIDE", snippets.get(PRODUCT_SLIDEGUIDE_KEY));
                htmlSnippets.put("PAGE_TITLE", pageTitle.trim());
                htmlSnippets.put("PAGE_METADESC", metaDescription);
                htmlSnippets.put("PAGE_METAKEYWORDS", metaKeywords);
                htmlSnippets.put("BREADCRUMB", breadCrumb);
                
                if(displayAccessories.equals("TRUE")){
                        setMobile(true);
                }
                
                try {
                        UserClient userServiceClient = new UserClient();
                        Client client = userServiceClient.getClient();
                        long itemId = Long.parseLong(id);
                        long userId = userinfo.getUserId();
                        if(userId != -1){
                                client.updateBrowseHistory(userId, itemId);
                        }
                
                } catch (Exception e) {
                        log.warn("Unable to update the browsing history because of: ", e);
                }
                
                try     {
                        PromotionClient promotionServiceClient = new PromotionClient();
                        in.shop2020.model.v1.user.PromotionService.Client promotionClient = promotionServiceClient.getClient();
                        
                        discounts = promotionClient.getDiscountsForEntity(productId);
                        
                } catch (Exception e) {
                        log.error("Unable to retrieve discounts", e);
                }
        
                DataLogger.logData(EventType.PRODUCT_VIEW, getSessionId(), userinfo.getUserId(), userinfo.getEmail(),
                productName, Long.toString(productId), request.getHeader("referer"));
                return "show";
    }

    /**
     * 
     * @param id
     */
    public void setId(String id) {
        String[] tokens = id.split("-");
        this.id = tokens[tokens.length - 1];
        this.productId = Long.parseLong(this.id);
    }

        public Map<String,String> getHtmlSnippets(){
                System.out.println(" getHtmlSnippets  is called");
                return htmlSnippets;
        }
        
        public String getSlideGuideSnippet(){
                return htmlSnippets.get("SLIDE_GUIDE");
        }

        public String getRedirectUrl(){
        return redirectUrl;
    }
        
        public String getProductSummarySnippet(){
                return htmlSnippets.get("PRODUCT_SUMMARY");
        }
        
        public String getPageTitleSnippet(){
                return htmlSnippets.get("PAGE_TITLE");
        }
        
        public String getPageMetaDescSnippet(){
                return htmlSnippets.get("PAGE_METADESC");
        }
        
        public String getPageMetaKeywordsSnippet(){
                return htmlSnippets.get("PAGE_METAKEYWORDS");
        }
        
        public String getProductName()  {
                return htmlSnippets.get("PRODUCT_NAME");
        }

        public String getCategoryName() {
                return htmlSnippets.get("CATEGORY_NAME");
        }
        
        public String getCategoryUrl()  {
                return htmlSnippets.get("CATEGORY_URL");
        }
        
        public String getProductId()    {
                return htmlSnippets.get("PRODUCT_ID");
        }
        
        public String getProductUrl()   {
                return htmlSnippets.get("PRODUCT_URL");
        }
        
        public String getRootUrl()      {
                return htmlSnippets.get("ROOT_URL");
        }

        public String getBreadCrumb(){
                return htmlSnippets.get("BREADCRUMB");
        }
        
        /**
         * @param isMobile the isMobile to set
         */
        public void setMobile(boolean isMobile) {
                this.isMobile = isMobile;
        }

        /**
         * @return the isMobile
         */
        public boolean isMobile() {
                return isMobile;
        }
        
    private void setSnippets() {
        EhcacheWrapper<Long, Map<String, String>> productSnippetsCache = new EhcacheWrapper<Long, Map<String, String>>(
                EhcacheWrapper.PRODUCT_PAGE_SNIPPET_CACHE_NAME, CacheManager.create());
        if(sourceId == -1){
                snippets = productSnippetsCache.get(productId);
        }
        if (snippets == null) {
            log.info("Getting product snippet for :" + productId);
            snippets = new HashMap<String, String>();
            snippets.put(PRODUCT_PROERTIES_SNIPPET_KEY, ContentServingService.getSnippet(SnippetType.PRODUCT_PROPERTIES_SNIPPET, productId+"", sourceId));
            snippets.put(PRODUCT_SUMMARY_SNIPPET_KEY, ContentServingService.getSnippet(SnippetType.PRODUCT_DETAIL_SNIPPET, productId+"", sourceId));
            snippets.put(PRODUCT_SLIDEGUIDE_KEY, ContentServingService.getSnippet(SnippetType.SLIDE_GUIDE_SNIPPET, productId+"", sourceId));
            if(sourceId == -1){
                productSnippetsCache.put(productId, snippets);
            }
            return;
        }
        log.info("Loaded from cache product snippet for :" + productId);
    }
    
    public Map<String, Double> getDiscounts()   {
        return discounts;
    }
    
    public String getEntityLogisticsEstimation(){
        List<Long> items=null; 
        try {
                LogisticsClient cl = new LogisticsClient();
            LogisticsService.Client client = cl.getClient();
            items = client.getEntityLogisticsEstimation(productId, userinfo.getPincode(), DeliveryType.PREPAID );
        } catch (Exception e1) {
            log.error("Unable to get items by catalog item id", e1);
        }
        return new Gson().toJson(items);
    }
}