Subversion Repositories SmartDukaan

Rev

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

package in.shop2020.serving.controllers;

import in.shop2020.serving.services.SolrSearchService;
import in.shop2020.serving.utils.FileUtils;
import in.shop2020.serving.utils.Utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Result;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * @author rajveer
 *
 */
@Result(name = "index", location = "special-page-index.vm")
public class SpecialPageController extends BaseController {
    private static final long serialVersionUID = 1L;
    private static Logger log = Logger.getLogger(Class.class);
        private static Map<String, JSONObject> specialPagesDetails;

        private static final String[] facetDefIDs = 
            new String[] {"F_50010","F_50011","F_50002","F_50001",  "F_50006", "F_50007" };

        private static final String[] facetLabels = 
            new String[] {"Category","Sub Category","Price", "Brand", "Data Connectivity", "Camera Resolution" };

        static {
            try {
                loadSpecialPagesDetails();
            }
            catch (IOException e) {
            log.error("Could not load special pages details", e);
        }
            catch (JSONException e) {
            log.error("Could not load special pages details", e);
        }
        }

        private List<String> results;
        private Map<String, String> snippets;
        private Map<String, List<String[]>> facets;
        private List<String[]> crumbs;

        private String specialPageName;
        private String specialPageTitle;
        private String facetSelection = "";

        private String query;

        private Double minPrice;
        private Double maxPrice;
        
        private long windowSize = 20;
        private long page = 1;
        private long totalResults;
        private long beginIndex = 0;
        private String url;
        private String priceUrl = "?";

        /**
         * GET /abc/10004
         * 
         */
//    @Actions({ @Action("/nokia"),
//               @Action("/samsung"),
//               @Action("/spice"),
//               @Action("/blackberry"),
//               @Action("/sony-ericsson"),
//               @Action("/micromax"),
//               @Action("/lg"),
//               @Action("/htc"),
//               @Action("/motorola"),
//               @Action("/dell"),
//               @Action("/apple"),
//               @Action("/android"),
//               @Action("/brand") })
    public String index() throws SecurityException, IOException, JSONException {
            String uri = request.getRequestURI();
            log.info("Uri: " + uri);
            specialPageName  = getSpecialPageNameFromUri(uri);
            specialPageTitle = getSpecialPageTitleFromUri(uri);
            query            = getQueryFromUri(uri);
        
        String[] fqrys = this.request.getParameterValues("fq");

        url = "?";

        int length = 1;
        
        if(fqrys!= null){
                length += fqrys.length;
        }
        
        String[] newfqrys;
        if(specialPageName.equals("Android")){
                newfqrys = new String[length];
        }
        else {
                newfqrys = new String[length+1];
        }
        
        if(specialPageName.equals("Android")){
                newfqrys[0] = "F_50010:" + "(\"Mobile Phones\" OR Tablets)";
        }
        else {
                newfqrys[0] = "F_50001:" + specialPageName;
                newfqrys[length] = "F_50010:" + "(\"Mobile Phones\" OR Tablets)";
        }

        String urlCrumb = url;
        
        this.crumbs = new ArrayList<String[]>();
        List<String> arrList = Arrays.asList(facetDefIDs);
        for(int i=1; i<length; i++) {
                newfqrys[i] = fqrys[i-1];
                urlCrumb += "&fq=" + URLEncoder.encode(fqrys[i-1], "UTF-8");
                priceUrl += "&fq=" + URLEncoder.encode(fqrys[i-1], "UTF-8");
                String filterUrl = url;
                String facetName = StringUtils.split(fqrys[i-1], ":")[0];
                String facetValue = StringUtils.split(fqrys[i-1], ":")[1];
                String facetLabel = facetLabels[arrList.indexOf(facetName)];
                this.specialPageTitle += " | " + facetLabel + " " + facetValue;
                this.facetSelection += facetValue + " ";
                for(int j=1; j<length; j++) {
                        if(i==j){
                                continue;
                        }
                        filterUrl += "&fq=" + URLEncoder.encode(fqrys[j-1], "UTF-8");
                }
                String[] acrumb = new String[] { facetLabel, facetValue, filterUrl };
                log.info("acrumb=" + Arrays.toString(acrumb));
                this.crumbs.add(acrumb);
        }

                url = urlCrumb;

        if(this.request.getParameter("page") != null){
                this.page = Long.parseLong(this.request.getParameter("page"));
                this.beginIndex = this.windowSize * (this.page-1);
        }

        if(this.request.getParameter("min-price") != null){
                this.minPrice = (new Double(this.request.getParameter("min-price")));
                url= url + "&min-price=" + this.request.getParameter("min-price");
        }

        if(this.request.getParameter("max-price") != null){
                this.maxPrice = (new Double(this.request.getParameter("max-price")));
                url= url + "&max-price=" + this.request.getParameter("max-price");
        }

        query = query + "&sort=F_50002+asc";

        SolrSearchService search = new SolrSearchService(query, newfqrys, facetDefIDs, (page-1)*windowSize, windowSize, minPrice, maxPrice, 10000, null);
        this.results =  search.getResultMap(); 

        
        this.facets = new LinkedHashMap<String, List<String[]>>();
        String qryString = this.request.getQueryString();
        log.info("qryString=" + qryString);
        
        for (int i=0; i<facetDefIDs.length; i++) {
                String facetDefID = facetDefIDs[i];
                String facetLabel = facetLabels[i];
                HashMap<String, Integer> facetDetailMap = search.getFacetDetails(facetDefID);
                if(facetDetailMap==null)
                        continue;
                List<String[]> values = new ArrayList<String[]>();
                String drilldownURL = url + "&fq=" + facetDefID + ":";
                for(Entry<String, Integer> facetEntry: facetDetailMap.entrySet()){
                    String facet = facetEntry.getKey();
                        drilldownURL = drilldownURL  + URLEncoder.encode(facet, "UTF-8");

                        String[] afacet = new String[] { facet, 
                                        facetEntry.getValue().toString(), drilldownURL  };

                        values.add(afacet);
                }
                
                this.facets.put(facetLabel, values);
        }

        Map<String, Double> priceMap = search.getPriceStatsMap();
        if(priceMap != null){
                this.minPrice = priceMap.get("min");
                this.maxPrice = priceMap.get("max");
        }
        else{
                this.minPrice = 0.0;
                this.maxPrice = 0.0;
        }

        this.totalResults = search.getTotalResults();
        return "index";
    }
    
    public String getPageMetaDesc() {
        return "Best price " + this.facetSelection + this.specialPageName.replaceAll("Phones", "mobile phones") 
            + " mobile phones in India. Experience n' buy online. FREE Next Day delivery. Original product - Full manufacturer warranty. Comprehensive reviews."; 
    }
    
    public String getPageMetaKeywords() throws JSONException {
        return specialPagesDetails.get(request.getRequestURI()).getString("metaKeywords");
    }
    
        public long getBeginIndex(){
                if(totalResults>0)
                        return beginIndex+1;
                return beginIndex;
        }

        public long getTotalPages() {
                return 1 + (totalResults-1)/windowSize;
        }

        public Map<String, String> getSnippets(){
        if(results != null){
                snippets = new HashMap<String, String>();       
                for(String docId: results){
                                try {
                                        snippets.put(docId, FileUtils.read( Utils.EXPORT_ENTITIES_PATH + docId + File.separator +"CategorySnippet.html"));
                                } catch (IOException e) {
                                        log.error(e);
                                }
                        }
        }
                return snippets;
    }

    /**
     * Loads all special pages related details
     */
    private static void loadSpecialPagesDetails() throws IOException, JSONException {
        FileReader fr = new FileReader(Utils.EXPORT_ENTITIES_PATH + "../../javascripts/special-pages.json");
        BufferedReader br = new BufferedReader(fr);
        String str = null;

        specialPagesDetails = new HashMap<String, JSONObject>();
        while ((str = br.readLine()) != null) {
            JSONObject jsonObject = new JSONObject(str);
            specialPagesDetails.put(jsonObject.getString("saholicURL"),
                    jsonObject);
        }

        log.info(specialPagesDetails);
    }

    /**
     * Returns true in case a string passed is a special page name
     */
    public static boolean isValidSpecialPage(String specialPage) {
        if (specialPage == null) {
            return false;
        }

        return specialPagesDetails.containsKey(specialPage);
    }

    private String getQueryFromUri(String uri) throws JSONException {
        return specialPagesDetails.get(uri).getString("searchQuery");
    }

    private String getSpecialPageTitleFromUri(String uri) throws JSONException {
        return specialPagesDetails.get(uri).getString("pageTitle");
    }

    private String getSpecialPageNameFromUri(String uri) throws JSONException {
        return specialPagesDetails.get(uri).getString("displayName");
    }

    public long getCurrentPage() {
        return this.page;
    }

    public Double getMinPrice() {
        return this.minPrice;
    }
    
    public Double getMaxPrice() {
        return this.maxPrice;
    }
    
    public List<String[]> getCrumbs() {
        return this.crumbs;
    }
    public String getSpecialPageTitle() {
        return this.specialPageTitle;
    }   
    
    public String getQuery() {
        return this.query;
    }

    public List<String> getResults() {
        return this.results;
    }
    
    public Map<String, List<String[]>> getFacets() {
        return this.facets;
    }
    
    public long getTotalResults(){
        return totalResults;
    }
    
    public String getUrl(){
        return this.url;
    }

    public String getPriceUrl(){
        return this.priceUrl;
    }

    public String getSpecialPageName() {
        return this.specialPageName;
    }   
}