Rev 35458 | 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.Collections;import java.util.List;import java.util.stream.Collectors;import javax.servlet.http.HttpServletRequest;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.exception.ProfitMandiBusinessException;import com.spice.profitmandi.common.model.ProfitMandiConstants;import com.spice.profitmandi.common.model.UserInfo;import com.spice.profitmandi.common.web.util.ResponseSender;import com.spice.profitmandi.service.catalog.BrandsService;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);@Autowiredprivate SolrService solrService;@Autowiredprivate ResponseSender<?> responseSender;@Autowiredprivate BrandsService brandsService;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(HttpServletRequest request, @RequestParam("search_text") String search_text, @RequestParam("offset") int offset) throws ProfitMandiBusinessException {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());// collection1 docs carry no brand field, so restricted brands are dropped by title matchList<String> restrictedBrands = this.restrictedBrands(request);solrSearchResultResponse = solrSearchResultResponse.stream().filter(x -> !isBlockedTitle(x.getTitle(), restrictedBrands)).collect(Collectors.toList());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(HttpServletRequest request, @RequestParam("search_text") String searchText) throws ProfitMandiBusinessException {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());List<String> restrictedBrands = this.restrictedBrands(request);solrSearchResultResponse = solrSearchResultResponse.stream().filter(x -> !isBlockedTitle(x.getTitle(), restrictedBrands)).collect(Collectors.toList());return responseSender.ok(solrSearchResultResponse);}private List<String> restrictedBrands(HttpServletRequest request) {UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");if (userInfo == null) {return Collections.emptyList();}try {return brandsService.restrictedBrands(userInfo.getRetailerId());} catch (ProfitMandiBusinessException e) {logger.error("Could not resolve restricted brands", e);return Collections.emptyList();}}private boolean isBlockedTitle(String title, List<String> blockedBrands) {if (title == null || blockedBrands.isEmpty()) {return false;}return blockedBrands.stream().anyMatch(x -> title.regionMatches(true, 0, x, 0, x.length())&& (title.length() == x.length() || !Character.isLetterOrDigit(title.charAt(x.length()))));}private JsonArray sanatizedResults(){//Need to re-write this section.This sucks badlyJsonArray 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;}}