Subversion Repositories SmartDukaan

Rev

Rev 3283 | Rev 4980 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
3283 rajveer 1
package in.shop2020.serving.services;
2
 
3
 
4
import in.shop2020.model.v1.catalog.InventoryService.Client;
5
import in.shop2020.model.v1.catalog.InventoryServiceException;
6
import in.shop2020.model.v1.catalog.status;
7
import in.shop2020.model.v1.catalog.Item;
8
import in.shop2020.thrift.clients.CatalogClient;
9
 
10
import java.util.ArrayList;
11
import java.util.HashSet;
12
import java.util.List;
13
import java.util.Set;
14
 
15
import org.apache.log4j.Logger;
16
import org.apache.thrift.TException;
17
import org.apache.thrift.transport.TTransportException;
18
 
19
/**
20
 * 
21
 * @author rajveer
22
 * 
23
 * Auto suggest service will help user to search some term. This is based on turnary search tree. 
24
 */
25
public class AutoSuggestService
26
{
27
	private Node root;
28
	private static Logger log = Logger.getLogger(AutoSuggestService.class);
29
	private static AutoSuggestService autoSuggestService;
30
 
31
	static{
32
		synchronized(AutoSuggestService.class){
33
			autoSuggestService = new AutoSuggestService();
34
			autoSuggestService.initialize();
35
		}
36
	}
37
	private void initialize() {
38
		log.info("Starting instance of Autosuggest service");
39
		CatalogClient catalogServiceClient;
40
		try {
41
			catalogServiceClient = new CatalogClient();
42
			Client client = catalogServiceClient.getClient();
43
	        List<Item> items = new ArrayList<Item>();
44
	        items.addAll(client.getAllItemsByStatus(status.ACTIVE));
45
	        items.addAll(client.getAllItemsByStatus(status.PAUSED));
46
	        items.addAll(client.getAllItemsByStatus(status.PAUSED_BY_RISK));
47
	        Set<Long> processedSet = new HashSet<Long>();
48
	        for(Item item: items){
49
	        	if(!processedSet.contains(item.getCatalogItemId())){
50
	        		processedSet.add(item.getCatalogItemId());
51
	        		addItemName(AutoSuggestService.getProductTitle(item));
52
	        	}
53
	        }
54
		} catch (TTransportException e) {
55
			log.error("Error while making thrift connection", e);
56
		} catch (InventoryServiceException e) {
57
			log.error("Inventory Service exception", e);
58
		} catch (TException e) {
59
			log.error("Thrift exception", e);
60
		}
61
		log.info("Done with starting Autosuggest service");
62
	}
63
 
64
	public static AutoSuggestService getAutoSuggestServiceInstance(){
65
		return autoSuggestService;
66
	}
67
 
68
	/**
69
	 * Get the title of the product from catalog service.
70
	 * @param item
71
	 * @return
72
	 */
73
	private static String getProductTitle(Item item){
74
		String title = ((item.getBrand() != null) ? item.getBrand().trim() + " " : "")
75
		+ ((item.getModelName() != null) ? item.getModelName().trim() + " " : "")
76
		+ (( item.getModelNumber() != null ) ? item.getModelNumber().trim() : "" );
77
		title = title.replaceAll("  ", " ");
78
		return title;
79
	}
80
 
81
	private Node addChars(char[] s, int position, Node node, String string)
82
    {
83
        if (node == null) { 
84
        	node = new Node(s[position], null); 
85
        }
4975 phani.kuma 86
        if (s[position] < node.storedChar) {
3283 rajveer 87
        	node.left = addChars(s, position, node.left, string); 
88
        }
4975 phani.kuma 89
        else if (s[position] > node.storedChar) {
3283 rajveer 90
        	node.right = addChars(s, position, node.right, string); 
4975 phani.kuma 91
        }
92
        else {
93
        	if (position + 1 == s.length) {
94
        		node.addItem(string);
3283 rajveer 95
        	}
4975 phani.kuma 96
        	else {
97
        		node.center =  addChars(s, position + 1, node.center, string);
3283 rajveer 98
        	}
4975 phani.kuma 99
        }
3283 rajveer 100
        return node;
101
    }
102
 
103
    public void addStringPart(String part, String string)
104
    {
105
        if (part == null || part == "") return;
106
        root = addChars(part.toCharArray(), 0, root, string);
107
    }
108
 
109
    /**
110
     * Add String to the tree
111
     * @param string
112
     */
113
    private void addItemName(String string) {
114
        if (string == null || string == "") return;
115
        String[] parts = string.trim().toLowerCase().split("\\s+");
116
        for(String part : parts){
117
        	addStringPart(part, string);
118
        }
119
    }
120
 
121
    /**
122
     * Get list of matching product names.
123
     * @param str
124
     * @param resultCount
125
     * @return
126
     */
127
    public List<String> getMatchingQueries(String str, int resultCount){
128
    	Set<String> totalSet = new HashSet<String>();
129
    	String[] parts = str.trim().toLowerCase().split("\\s+");
130
        for(String part : parts){
131
        	Node node = getPartialMatchNode(part);
132
        	Set<String> set = new HashSet<String>();
133
        	getChildElements(node, set);
134
        	if(totalSet.isEmpty()){
135
        		totalSet.addAll(set);	
136
        	}else{
137
        		totalSet.retainAll(set);
138
        	}
139
        }
140
        List<String> items = new ArrayList<String>(totalSet);
141
        if(items.size() > resultCount){
142
        	return items.subList(0, resultCount-1);
143
        }else{
144
        	return items;	
145
        }
146
    }
147
 
148
    /**
149
     * Return the node till which we are able to match the word.
150
     * @param str
151
     * @return
152
     */
153
    private Node getPartialMatchNode(String str){
154
	    char[] s = str.toCharArray();
155
	    int pos = 0;
156
	    Node node = root;
157
	    while (node != null)
158
	    {
159
	        if (s[pos] < node.storedChar) { node = node.left; }
160
	        else if (s[pos] > node.storedChar) { node = node.right; }
161
	        else
162
	        {
163
	            if (++pos == s.length){
164
	            	if(node.center==null){
165
	            		return node;
166
	            	}else{
167
	            		return node.center;
168
	            	}
169
	            }
170
	            node = node.center;
171
	        }
172
	    }
173
	    return node;
174
    }
175
 
176
    private void getChildElements(Node node, Set<String>  set){
177
    	if(node == null){
178
    		return;
179
    	}
4975 phani.kuma 180
    	if(node.itemSet != null && !node.itemSet.isEmpty()){
181
    		set.addAll(node.itemSet);
3283 rajveer 182
    	}
4975 phani.kuma 183
    	getChildElements(node.center, set);	
3283 rajveer 184
    	getChildElements(node.left, set);
185
    	getChildElements(node.right, set);
186
    }
187
 
188
 
189
	@Override
190
	public String toString() {
191
		return "AutoSuggest [root=" + root + "]";
192
	}
193
 
194
	public static void main(String[] args) throws Exception {
195
		AutoSuggestService as = new AutoSuggestService();
196
		as.addItemName("Nokia N8");
197
		as.addItemName("Nokia C5-00");
198
		as.addItemName("Nokia C3-00");
199
		as.addItemName("Nokia X2-01");
200
		as.addItemName("Samsung Galaxy Pro");
201
		as.addItemName("Samsung Galaxy Pop");
202
		as.addItemName("Samsung Galaxy 551 I5510");
203
		System.out.println(as.getMatchingQueries("noki", 10));
204
		System.out.println(as.getMatchingQueries("nok", 10));
205
		System.out.println(as.getMatchingQueries("n8", 10));
206
		System.out.println(as.getMatchingQueries("po gala", 10));
207
	}
208
}
209
 
210
class Node
211
{
212
	char storedChar;
213
    Node left, center, right;
214
    Set<String> itemSet;
215
 
216
    public void addItem(String itemName){
217
    	if(itemSet == null || itemSet.isEmpty()){
218
    		itemSet = new HashSet<String>();
219
    	}
220
    	itemSet.add(itemName);
221
    }
222
    public Node(char ch, String itemName)
223
    {
224
        this.storedChar = ch;
225
        if(itemName != null){
226
        	itemSet = new HashSet<String>();
227
        	itemSet.add(itemName);
228
        }
229
    }
230
	@Override
231
	public String toString() {
232
		return "Node [storedChar=" + storedChar + ", left=" + left
233
				+ ", center=" + center + ", right=" + right + ", itemSet="
234
				+ itemSet + "]";
235
	}   
236
}