Subversion Repositories SmartDukaan

Rev

Rev 35458 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
21287 kshitij.so 1
package com.spice.profitmandi.web.controller;
2
 
3
import java.io.IOException;
4
import java.net.URISyntaxException;
37144 amit 5
import java.util.Collections;
21297 kshitij.so 6
import java.util.List;
37144 amit 7
import java.util.stream.Collectors;
21287 kshitij.so 8
 
37144 amit 9
import javax.servlet.http.HttpServletRequest;
10
 
23568 govind 11
import org.apache.logging.log4j.Logger;
12
import org.apache.logging.log4j.LogManager;
21287 kshitij.so 13
import org.springframework.beans.factory.annotation.Autowired;
14
import org.springframework.http.MediaType;
15
import org.springframework.http.ResponseEntity;
16
import org.springframework.stereotype.Controller;
17
import org.springframework.web.bind.annotation.RequestMapping;
18
import org.springframework.web.bind.annotation.RequestMethod;
19
import org.springframework.web.bind.annotation.RequestParam;
20
 
21
import com.eclipsesource.json.Json;
22
import com.eclipsesource.json.JsonArray;
23
import com.eclipsesource.json.JsonObject;
24
import com.eclipsesource.json.JsonValue;
21389 kshitij.so 25
import com.google.gson.Gson;
26
import com.google.gson.reflect.TypeToken;
37144 amit 27
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
21287 kshitij.so 28
import com.spice.profitmandi.common.model.ProfitMandiConstants;
37144 amit 29
import com.spice.profitmandi.common.model.UserInfo;
22931 ashik.ali 30
import com.spice.profitmandi.common.web.util.ResponseSender;
37144 amit 31
import com.spice.profitmandi.service.catalog.BrandsService;
21297 kshitij.so 32
import com.spice.profitmandi.web.res.SolrSearchResultResponse;
33
import com.spice.profitmandi.web.res.SolrSuggestionResponse;
21287 kshitij.so 34
import com.spice.profitmandi.web.services.SolrService;
35
 
36
import io.swagger.annotations.ApiImplicitParam;
37
import io.swagger.annotations.ApiImplicitParams;
38
import io.swagger.annotations.ApiOperation;
39
 
40
@Controller
35458 amit 41
@org.springframework.transaction.annotation.Transactional(rollbackFor = Throwable.class)
21287 kshitij.so 42
public class SolrSearchController {
43
 
23568 govind 44
	private static final Logger logger=LogManager.getLogger(SolrSearchController.class);
21287 kshitij.so 45
 
46
	@Autowired
22931 ashik.ali 47
	private SolrService solrService;
37144 amit 48
 
22931 ashik.ali 49
	@Autowired
50
	private ResponseSender<?> responseSender;
21287 kshitij.so 51
 
37144 amit 52
	@Autowired
53
	private BrandsService brandsService;
54
 
21287 kshitij.so 55
	private static final int max_count = 10;
56
	private static final int max_count_accesories = 5;
57
	private double max_accessory_score, max_mobile_score, max_tablet_score;
58
	private int mobile_records, tablet_records;
59
	private JsonObject result_json;
60
 
61
	@RequestMapping(value = ProfitMandiConstants.URL_SOLR_SEARCH, method=RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE)
62
	@ApiImplicitParams({
35435 amit 63
		@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token",
21287 kshitij.so 64
				required = true, dataType = "string", paramType = "header")
65
	})
66
	@ApiOperation(value = "Search Results")
37144 amit 67
	public ResponseEntity<?> getSearchResults(HttpServletRequest request, @RequestParam("search_text") String search_text, @RequestParam("offset") int offset) throws ProfitMandiBusinessException {
21287 kshitij.so 68
		logger.info("search_text : "+search_text+" offset : "+offset);
69
		String jsonString = null;
70
		try {
71
			jsonString = solrService.getSearchResults(search_text.trim(), offset);
21297 kshitij.so 72
			logger.info("Response from solr "+jsonString);
21287 kshitij.so 73
		} catch (URISyntaxException | IOException e) {
74
			logger.error("Error while gettting search results from solr",e);
23022 ashik.ali 75
			responseSender.internalServerError(e);
21287 kshitij.so 76
		}
77
		JsonArray result_json = Json.parse(jsonString).asObject().get("response").asObject().get("docs").asArray();
78
		for (JsonValue j : result_json ){
79
			j.asObject().add("productUrl", j.asObject().get("ids").asArray().get(0)+"/"+j.asObject().get("id").asString());
80
		}
21297 kshitij.so 81
		Gson gson = new Gson();
82
		List<SolrSearchResultResponse> solrSearchResultResponse = gson.fromJson(result_json.toString(), new TypeToken<List<SolrSearchResultResponse>>(){}.getType());
37144 amit 83
		// collection1 docs carry no brand field, so restricted brands are dropped by title match
84
		List<String> restrictedBrands = this.restrictedBrands(request);
85
		solrSearchResultResponse = solrSearchResultResponse.stream()
86
				.filter(x -> !isBlockedTitle(x.getTitle(), restrictedBrands)).collect(Collectors.toList());
22931 ashik.ali 87
		return responseSender.ok(solrSearchResultResponse);
21287 kshitij.so 88
	}
89
 
90
 
91
	@RequestMapping(value = ProfitMandiConstants.URL_SOLR_SUGGESTION, method=RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE)
92
	@ApiImplicitParams({
35435 amit 93
		@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token",
21287 kshitij.so 94
				required = true, dataType = "string", paramType = "header")
95
	})
96
	@ApiOperation(value = "Auto Suggest")
37144 amit 97
	public ResponseEntity<?> getSuggestions(HttpServletRequest request, @RequestParam("search_text") String searchText) throws ProfitMandiBusinessException {
24995 amit.gupta 98
		logger.info("Suggestion text : "+searchText);
21287 kshitij.so 99
		String jsonString;
100
		try {
24995 amit.gupta 101
			jsonString = solrService.getSuggestions(searchText.trim());
21287 kshitij.so 102
		} catch (URISyntaxException | IOException e) {
103
			logger.error("Error while getting suggestions from solr",e);
23022 ashik.ali 104
			return responseSender.internalServerError(e);
21287 kshitij.so 105
		}
106
		result_json = Json.parse(jsonString).asObject().get("grouped").asObject();
21297 kshitij.so 107
		Gson gson = new Gson();
108
		List<SolrSuggestionResponse> solrSearchResultResponse = gson.fromJson(sanatizedResults().toString(), new TypeToken<List<SolrSuggestionResponse>>(){}.getType());
37144 amit 109
		List<String> restrictedBrands = this.restrictedBrands(request);
110
		solrSearchResultResponse = solrSearchResultResponse.stream()
111
				.filter(x -> !isBlockedTitle(x.getTitle(), restrictedBrands)).collect(Collectors.toList());
22931 ashik.ali 112
		return responseSender.ok(solrSearchResultResponse);
21287 kshitij.so 113
	}
114
 
37144 amit 115
	private List<String> restrictedBrands(HttpServletRequest request) {
116
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
117
		if (userInfo == null) {
118
			return Collections.emptyList();
119
		}
120
		try {
121
			return brandsService.restrictedBrands(userInfo.getRetailerId());
122
		} catch (ProfitMandiBusinessException e) {
123
			logger.error("Could not resolve restricted brands", e);
124
			return Collections.emptyList();
125
		}
126
	}
127
 
128
	private boolean isBlockedTitle(String title, List<String> blockedBrands) {
129
		if (title == null || blockedBrands.isEmpty()) {
130
			return false;
131
		}
132
		return blockedBrands.stream().anyMatch(x -> title.regionMatches(true, 0, x, 0, x.length())
133
				&& (title.length() == x.length() || !Character.isLetterOrDigit(title.charAt(x.length()))));
134
	}
135
 
21287 kshitij.so 136
	private JsonArray sanatizedResults(){
137
		//Need to re-write this section.This sucks badly
138
		JsonArray output = Json.array().asArray();
139
		JsonArray temp_mobiles = getResults(3);
140
		JsonArray temp_tablets = getResults(5);
141
		JsonArray temp_accesories = getResults(6);
142
		if (max_accessory_score > max_mobile_score){
143
			for (JsonValue j : temp_accesories){
144
				output.add(j);
145
			}
146
		}
147
		int toFetch = temp_accesories.size() == 0 ? 5 : 3;
148
		int count = 1;
149
		if (max_mobile_score > max_tablet_score){
150
			for (JsonValue j : temp_mobiles){
151
				if (count > toFetch)
152
					break;
153
				output.add(j);
154
				count++;
155
			}
156
			count = 1;
157
			for (JsonValue j : temp_tablets){
158
				if (count > toFetch)
159
					break;
160
				output.add(j);
161
				count++;
162
			}
163
		}
164
		else{
165
			for (JsonValue j : temp_tablets){
166
				if (count > toFetch)
167
					break;
168
				output.add(j);
169
				count++;
170
			}
171
			count = 1;
172
			for (JsonValue j : temp_mobiles){
173
				if (count > toFetch)
174
					break;
175
				output.add(j);
176
				count++;
177
			}
178
		}
179
		if (max_accessory_score <= max_mobile_score){
180
			for (JsonValue j : temp_accesories){
181
				output.add(j);
182
			}
183
		}
184
		return output;
185
	}
186
 
187
	private JsonArray getResults(int category_id){
188
 
189
		JsonArray output = new JsonArray();
190
		JsonArray suggestion;
191
		JsonArray subcat_suggestion;
192
		int count = 0;
193
 
194
		switch(category_id){
195
		case 3:
196
			suggestion= result_json.get("category_id:3").asObject().get("doclist").asObject().get("docs").asArray();
197
			mobile_records = result_json.get("category_id:3").asObject().get("doclist").asObject().get("numFound").asInt();
198
			try{
199
				max_mobile_score = result_json.get("category_id:3").asObject().get("doclist").asObject().get("maxScore").asDouble();
200
			}
201
			catch(Exception e){
202
				max_mobile_score = 0.0;
203
			}
204
			for (JsonValue item : suggestion) {
205
				if (count == max_count){
206
					break;
207
				}
208
				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());
209
				output.add(temp);
210
				count++;
211
			}
212
		case 5:
213
			suggestion = result_json.get("category_id:5").asObject().get("doclist").asObject().get("docs").asArray();
214
			tablet_records = result_json.get("category_id:5").asObject().get("doclist").asObject().get("numFound").asInt();
215
			try{
216
				max_tablet_score = result_json.get("category_id:5").asObject().get("doclist").asObject().get("maxScore").asDouble();
217
			}
218
			catch(Exception e){
219
				max_tablet_score = 0.0;
220
			}
221
			for (JsonValue item : suggestion) {
222
				if (count == max_count){
223
					break;
224
				}
225
				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());
226
				output.add(temp);
227
				count++;
228
			}
229
		case 6:
230
			subcat_suggestion = result_json.get("subCategoryId").asObject().get("groups").asArray();
231
			max_accessory_score = 0.0;
232
			for (JsonValue itemList : subcat_suggestion) {
233
				if (itemList.asObject().get("groupValue").asInt()==0){
234
					continue;
235
				}
236
				suggestion = itemList.asObject().get("doclist").asObject().get("docs").asArray();
237
				try{
238
					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;
239
				}
240
				catch(Exception e){
241
					;
242
				}
243
				count = 0;
244
				for (JsonValue item : suggestion) {
245
					if (count == max_count_accesories){
246
						break;
247
					}
248
					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"));
249
					output.add(temp);
250
					count++;
251
				}
252
			}
253
		}
254
		return output;
255
	}
256
 
257
}