Subversion Repositories SmartDukaan

Rev

Rev 35435 | Blame | Compare with Previous | Last modification | View Log | RSS feed

package com.spice.profitmandi.web.controller;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.List;

import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.eclipsesource.json.Json;
import com.eclipsesource.json.JsonArray;
import com.eclipsesource.json.JsonObject;
import com.eclipsesource.json.JsonValue;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.spice.profitmandi.common.model.ProfitMandiConstants;
import com.spice.profitmandi.common.web.util.ResponseSender;
import com.spice.profitmandi.web.res.SolrSearchResultResponse;
import com.spice.profitmandi.web.res.SolrSuggestionResponse;
import com.spice.profitmandi.web.services.SolrService;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@Controller
@org.springframework.transaction.annotation.Transactional(rollbackFor = Throwable.class)
public class SolrSearchController {

        private static final Logger logger=LogManager.getLogger(SolrSearchController.class);

        @Autowired
        private SolrService solrService;
        
        @Autowired
        private ResponseSender<?> responseSender;

        private static final int max_count = 10;
        private static final int max_count_accesories = 5;
        private double max_accessory_score, max_mobile_score, max_tablet_score;
        private int mobile_records, tablet_records;
        private JsonObject result_json;

        @RequestMapping(value = ProfitMandiConstants.URL_SOLR_SEARCH, method=RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE)
        @ApiImplicitParams({
                @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token",
                                required = true, dataType = "string", paramType = "header")
        })
        @ApiOperation(value = "Search Results")
        public ResponseEntity<?> getSearchResults(@RequestParam("search_text") String search_text, @RequestParam("offset") int offset){
                logger.info("search_text : "+search_text+" offset : "+offset);
                String jsonString = null;
                try {
                        jsonString = solrService.getSearchResults(search_text.trim(), offset);
                        logger.info("Response from solr "+jsonString);
                } catch (URISyntaxException | IOException e) {
                        logger.error("Error while gettting search results from solr",e);
                        responseSender.internalServerError(e);
                }
                JsonArray result_json = Json.parse(jsonString).asObject().get("response").asObject().get("docs").asArray();
                for (JsonValue j : result_json ){
                        j.asObject().add("productUrl", j.asObject().get("ids").asArray().get(0)+"/"+j.asObject().get("id").asString());
                }
                Gson gson = new Gson();
                List<SolrSearchResultResponse> solrSearchResultResponse = gson.fromJson(result_json.toString(), new TypeToken<List<SolrSearchResultResponse>>(){}.getType());
                return responseSender.ok(solrSearchResultResponse);
        }


        @RequestMapping(value = ProfitMandiConstants.URL_SOLR_SUGGESTION, method=RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE)
        @ApiImplicitParams({
                @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token",
                                required = true, dataType = "string", paramType = "header")
        })
        @ApiOperation(value = "Auto Suggest")
        public ResponseEntity<?> getSuggestions(@RequestParam("search_text") String searchText){
                logger.info("Suggestion text : "+searchText);
                String jsonString;
                try {
                        jsonString = solrService.getSuggestions(searchText.trim());
                } catch (URISyntaxException | IOException e) {
                        logger.error("Error while getting suggestions from solr",e);
                        return responseSender.internalServerError(e);
                }
                result_json = Json.parse(jsonString).asObject().get("grouped").asObject();
                Gson gson = new Gson();
                List<SolrSuggestionResponse> solrSearchResultResponse = gson.fromJson(sanatizedResults().toString(), new TypeToken<List<SolrSuggestionResponse>>(){}.getType());
                return responseSender.ok(solrSearchResultResponse);
        }

        private JsonArray sanatizedResults(){
                //Need to re-write this section.This sucks badly
                JsonArray output = Json.array().asArray();
                JsonArray temp_mobiles = getResults(3);
                JsonArray temp_tablets = getResults(5);
                JsonArray temp_accesories = getResults(6);
                if (max_accessory_score > max_mobile_score){
                        for (JsonValue j : temp_accesories){
                                output.add(j);
                        }
                }
                int toFetch = temp_accesories.size() == 0 ? 5 : 3;
                int count = 1;
                if (max_mobile_score > max_tablet_score){
                        for (JsonValue j : temp_mobiles){
                                if (count > toFetch)
                                        break;
                                output.add(j);
                                count++;
                        }
                        count = 1;
                        for (JsonValue j : temp_tablets){
                                if (count > toFetch)
                                        break;
                                output.add(j);
                                count++;
                        }
                }
                else{
                        for (JsonValue j : temp_tablets){
                                if (count > toFetch)
                                        break;
                                output.add(j);
                                count++;
                        }
                        count = 1;
                        for (JsonValue j : temp_mobiles){
                                if (count > toFetch)
                                        break;
                                output.add(j);
                                count++;
                        }
                }
                if (max_accessory_score <= max_mobile_score){
                        for (JsonValue j : temp_accesories){
                                output.add(j);
                        }
                }
                return output;
        }

        private JsonArray getResults(int category_id){

                JsonArray output = new JsonArray();
                JsonArray suggestion;
                JsonArray subcat_suggestion;
                int count = 0;

                switch(category_id){
                case 3:
                        suggestion= result_json.get("category_id:3").asObject().get("doclist").asObject().get("docs").asArray();
                        mobile_records = result_json.get("category_id:3").asObject().get("doclist").asObject().get("numFound").asInt();
                        try{
                                max_mobile_score = result_json.get("category_id:3").asObject().get("doclist").asObject().get("maxScore").asDouble();
                        }
                        catch(Exception e){
                                max_mobile_score = 0.0;
                        }
                        for (JsonValue item : suggestion) {
                                if (count == max_count){
                                        break;
                                }
                                JsonObject temp = Json.object().add("subCategoryId",item.asObject().get("subCategoryId").asInt()).add("category_id",item.asObject().get("category_id").asInt()).add("title",item.asObject().get("title").asString()).add("category",item.asObject().get("category").asString());
                                output.add(temp);
                                count++;
                        }
                case 5:
                        suggestion = result_json.get("category_id:5").asObject().get("doclist").asObject().get("docs").asArray();
                        tablet_records = result_json.get("category_id:5").asObject().get("doclist").asObject().get("numFound").asInt();
                        try{
                                max_tablet_score = result_json.get("category_id:5").asObject().get("doclist").asObject().get("maxScore").asDouble();
                        }
                        catch(Exception e){
                                max_tablet_score = 0.0;
                        }
                        for (JsonValue item : suggestion) {
                                if (count == max_count){
                                        break;
                                }
                                JsonObject temp = Json.object().add("subCategoryId",item.asObject().get("subCategoryId").asInt()).add("category_id",item.asObject().get("category_id").asInt()).add("title",item.asObject().get("title").asString()).add("category",item.asObject().get("category").asString());
                                output.add(temp);
                                count++;
                        }
                case 6:
                        subcat_suggestion = result_json.get("subCategoryId").asObject().get("groups").asArray();
                        max_accessory_score = 0.0;
                        for (JsonValue itemList : subcat_suggestion) {
                                if (itemList.asObject().get("groupValue").asInt()==0){
                                        continue;
                                }
                                suggestion = itemList.asObject().get("doclist").asObject().get("docs").asArray();
                                try{
                                        max_accessory_score = max_accessory_score < itemList.asObject().get("doclist").asObject().get("maxScore").asDouble() ? itemList.asObject().get("doclist").asObject().get("maxScore").asDouble() : max_accessory_score;
                                }
                                catch(Exception e){
                                        ;
                                }
                                count = 0;
                                for (JsonValue item : suggestion) {
                                        if (count == max_count_accesories){
                                                break;
                                        }
                                        JsonObject temp = Json.object().add("subCategoryId",item.asObject().get("subCategoryId").asInt()).add("category_id",item.asObject().get("category_id").asInt()).add("title",item.asObject().get("title").asString()).add("category",item.asObject().getString("subCategory", "Accessories"));
                                        output.add(temp);
                                        count++;
                                }
                        }
                }
                return output;
        }

}