Subversion Repositories SmartDukaan

Rev

Rev 4975 | Rev 5017 | 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){
4980 phani.kuma 164
	            	return node;
3283 rajveer 165
	            }
166
	            node = node.center;
167
	        }
168
	    }
169
	    return node;
170
    }
171
 
172
    private void getChildElements(Node node, Set<String>  set){
173
    	if(node == null){
174
    		return;
175
    	}
4975 phani.kuma 176
    	if(node.itemSet != null && !node.itemSet.isEmpty()){
177
    		set.addAll(node.itemSet);
3283 rajveer 178
    	}
4975 phani.kuma 179
    	getChildElements(node.center, set);	
3283 rajveer 180
    	getChildElements(node.left, set);
181
    	getChildElements(node.right, set);
182
    }
183
 
184
 
185
	@Override
186
	public String toString() {
187
		return "AutoSuggest [root=" + root + "]";
188
	}
189
 
190
	public static void main(String[] args) throws Exception {
191
		AutoSuggestService as = new AutoSuggestService();
192
		as.addItemName("Nokia N8");
193
		as.addItemName("Nokia C5-00");
194
		as.addItemName("Nokia C3-00");
195
		as.addItemName("Nokia X2-01");
196
		as.addItemName("Samsung Galaxy Pro");
197
		as.addItemName("Samsung Galaxy Pop");
198
		as.addItemName("Samsung Galaxy 551 I5510");
199
		System.out.println(as.getMatchingQueries("noki", 10));
200
		System.out.println(as.getMatchingQueries("nok", 10));
201
		System.out.println(as.getMatchingQueries("n8", 10));
202
		System.out.println(as.getMatchingQueries("po gala", 10));
203
	}
204
}
205
 
206
class Node
207
{
208
	char storedChar;
209
    Node left, center, right;
210
    Set<String> itemSet;
211
 
212
    public void addItem(String itemName){
213
    	if(itemSet == null || itemSet.isEmpty()){
214
    		itemSet = new HashSet<String>();
215
    	}
216
    	itemSet.add(itemName);
217
    }
218
    public Node(char ch, String itemName)
219
    {
220
        this.storedChar = ch;
221
        if(itemName != null){
222
        	itemSet = new HashSet<String>();
223
        	itemSet.add(itemName);
224
        }
225
    }
226
	@Override
227
	public String toString() {
228
		return "Node [storedChar=" + storedChar + ", left=" + left
229
				+ ", center=" + center + ", right=" + right + ", itemSet="
230
				+ itemSet + "]";
231
	}   
232
}