KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > openedit > modules > store > StoreSearchModule


1 /*
2  * Created on Jul 19, 2006
3  */

4 package com.openedit.modules.store;
5
6 import java.text.SimpleDateFormat JavaDoc;
7 import java.util.Date JavaDoc;
8 import java.util.Iterator JavaDoc;
9 import java.util.List JavaDoc;
10
11 import org.apache.commons.logging.Log;
12 import org.apache.commons.logging.LogFactory;
13
14 import com.openedit.OpenEditException;
15 import com.openedit.WebPageRequest;
16 import com.openedit.hittracker.SearchQuery;
17 import com.openedit.modules.search.LuceneHitTracker;
18 import com.openedit.modules.search.LuceneSearchQuery;
19 import com.openedit.page.Page;
20 import com.openedit.page.PageAction;
21 import com.openedit.store.Cart;
22 import com.openedit.store.Category;
23 import com.openedit.store.Store;
24 import com.openedit.store.StoreException;
25 import com.openedit.users.User;
26 import com.openedit.util.PathUtilities;
27 import com.openedit.util.URLUtilities;
28 import com.openedit.web.Crumb;
29
30
31 public class StoreSearchModule extends BaseStoreModule
32 {
33     private static final Log log = LogFactory.getLog(StoreSearchModule.class);
34
35     /*
36     public void loadSearchFields(WebPageRequest inPageRequest) throws Exception
37     {
38         
39         String prefix = findValue("prefix", inPageRequest);
40         List keys = inPageRequest.getPage().getPageSettings().getAllPropertyKeysWithoutPrefix(prefix);
41         Store store = getStore(inPageRequest);
42         List details = new ArrayList();
43         for (Iterator iter = keys.iterator(); iter.hasNext();)
44         {
45             String key = (String) iter.next();
46             Detail detail = store.getProductArchive().getPropertyDetails().getDetail(key);
47             details.add(detail);
48         }
49         inPageRequest.putPageValue(prefix, details);
50         
51     }
52     */

53     
54     public void fieldSearch(WebPageRequest inPageRequest) throws Exception JavaDoc
55     {
56         String JavaDoc[] fieldid = inPageRequest.getRequestParameters("fieldid");
57         if ( fieldid == null)
58         {
59             return;
60         }
61         inPageRequest.removeSessionValue("crumb");
62
63         SearchQuery search = new LuceneSearchQuery();
64
65         String JavaDoc[] fields = inPageRequest.getRequestParameters("field");
66         String JavaDoc[] operations = inPageRequest.getRequestParameters("operation");
67         String JavaDoc[] values = inPageRequest.getRequestParameters("value");
68
69         String JavaDoc dateFormat = inPageRequest.getRequestParameter("dateformat");
70         if( dateFormat == null)
71         {
72             dateFormat = "MM/dd/yyyy";
73         }
74         SimpleDateFormat JavaDoc formater = new SimpleDateFormat JavaDoc(dateFormat);
75         //StringBuffer friendly = new StringBuffer();
76

77         for (int i = 0; i < fieldid.length; i++)
78         {
79             String JavaDoc field = fieldid[i];
80             String JavaDoc val = values[i];
81
82             search.putInput(field, val);
83
84             String JavaDoc friendly = null;
85             if( fields != null)
86             {
87                 friendly = fields[i];
88             }
89             else
90             {
91                 friendly = fieldid[i];
92             }
93             
94             if( val != null && val.length() > 0)
95             {
96                 String JavaDoc op = operations[i];
97                 if( "matches".equals(op))
98                 {
99                     search.addMatches( field, val, friendly);
100                 }
101                 if( "exact".equals(op))
102                 {
103                     search.addExact( field, val, friendly);
104                 }
105                 else if( "startswith".equals(op))
106                 {
107                     search.addStartsWith( field, val, friendly);
108                 }
109                 else if( "before".equals(op))
110                 {
111                     Date JavaDoc d = formater.parse(val);
112                     search.addBefore(field,d,friendly);
113                 }
114                 else if( "after".equals(op))
115                 {
116                     Date JavaDoc d = formater.parse(val);
117                     search.addAfter(field,d, friendly);
118                 }
119                 else
120                 {
121                     log.error("Unkown operation " + op);
122                 }
123             }
124         }
125         String JavaDoc defaultjoin = inPageRequest.getRequestParameter("defaultjoin");
126         if( defaultjoin != null)
127         {
128             boolean andall = Boolean.parseBoolean(defaultjoin);
129             search.setAndTogether(andall);
130             search.putInput("defaultjoin", defaultjoin);
131         }
132         String JavaDoc sort = inPageRequest.getRequestParameter("sortby");
133         search.setSortBy(sort);
134         cachedSearch(inPageRequest, search);
135         
136     }
137     public void advancedSearch(WebPageRequest inPageRequest) throws Exception JavaDoc
138     {
139         SearchQuery search = new LuceneSearchQuery();
140         search.setAndTogether(true);
141         
142         
143         String JavaDoc notwords = inPageRequest.getRequestParameter("notwords");
144         if( notwords != null)
145         {
146             String JavaDoc[] notwordsl = notwords.split("\\s");
147             for (int i = 0; i < notwordsl.length; i++)
148             {
149                 search.addNot(notwordsl[i]);
150             }
151         }
152         
153         Category catalog = null;
154         String JavaDoc catalogId = inPageRequest.getRequestParameter(CATEGORYID);
155         if( catalogId != null)
156         {
157             catalog = getStore(inPageRequest).getCatalog(catalogId);
158             if( catalog != null)
159             {
160                 search.addMatches("category",catalogId, "In Category " + catalog.getName());
161             }
162             else
163             {
164                 search.addMatches("category",catalogId, "In Category " + catalogId);
165             }
166             
167         }
168
169         String JavaDoc ands = inPageRequest.getRequestParameter("andwords");
170         if( ands != null)
171         {
172             String JavaDoc[] words = ands.split("\\s");
173             for (int i = 0; i < words.length; i++)
174             {
175                 search.addMatches(words[i]);
176             }
177         }
178         String JavaDoc quoted = inPageRequest.getRequestParameter("quotewords");
179         if( quoted != null)
180         {
181             search.addExact(quoted, "exactly");
182         
183         }
184         String JavaDoc orwords = inPageRequest.getRequestParameter("orwords");
185         if( orwords != null)
186         {
187             search.addOrsGroup(null,orwords,"or " + orwords);
188         
189         }
190         
191 // String daterange = inPageRequest.getRequestParameter("daterange");
192
// if( daterange != null)
193
// {
194
// search.addMonthRangeBeforeToday(daterange);
195
// buffer.append(daterange);
196
// buffer.append("months before");
197
//
198
// }
199
String JavaDoc userq = search.toString();
200
201         String JavaDoc filter = buildFilterString(inPageRequest.getUser(), catalog);
202         search.addFilter(filter);
203         
204         String JavaDoc fullQuery = search.toString();
205         String JavaDoc sort = inPageRequest.getRequestParameter("sortby");
206         search.setSortBy(sort);
207         cachedSearch(inPageRequest,search);
208         
209     }
210     
211     
212     public void searchCatalogs(WebPageRequest inPageRequest) throws Exception JavaDoc
213     {
214         SearchQuery search = new LuceneSearchQuery();
215         String JavaDoc catalogId = inPageRequest.getRequestParameter(CATEGORYID);
216         if (catalogId == null)
217         {
218             Page page = inPageRequest.getPage();
219             catalogId = page.get(CATEGORYID);
220         }
221         if (catalogId == null)
222         {
223             //get it from the path?
224
String JavaDoc path = inPageRequest.getPath();
225             catalogId = PathUtilities.extractPageName(path);
226         }
227     
228         //Why the content page? Page page = inPageRequest.getContentPage();
229

230         Store store = getStore(inPageRequest);
231     
232         Category catalog = store.getCatalog(catalogId);
233         if (catalog == null)
234         {
235             if (inPageRequest.getContentPage() == inPageRequest.getPage())
236             {
237                 inPageRequest.redirect(store.getStoreHome() + "/search/nosuchcatalog.html");
238             }
239             log.error("No such catalog " + catalogId);
240             return;
241         }
242         inPageRequest.putPageValue("catalog", catalog); //@deprecated
243
inPageRequest.putPageValue("category", catalog); //@deprecated
244

245         getCart(inPageRequest).setLastVisitedCatalog(catalog); //this is prone to error
246

247         boolean includechildren = false;
248         if (catalog.getParentCatalog() == null) //this is the root level
249
{
250             includechildren = true; //since products dont mark themself in the index catalog
251
}
252         //TODO: Add option to the action
253

254         String JavaDoc catalogs = catalogId;
255         String JavaDoc filter = buildFilterString(inPageRequest.getUser(), catalog);
256         if (includechildren)
257         {
258             for (Iterator JavaDoc iter = catalog.getChildren().iterator(); iter.hasNext();)
259             {
260                 Category childCatalog = (Category) iter.next();
261                 if (filter != null && filter.indexOf(childCatalog.getId()) > -1)
262                 {
263                     continue; //skip this catalog
264
}
265                 catalogs = catalogs + " OR " + childCatalog.getId();
266             }
267         }
268             search.addMatches("category", "(" + catalogs + ")", "Category matches " + catalog.getName() );//+ ") AND " + not;
269
if( filter != null )
270             {
271                 search.addFilter(filter);
272             }
273
274         Crumb crumb = store.buildCrumb(catalog);
275         inPageRequest.putSessionValue("crumb", crumb);
276     
277         PageAction action = inPageRequest.getCurrentAction();
278         
279         String JavaDoc sortBy = null;
280         if (action != null)
281         {
282             //String val = action.getChildValue("sortfield");
283
sortBy = catalog.get("sortfield");
284             if (sortBy == null || sortBy.length() < 1)
285             {
286                 sortBy = action.getChildValue("sortfield");
287             }
288         }
289         search.setSortBy(sortBy);
290         
291         cachedSearch(inPageRequest, search);
292     
293     }
294
295     /**
296      * This should all be moved to the new CatalogModule and into objects
297      * @param inPageRequest
298      */

299     public void searchStore(WebPageRequest inPageRequest) throws Exception JavaDoc
300     {
301         String JavaDoc query = inPageRequest.getRequestParameter("query");
302         String JavaDoc withincatalog = inPageRequest.getRequestParameter("department");
303         if (query == null && withincatalog == null)
304         {
305                 return;
306         }
307         inPageRequest.removeSessionValue("crumb");
308     
309         //This is used in the /base/ store /catalogs/subcatalogs/crumb.html page
310
// Crumb crumb = new Crumb();
311

312         //TODO This info should be read from the hits object instead of a crumb object
313
//TODO: Remove crumb since it is not in session and will be lost when they go to page 2
314
// crumb.setText("search " + URLUtilities.xmlEscape(query));
315
Store store = getStore(inPageRequest);
316 // crumb.setLink(store.getStoreHome() + "/search/results.html?page=1");
317
// inPageRequest.putPageValue("crumb", crumb);
318

319         //This needs to be configurable
320
// StringBuffer friendly = new StringBuffer();
321
SearchQuery search = new LuceneSearchQuery();
322         search.setAndTogether(true);
323         search.putInput("query", query);
324
325         if( query != null )
326         {
327             if( query.indexOf(" ") == -1 && query.indexOf(":") == -1 )
328             {
329                 search.addStartsWith("description",query,"description");
330             }
331             else
332             {
333                 search.addMatches(null,query,null);
334             }
335         }
336         Category department = null;
337         if (withincatalog != null && !"all".equals(withincatalog))
338         {
339             department = getStore(inPageRequest).getCatalog(withincatalog);
340             search.addMatches("category", withincatalog, " in category " + department.getName());
341  
342         }
343         Cart cart = getCart(inPageRequest);
344         cart.setLastVisitedCatalog(department);
345 // String filteren = inPageRequest.getPage().get("filtersearchenabled");
346
// if( filteren == null || Boolean.parseBoolean(filteren))
347
// {
348
String JavaDoc not = buildFilterString(inPageRequest.getUser(),department);
349             if (not != null)
350             {
351                 search.addFilter(not);
352             }
353 // }
354
String JavaDoc ordering = null;
355         if (inPageRequest.getCurrentAction() != null)
356         {
357             Category catalog = store.getCatalog(withincatalog);
358             if (catalog != null)
359             {
360                 ordering = catalog.get("sortfield");
361             }
362             if (ordering == null || ordering.length() < 1)
363             {
364                 ordering = inPageRequest.getCurrentAction().getChildValue("sortfield");
365             }
366         }
367         String JavaDoc sort = inPageRequest.getRequestParameter("sortby");
368         search.setSortBy(sort);
369         cachedSearch(inPageRequest, search);
370     }
371     
372     protected void cachedSearch(WebPageRequest inPageRequest, SearchQuery inQuery) throws StoreException, OpenEditException
373     {
374         String JavaDoc fullq = inQuery.toQuery();
375         if( fullq == null)
376         {
377             return;
378         }
379         //log.debug("Search: " + fullq);
380

381         LuceneHitTracker tracker = (LuceneHitTracker) inPageRequest.getSessionValue("hits");
382         boolean runsearch = true;
383         if (fullq != null)
384         {
385             if (tracker != null)
386             {
387                 if( inQuery.getSortBy() == null)
388                 {
389                     String JavaDoc oldSort = tracker.getOrdering();
390                     inQuery.setSortBy(oldSort);
391                 }
392                 String JavaDoc id = getStore(inPageRequest).getStoreSearcher().getIndexId();
393                 if( tracker.getIndexId().equals(id) )
394                 {
395                     if (fullq.length() == 0)
396                     {
397                         runsearch = false; //they are just going to the next page
398
}
399                     else if (fullq.equals(tracker.getQuery()))
400                     {
401                         String JavaDoc pagenumber = inPageRequest.getRequestParameter("page");
402                         if( pagenumber != null )
403                         {
404                             runsearch = false;
405                         }
406                         //duplicate search skip it
407
//tracker.setPage(1);
408
String JavaDoc cache = inPageRequest.getRequestParameter("cache");
409                         
410                         if ( cache == null || Boolean.parseBoolean(cache))
411                         {
412                             runsearch = false;
413                         }
414                     }
415                 }
416             }
417             if( runsearch )
418             {
419                 try
420                 {
421                     tracker = getStore(inPageRequest).getStoreSearcher().search(fullq, inQuery.getSortBy());
422                     tracker.setSearchQuery(inQuery);
423                     
424                     inPageRequest.putSessionValue("hits", tracker);
425                 }
426                 catch (StoreException ex)
427                 {
428                     inPageRequest.putPageValue("error", "Invalid search input. "
429                         + URLUtilities.xmlEscape(fullq));
430                     log.error(ex + " on " + fullq);
431                     inQuery.putInput("error", "Invalid search " + URLUtilities.xmlEscape(fullq));
432                 }
433             }
434         }
435     }
436
437     protected String JavaDoc buildFilterString(User inUser, Category inSelected)
438     {
439         if (inUser == null )
440         {
441             return null;
442         }
443         List JavaDoc checks = inUser.listGroupPermissions();
444         checks.addAll( inUser.getProperties().keySet() );
445
446         SearchQuery group = new LuceneSearchQuery();
447         group.setAndTogether(false);
448
449         for (Iterator JavaDoc iter = checks.iterator(); iter.hasNext();)
450         {
451             String JavaDoc name = (String JavaDoc) iter.next();
452             if (name.startsWith("limitcategory:"))
453             {
454                 String JavaDoc catId = name.substring("limitcategory:".length());
455                 group.addMatches("category", catId, null);
456             }
457         }
458         if( !group.isEmpty() )
459         {
460             return "(" + group.toString() + ")";
461         }
462         if ( inSelected == null )
463         {
464             return null;
465         }
466         SearchQuery also = group;
467
468         for (Iterator JavaDoc iter = checks.iterator(); iter.hasNext();)
469         {
470             String JavaDoc name = (String JavaDoc) iter.next();
471             if (name.startsWith("hidecategory:"))
472             {
473                 String JavaDoc catId = name.substring("hidecategory:".length());
474                 if( !inSelected.getId().startsWith(catId))
475                 {
476                     group.addNot("category", catId);
477                 }
478             }
479             else if (name.startsWith("excludecategory:"))
480             {
481                 String JavaDoc catId = name.substring("excludecategory:".length());
482                 if( !inSelected.getId().startsWith(catId))
483                 {
484                     group.addNot("category", catId);
485                 }
486             }
487             else if (name.startsWith("excluderecords:"))
488             {
489                 //Format is exclude:Field Id:value
490
String JavaDoc[] command = name.split(":");
491                 group.addNot(command[1],command[2]);
492             }
493             else if (name.startsWith("limitrecords:"))
494             {
495                 //Format is exclude:Field Id:value
496
String JavaDoc[] command = name.split(":");
497                 group.addMatches(command[1],command[2], null);
498             }
499         }
500         if( !also.isEmpty() )
501         {
502             return also.toQuery();
503         }
504         // return " NOT catalogs:( " + notfilter.substring(0, notfilter.length() - 2) + ")";
505
return null;
506     }
507
508     public Cart getCart(WebPageRequest inPageRequest) throws OpenEditException
509     {
510         Cart cart = (Cart) inPageRequest.getSessionValue("cart");
511         if (cart == null)
512         {
513             cart = new Cart(getStore(inPageRequest));
514             inPageRequest.putSessionValue("cart", cart);
515         }
516         return cart;
517     }
518
519     /**
520      * Only searches if the query does not match the page they want
521      * @param inPageRequest
522      * @throws Exception
523      */

524     public void loadPageOfSearch(WebPageRequest inPageRequest) throws Exception JavaDoc
525     {
526         String JavaDoc page = inPageRequest.getRequestParameter("page");
527     
528         if (page != null)
529         {
530             //String q = inPageRequest.getRequestParameter( "query" );
531
LuceneHitTracker tracker = (LuceneHitTracker) inPageRequest.getSessionValue("hits");
532             if (tracker != null)
533             {
534                 int jumpToPage = Integer.parseInt(page);
535                 if (jumpToPage <= tracker.getTotalPages() && jumpToPage > 0)
536                 {
537                     tracker.setPage(jumpToPage);
538                 }
539                 else
540                 {
541                     tracker.setPage(1);
542                 }
543 // Crumb crumb = new Crumb();
544
// crumb.setText("search " + URLUtilities.xmlEscape(tracker.getUserQuery()));
545
// crumb.setLink(store.getStoreHome() + "/search/results.html?page=1");
546
// inPageRequest.putPageValue("crumb", crumb);
547

548             }
549             else
550             {
551                 log.error("No search found to turn page on " + inPageRequest.getPathUrl());
552             }
553         }
554     
555     }
556
557     public void changeSort( WebPageRequest inReq ) throws Exception JavaDoc
558     {
559         String JavaDoc sort = inReq.getRequestParameter("sortby");
560         if( sort != null)
561         {
562             LuceneHitTracker tracker = (LuceneHitTracker) inReq.getSessionValue("hits");
563             if (tracker != null)
564             {
565                 SearchQuery group = tracker.getSearchQuery();
566                 group.setSortBy(sort);
567                 tracker.setIndexId(tracker.getIndexId() + sort);
568                 //inReq.removeSessionValue("hits");
569
cachedSearch(inReq, group);
570             }
571         }
572     }
573 }
574
Popular Tags