Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
20424 kshitij.so 1
package com.hotspotstore.services;
2
 
3
 
4
 
5
import java.io.File;
6
import java.util.ArrayList;
7
import java.util.HashMap;
8
import java.util.HashSet;
9
import java.util.List;
10
import java.util.Map;
11
import java.util.Map.Entry;
12
import java.util.Set;
13
 
14
import org.apache.commons.io.FileUtils;
15
import org.apache.log4j.Logger;
16
 
17
import com.google.gson.Gson;
18
import com.google.gson.reflect.TypeToken;
19
 
20
/**
21
 * 
22
 * @author rajveer
23
 * 
24
 * Auto suggest service will help user to search some term. This is based on turnary search tree. 
25
 */
26
public class AutoSuggestService
27
{
28
	private Node root;
29
	private static Logger log = Logger.getLogger(AutoSuggestService.class);
30
	private static AutoSuggestService autoSuggestService;
31
	private static final String EXPORT_JAVASCRIPT_CONTENT_PATH="/var/lib/tomcat6/webapps/export/javascripts/";
32
 
33
	static{
34
		synchronized(AutoSuggestService.class){
35
			autoSuggestService = new AutoSuggestService();
36
			autoSuggestService.initialize();
37
		}
38
	}
39
 
40
	private void initialize() {
41
		log.info("Starting instance of Autosuggest service");
42
		try {
43
			Gson g = new Gson();
44
			java.lang.reflect.Type typeOfT = new TypeToken<Map<String, List<String>>>(){}.getType();
20591 kshitij.so 45
			Map<String, List<String>> synonyms = g.fromJson(FileUtils.readFileToString(new File(EXPORT_JAVASCRIPT_CONTENT_PATH + "autosuggesthotspot.json")), typeOfT);
20424 kshitij.so 46
			if(synonyms != null){
47
				for(Entry<String, List<String>> entry : synonyms.entrySet()){
48
					for(String title : entry.getValue()){
49
						addItemName(title, entry.getKey());
50
					}
51
				}
52
			}
53
		} catch (Exception e) {
54
			log.error("", e);
55
		}
56
		log.info("Done with starting Autosuggest service");
57
	}
58
 
59
	public static AutoSuggestService getAutoSuggestServiceInstance(){
60
		return autoSuggestService;
61
	}
62
 
63
	private Node addChars(char[] s, int position, Node node, String string, String displaystring)
64
    {
65
        if (node == null) { 
66
        	node = new Node(s[position], null, null); 
67
        }
68
        if (s[position] < node.storedChar) {
69
        	node.left = addChars(s, position, node.left, string, displaystring); 
70
        }
71
        else if (s[position] > node.storedChar) {
72
        	node.right = addChars(s, position, node.right, string, displaystring); 
73
        }
74
        else {
75
        	if (position + 1 == s.length) {
76
        		node.addItem(string, displaystring);
77
        	}
78
        	else {
79
        		node.center =  addChars(s, position + 1, node.center, string, displaystring);
80
        	}
81
        }
82
        return node;
83
    }
84
 
85
    public void addStringPart(String part, String string, String displaystring)
86
    {
87
        if (part == null || part == "") return;
88
        root = addChars(part.toCharArray(), 0, root, string, displaystring);
89
    }
90
 
91
    /**
92
     * Add String to the tree
93
     * @param string
94
     */
95
    private void addItemName(String string, String displayString) {
96
        if (string == null || string == "") return;
97
        String[] parts = string.trim().toLowerCase().split("\\s+");
98
        for(String part : parts){
99
        	addStringPart(part, string, displayString);
100
        }
101
    }
102
 
103
    /**
104
     * Get list of matching product names.
105
     * @param str
106
     * @param resultCount
107
     * @return
108
     */
109
    public List<String> getMatchingQueries(String str, int resultCount){
110
    	Set<String> totalSet = new HashSet<String>();
111
    	String[] parts = str.trim().toLowerCase().split("\\s+");
112
        for(String part : parts){
113
        	Node node = getPartialMatchNode(part);
114
        	Set<String> set = new HashSet<String>();
115
        	getChildElements(node, set, part);
116
        	if(totalSet.isEmpty()){
117
        		totalSet.addAll(set);
118
        	}else{
119
        		totalSet.retainAll(set);
120
        	}
121
        }
122
        List<String> items = new ArrayList<String>(totalSet);
123
        if(items.size() > resultCount){
124
        	return items.subList(0, resultCount-1);
125
        }else{
126
        	return items;	
127
        }
128
    }
129
 
130
    /**
131
     * Return the node till which we are able to match the word.
132
     * @param str
133
     * @return
134
     */
135
    private Node getPartialMatchNode(String str){
136
	    char[] s = str.toCharArray();
137
	    int pos = 0;
138
	    Node node = root;
139
	    while (node != null)
140
	    {
141
	        if (s[pos] < node.storedChar) { node = node.left; }
142
	        else if (s[pos] > node.storedChar) { node = node.right; }
143
	        else
144
	        {
145
	            if (++pos == s.length){
146
	            	return node;
147
	            }
148
	            node = node.center;
149
	        }
150
	    }
151
	    return node;
152
    }
153
 
154
    private void getChildElements(Node node, Set<String>  set, String str){
155
    	if(node == null){
156
    		return;
157
    	}
158
    	if(node.itemMap != null && !node.itemMap.isEmpty()){
159
    		for(Entry<String, String> entry : node.itemMap.entrySet()) {
160
    			String item_name = entry.getKey();
161
    			String item_displayname = entry.getValue();
162
    			String ignore_item_name = item_name.toLowerCase();
163
    			if(ignore_item_name.indexOf(str) != -1){
164
    				set.add(item_displayname);
165
    			}
166
    		}
167
    	}
168
    	getChildElements(node.center, set, str);	
169
    	getChildElements(node.left, set, str);
170
    	getChildElements(node.right, set, str);
171
    }
172
 
173
 
174
	@Override
175
	public String toString() {
176
		return "AutoSuggest [root=" + root + "]";
177
	}
178
 
179
	public static void main(String[] args) throws Exception {
180
		AutoSuggestService as = new AutoSuggestService();
181
		as.addItemName("Nokia N8", "Nokia N");
182
		as.addItemName("Nokia C5-00", "Nokia C5");
183
		as.addItemName("Nokia C3-00", "Nokia C3");
184
		as.addItemName("Nokia X2-01", "Nokia X2");
185
		as.addItemName("Samsung Galaxy Pro", "Samsung Galaxy Pro");
186
		as.addItemName("Samsung Galaxy Pop", "Samsung Galaxy Pop");
187
		as.addItemName("Samsung Galaxy 551 I5510", "Samsung Galaxy 551");
188
		System.out.println(as.getMatchingQueries("noki", 10));
189
		System.out.println(as.getMatchingQueries("nok", 10));
190
		System.out.println(as.getMatchingQueries("Nokia", 10));
191
		System.out.println(as.getMatchingQueries("n8", 10));
192
		System.out.println(as.getMatchingQueries("po gala", 10));
193
	}
194
}
195
 
196
class Node
197
{
198
	char storedChar;
199
    Node left, center, right;
200
    Map<String, String> itemMap;
201
 
202
    public void addItem(String itemName, String itemDisplayName){
203
    	if(itemMap == null || itemMap.isEmpty()){
204
    		itemMap = new HashMap<String, String>();
205
    	}
206
    	itemMap.put(itemName, itemDisplayName);
207
    }
208
    public Node(char ch, String itemName, String itemDisplayName)
209
    {
210
        this.storedChar = ch;
211
        if(itemName != null){
212
        	itemMap = new HashMap<String, String>();
213
        	itemMap.put(itemName, itemDisplayName);
214
        }
215
    }
216
	@Override
217
	public String toString() {
218
		return "Node [storedChar=" + storedChar + ", left=" + left
219
				+ ", center=" + center + ", right=" + right + ", itemMap="
220
				+ itemMap + "]";
221
	}   
222
}