Rev 11672 | Rev 11970 | 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.ItemText;import in.shop2020.logistics.LogisticsInfo;import in.shop2020.logistics.LogisticsService;import in.shop2020.logistics.LogisticsServiceException;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.UserClient;import in.shop2020.utils.DataLogger;import java.io.IOException;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Calendar;import java.util.GregorianCalendar;import java.util.HashMap;import java.util.List;import java.util.Map;import net.sf.ehcache.CacheManager;import org.apache.commons.lang.StringUtils;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.apache.thrift.TException;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", params={"statusCode", "301"})})public class EntityController extends BaseController {private static final long serialVersionUID = 1L;private static Logger log = Logger.getLogger(Class.class);private Long firstItem = 0l;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 entityLogisticsEstimation = "[]";private static final String DEFAULT_PINCODE = "110001";private String id;private String redirectUrl;private long productId;private boolean isMobile = false;private Map<String, Double> discounts = new HashMap<String, Double>();private Map<String, String> snippets;private static Map<Long, String> label = new HashMap<Long, String>();public static Map<Integer, String> businessDayToActualDateMap = new HashMap<Integer, String>();private Map<String, String> deliveryEstimate = new HashMap<String, String>();static{setRetargettingLabel();}public EntityController(){super();}// GET /*/1000001@Actions({@Action("/mobile-phones"),@Action("/cameras"),@Action("/mobile-accessories"),@Action("/tablets"),@Action("/laptops"),@Action("/laptop-accessories"),@Action("/entity"),@Action("/music-players"),@Action("/smart-watches")})public String show() throws SecurityException, IOException, JSONException {log.info("id=" + id);String entityUrl = "";String metaDescription = "";String pageTitle = "";String productName = "";String categoryName = "";String categoryUrl = "";String displayAccessories = "FALSE";String breadCrumb = "";String parentCategory = "";String compareCategory = "";String isComparable = "false";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");pageTitle = productPropertiesInJson.getString("title");productName = productPropertiesInJson.getString("name");categoryName = productPropertiesInJson.getString("categoryName");categoryUrl = productPropertiesInJson.getString("categoryUrl");displayAccessories = productPropertiesInJson.getString("displayAccessories");breadCrumb = productPropertiesInJson.getString("breadCrumb");parentCategory = productPropertiesInJson.getString("parentCategory");compareCategory = productPropertiesInJson.getString("compareCategory");isComparable = productPropertiesInJson.getString("isComparable");}catch (JSONException e) {log.warn("Unable to parse product properties JSON", e);try {CatalogClient catalogClientService = new CatalogClient();in.shop2020.model.v1.catalog.CatalogService.Client client = catalogClientService.getClient();Item item = client.getItemsByCatalogId(productId).get(0);redirectUrl = "/" + item.getBrand().toLowerCase().replace(" ", "-");} catch (Exception e1) {log.warn("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 urlString 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("BREADCRUMB", breadCrumb);htmlSnippets.put("PARENT_CATEGORY", parentCategory);htmlSnippets.put("COMPARE_CATEGORY", compareCategory);htmlSnippets.put("IS_COMPARABLE", isComparable);if(displayAccessories.equals("TRUE")){setMobile(true);}try {if(userinfo.getUserId() != -1){long itemId = Long.parseLong(id);UserClient userServiceClient = new UserClient();Client client = userServiceClient.getClient();client.updateBrowseHistory(userinfo.getUserId(), itemId);}} catch (Exception e) {log.warn("Unable to update the browsing history because of: ", e);}DataLogger.logData(EventType.PRODUCT_VIEW, getSessionId(), userinfo.getUserId(), userinfo.getEmail(), userinfo.getPincode(),productName, Long.toString(productId), StringUtils.substring(request.getHeader("referer"), 0, 500));try {CatalogClient catalogClientService = new CatalogClient();in.shop2020.model.v1.catalog.CatalogService.Client client = catalogClientService.getClient();setEntityLogisticsEstimation();getDeliveryEstimate( firstItem, userinfo.getPincode());} catch (Exception e1) {log.warn("Unable to get delivery estimates for "+ id);}return "show";}/**** @return*/public void getDeliveryEstimate(Long itemId, String pincode){LogisticsClient logisticsServiceClient = null;String days = "-1";long businessDays = -1;boolean isCODAvailable=false;boolean isOTGAvailable=false;String codDays = "-1";try {logisticsServiceClient = new LogisticsClient();LogisticsService.Client logisticsClient = logisticsServiceClient.getClient();LogisticsInfo logistincInfo = logisticsClient.getLogisticsEstimation(itemId, pincode, DeliveryType.PREPAID);if(logistincInfo.getDeliveryTime()!=-1L){days = getDeliveryDateString((int)logistincInfo.getDeliveryTime(), DeliveryType.PREPAID);if(logistincInfo.isCodAllowed()){codDays = getDeliveryDateString((int)(logistincInfo.getDeliveryTime()), DeliveryType.COD);}}businessDays = logistincInfo.getDeliveryTime();isCODAvailable = logistincInfo.isCodAllowed();isOTGAvailable = logistincInfo.isOtgAvailable();log.info("busines days = " + businessDays + "is COD avaialbale " + isCODAvailable + "is OTG available " + isOTGAvailable + " days "+days+" cod days "+codDays);} catch (LogisticsServiceException e) {log.error("Unable to get estimate/COD availability for " + itemId, e);} catch(TException e) {} catch (Exception e) {}deliveryEstimate.put("delivery_estimate", days);deliveryEstimate.put("cod_delivery_estimate", codDays);deliveryEstimate.put("is_cod_available_for_location", Boolean.toString(isCODAvailable));deliveryEstimate.put("on_time_guarantee", Boolean.toString(isOTGAvailable));deliveryEstimate.put("business_days", businessDays + "");}private static String getDeliveryDateString(int days, DeliveryType type) throws TException {Calendar now = new GregorianCalendar();int hour = now.get(Calendar.HOUR_OF_DAY);if(type == DeliveryType.COD && hour < 15){days = days + 1;}if(businessDayToActualDateMap.containsKey(days)){if(hour != 0){return businessDayToActualDateMap.get(days);}businessDayToActualDateMap.clear();}now.set(now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH), 0, 0, 0);LogisticsClient logisticsServiceClient = null;logisticsServiceClient = new LogisticsClient();LogisticsService.Client logisticsClient = logisticsServiceClient.getClient();int newdays = (int) logisticsClient.adjustDeliveryDays(now.getTimeInMillis(), days);now.add(Calendar.DAY_OF_MONTH, newdays);SimpleDateFormat dateformat = new SimpleDateFormat("EEE dd-MMM-yy");if(newdays == 1){businessDayToActualDateMap.put(days, "Tomorrow, " + dateformat.format(now.getTime()));}else{businessDayToActualDateMap.put(days, dateformat.format(now.getTime()));}return businessDayToActualDateMap.get(days);}/**** @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(){String query = request.getQueryString();if(query!=null){return redirectUrl + "?" + query;}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 getProductName() {return htmlSnippets.get("PRODUCT_NAME");}public String getCompareCategory(){return htmlSnippets.get("COMPARE_CATEGORY");}public String getCompareCategoryLowerCase(){String compareCategory = htmlSnippets.get("COMPARE_CATEGORY");return compareCategory.toLowerCase();}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");}public String isComparable(){return htmlSnippets.get("IS_COMPARABLE");}/*** @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 void setEntityLogisticsEstimation(){List<ItemText> itemTexts = null;try {LogisticsClient cl = new LogisticsClient();LogisticsService.Client client = cl.getClient();itemTexts = client.getEntityLogisticsEstimation(productId, DEFAULT_PINCODE, DeliveryType.PREPAID );if(itemTexts!=null){List<Long> items = new ArrayList<Long>();for(ItemText itemText : itemTexts) {items.add(itemText.getItemId());}firstItem = items.get(0);entityLogisticsEstimation = new Gson().toJson(items);return;}} catch (Exception e1) {log.error("Unable to get items for productId: "+ productId, e1);}entityLogisticsEstimation = "[]";}public String getEntityLogisticsEstimation() {return entityLogisticsEstimation;}private static void setRetargettingLabel() {label.put((long) 1002160, "6EIBCKjf1wMQ6Pua0wM"); //Samsung Galaxy Y S5360label.put((long) 1002106, "JFGVCKCt8gMQ6Pua0wM"); //Sony Ericsson Xperia Neo V MT11ilabel.put((long) 1003230, "ArAYCJiu8gMQ6Pua0wM"); //Micromax Funbook Tab P300label.put((long) 1002151, "j0c_CJCv8gMQ6Pua0wM"); //HTC Explorer (Pico) A310elabel.put((long) 1000607, "7H3QCKDh8wMQ6Pua0wM"); //SanDisk MicroSD 8GBlabel.put((long) 1003213, "QtGQCJji8wMQ6Pua0wM"); //Micromax SUPERFONE Gossip A78label.put((long) 1002530, "0YNbCJDj8wMQ6Pua0wM"); //Samsung Champ Deluxe Duos C3312label.put((long) 1003039, "pQUaCIjk8wMQ6Pua0wM"); //Samsung Star 3 Duos S5222label.put((long) 1002575, "zcYTCIDl8wMQ6Pua0wM"); //Samsung Galaxy Y Duos S6102}public String getRetargettingLabel() {return label.get(this.productId);}public String getEmiObject(){return ProceedToPayController.getEmiSchemesInJSON();}public String getDeliveryEstimate() {return new Gson().toJson(this.deliveryEstimate);}}