KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > opencms > workplace > tools > searchindex > CmsSearchWidgetDialog


1 /*
2  * File : $Source: /usr/local/cvs/opencms/src-modules/org/opencms/workplace/tools/searchindex/CmsSearchWidgetDialog.java,v $
3  * Date : $Date: 2006/09/22 12:51:38 $
4  * Version: $Revision: 1.5 $
5  *
6  * This library is part of OpenCms -
7  * the Open Source Content Mananagement System
8  *
9  * Copyright (c) 2005 Alkacon Software GmbH (http://www.alkacon.com)
10  *
11  * This library is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public
13  * License as published by the Free Software Foundation; either
14  * version 2.1 of the License, or (at your option) any later version.
15  *
16  * This library is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19  * Lesser General Public License for more details.
20  *
21  * For further information about Alkacon Software GmbH, please see the
22  * company website: http://www.alkacon.com
23  *
24  * For further information about OpenCms, please see the
25  * project website: http://www.opencms.org
26  *
27  * You should have received a copy of the GNU Lesser General Public
28  * License along with this library; if not, write to the Free Software
29  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
30  */

31
32 package org.opencms.workplace.tools.searchindex;
33
34 import org.opencms.i18n.CmsMessages;
35 import org.opencms.jsp.CmsJspActionElement;
36 import org.opencms.search.CmsSearch;
37 import org.opencms.search.CmsSearchParameters;
38 import org.opencms.util.CmsStringUtil;
39 import org.opencms.widgets.CmsCheckboxWidget;
40 import org.opencms.widgets.CmsDisplayWidget;
41 import org.opencms.widgets.CmsInputWidget;
42 import org.opencms.widgets.CmsSelectWidget;
43 import org.opencms.widgets.CmsSelectWidgetOption;
44 import org.opencms.widgets.CmsVfsFileWidget;
45 import org.opencms.workplace.CmsDialog;
46 import org.opencms.workplace.CmsWidgetDialogParameter;
47 import org.opencms.workplace.CmsWorkplaceSettings;
48
49 import java.util.Iterator JavaDoc;
50 import java.util.LinkedList JavaDoc;
51 import java.util.List JavaDoc;
52 import java.util.Map JavaDoc;
53
54 import javax.servlet.http.HttpServletRequest JavaDoc;
55 import javax.servlet.http.HttpServletResponse JavaDoc;
56 import javax.servlet.jsp.PageContext JavaDoc;
57
58 /**
59  * A <code>{@link org.opencms.workplace.CmsWidgetDialog}</code> that performs a
60  * search on the <code>{@link org.opencms.search.CmsSearchIndex}</code> identified
61  * by request parameter
62  * <code>{@link org.opencms.workplace.tools.searchindex.A_CmsEditSearchIndexDialog#PARAM_INDEXNAME}</code>
63  * using an instance of <code>{@link org.opencms.search.CmsSearchParameters}</code>
64  * as widget object to fill.
65  * <p>
66  *
67  * @author Achim Westermann
68  *
69  * @version $Revision: 1.5 $
70  *
71  * @since 6.0.0
72  */

73 public class CmsSearchWidgetDialog extends A_CmsEditSearchIndexDialog {
74
75     /** The request parameter for the search object. **/
76     public static final String JavaDoc PARAM_SEARCH_OBJECT = "searchobject";
77
78     /** The request parameter for the search parameters. **/
79     public static final String JavaDoc PARAM_SEARCH_PARAMS = "searchparams";
80
81     /** The search instance used with the search parameters. **/
82     protected CmsSearch m_search;
83
84     /** The search parameter instance used for storing widget values and performing search. */
85     protected CmsSearchParameters m_searchParams;
86
87     /**
88      * Public constructor with JSP action element.<p>
89      *
90      * @param jsp an initialized JSP action element
91      */

92     public CmsSearchWidgetDialog(CmsJspActionElement jsp) {
93
94         super(jsp);
95
96     }
97
98     /**
99      * Public constructor with JSP variables.<p>
100      *
101      * @param context the JSP page context
102      * @param req the JSP request
103      * @param res the JSP response
104      */

105     public CmsSearchWidgetDialog(PageContext JavaDoc context, HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc res) {
106
107         this(new CmsJspActionElement(context, req, res));
108
109     }
110
111     /**
112      * Overrides this action that is performed in case an element
113      * has been added to a widget parameter
114      * (<code>{@link org.opencms.workplace.CmsWidgetDialog#ACTION_ELEMENT_ADD}</code>)
115      * or removed
116      * (<code>{@link org.opencms.workplace.CmsWidgetDialog#ACTION_ELEMENT_ADD}</code>) or removed
117      * from a widget parameter to additionally commit these values to the
118      * underlying lists.<p>
119      *
120      * This is necessary because this dialog performs a search for every request
121      * (not only if OK is pressed, also if a category or field is added/removed).
122      * The search directly uses the underlying Lists of categories, fields,... .
123      * More precise: The very same lists that are in the search parameter instance used
124      * for search are contained as base collections of the widget parameters.
125      * Therefore before every search the changes of categories, fields,... have to
126      * be committed here.<p>
127      *
128      * @see org.opencms.workplace.CmsWidgetDialog#actionToggleElement()
129      */

130     public void actionToggleElement() {
131
132         super.actionToggleElement();
133         commitWidgetValues();
134     }
135
136     /**
137      * Builds the standard javascript for submitting the dialog.<p>
138      *
139      * Overridden to allow additional validation and encoding of the
140      * search query. <p>
141      *
142      * @return the standard javascript for submitting the dialog
143      */

144     public String JavaDoc dialogScriptSubmit() {
145
146         StringBuffer JavaDoc html = new StringBuffer JavaDoc(512);
147         html.append(submitJS());
148         html.append("function submitAction(actionValue, theForm, formName) {\n");
149         html.append("\tif (theForm == null) {\n");
150         html.append("\t\ttheForm = document.forms[formName];\n");
151         html.append("\t}\n");
152         html.append("\tvar queryOK = validateQuery();\n");
153         html.append("\ttheForm." + CmsDialog.PARAM_FRAMENAME + ".value = window.name;\n");
154         html.append("\tif (queryOK) {\n");
155         html.append("\t\tif (actionValue == '" + CmsDialog.DIALOG_OK + "') {\n");
156         // html.append("\t\t\talert('action :'+actionValue);\n");
157
html.append("\t\t\tloadingOn();\n");
158         html.append("\t\t\treturn queryOK;\n");
159         html.append("\t\t}\n");
160         html.append("\t\ttheForm." + CmsDialog.PARAM_ACTION + ".value = actionValue;\n");
161         html.append("\t\tsubmitForm(theForm);\n");
162         html.append("\t}\n");
163         html.append("\treturn queryOK;\n");
164         html.append("}\n");
165         return html.toString();
166     }
167
168     /**
169      * This dialog does not return on commit but stay for many search requests until it is
170      * exited with cancel or up in the workplace. <p>
171      *
172      * @return false always to ensure the dialog is not left
173      *
174      * @see org.opencms.workplace.CmsWidgetDialog#closeDialogOnCommit()
175      */

176     protected boolean closeDialogOnCommit() {
177
178         return false;
179     }
180
181     /**
182      * @see org.opencms.workplace.CmsWidgetDialog#createDialogHtml(java.lang.String)
183      */

184     protected String JavaDoc createDialogHtml(String JavaDoc dialog) {
185
186         StringBuffer JavaDoc result = new StringBuffer JavaDoc(1024);
187
188         result.append(createWidgetTableStart());
189         // show error header once if there were validation errors
190
result.append(createWidgetErrorHeader());
191
192         if (dialog.equals(PAGES[0])) {
193
194             // first block "Query for index...."
195
result.append(dialogBlockStart(key(Messages.GUI_LABEL_SEARCHINDEX_BLOCK_SEARCH_QUERY_0)));
196             result.append(createWidgetTableStart());
197             result.append(createDialogRowsHtml(0, 5));
198             result.append(createWidgetTableEnd());
199             result.append(dialogBlockEnd());
200
201             // 2nd block "Fields to search in"
202
result.append(dialogBlockStart(key(Messages.GUI_LABEL_SEARCHINDEX_BLOCK_SEARCH_FIELDS_0)));
203             result.append(createWidgetTableStart());
204             result.append(createDialogRowsHtml(6, 10));
205             result.append(createWidgetTableEnd());
206             result.append(dialogBlockEnd());
207         }
208
209         result.append(createWidgetTableEnd());
210
211         return result.toString();
212     }
213
214     /**
215      * Returns the html code for the default action content.<p>
216      *
217      * Overrides <code> {@link org.opencms.workplace.CmsWidgetDialog#defaultActionHtml()}</code>
218      * in order to put additional forms for page links and search results after OK - CANCEL buttons
219      * and outside the main form.<p>
220      *
221      * @return html code
222      */

223     protected String JavaDoc defaultActionHtmlContent() {
224
225         StringBuffer JavaDoc result = new StringBuffer JavaDoc(2048);
226         result.append("<form name=\"EDITOR\" id=\"EDITOR\" method=\"post\" action=\"").append(getDialogUri());
227         result.append("\" class=\"nomargin\" onsubmit=\"return submitAction('").append(DIALOG_OK).append(
228             "', null, 'EDITOR');\">\n");
229         result.append(dialogContentStart(null));
230         result.append(buildDialogForm());
231         result.append(dialogContentEnd());
232         result.append(dialogButtonsCustom());
233         result.append(paramsAsHidden());
234         if (getParamFramename() == null) {
235             result.append("\n<input type=\"hidden\" name=\"").append(PARAM_FRAMENAME).append("\" value=\"\">\n");
236         }
237
238         // add script for filtering categories
239
result.append(filterCategoryJS());
240         result.append("</form>\n");
241
242         // get search results if query was more than nothing
243
// we have to retrieve them before category search results are available because
244
// those are collected as a side effect of search iteration.
245
String JavaDoc searchResults = createSearchResults();
246
247         // append category search results if there...
248
result.append(createCategorySearchResultHtml());
249         result.append(searchResults);
250
251         result.append(getWidgetHtmlEnd());
252         // Normalize the previous encoded query value on client side
253
result.append(normalizePreviousQueryJS());
254
255         return result.toString();
256     }
257
258     /**
259      *
260      * @see org.opencms.workplace.CmsWidgetDialog#defineWidgets()
261      */

262     protected void defineWidgets() {
263
264         // initialization -> initUserObject
265
super.defineWidgets();
266         // first block "Query for search index..."
267
addWidget(new CmsWidgetDialogParameter(m_searchParams, "index", "", PAGES[0], new CmsDisplayWidget(), 1, 1));
268         addWidget(new CmsWidgetDialogParameter(m_searchParams, "query", "", PAGES[0], new CmsInputWidget(), 1, 1));
269         addWidget(new CmsWidgetDialogParameter(m_searchParams, "sortName", "", PAGES[0], new CmsSelectWidget(
270             getSortWidgetConfiguration()), 0, 1));
271         addWidget(new CmsWidgetDialogParameter(
272             m_searchParams.getRoots(),
273             "roots",
274             "/",
275             PAGES[0],
276             new CmsVfsFileWidget(),
277             1,
278             10));
279         addWidget(new CmsWidgetDialogParameter(
280             m_searchParams.getCategories(),
281             "categories",
282             "",
283             PAGES[0],
284             new CmsInputWidget(),
285             0,
286             6));
287
288         addWidget(new CmsWidgetDialogParameter(m_searchParams, "calculateCategories", new CmsCheckboxWidget()));
289
290         // 2nd block "fields to search in"
291
addWidget(new CmsWidgetDialogParameter(m_searchParams, "searchFieldContent", new CmsCheckboxWidget()));
292         addWidget(new CmsWidgetDialogParameter(m_searchParams, "searchFieldMeta", new CmsCheckboxWidget()));
293         addWidget(new CmsWidgetDialogParameter(m_searchParams, "searchFieldTitle", new CmsCheckboxWidget()));
294         addWidget(new CmsWidgetDialogParameter(m_searchParams, "searchFieldKeywords", new CmsCheckboxWidget()));
295         addWidget(new CmsWidgetDialogParameter(m_searchParams, "searchFieldDescription", new CmsCheckboxWidget()));
296
297     }
298
299     /**
300      * Overridden to additionally get a hold on the widget object of type
301      * <code>{@link CmsSearchParameters}</code>.<p>
302      *
303      * @see org.opencms.workplace.tools.searchindex.A_CmsEditSearchIndexDialog#initUserObject()
304      */

305     protected void initUserObject() {
306
307         super.initUserObject();
308         Object JavaDoc o = getDialogObject();
309         if (o == null) {
310             m_searchParams = new CmsSearchParameters();
311             // implant a hook upon modifications of the list
312
// this will set the search page to 1 if a restriction to the set of categories is performed
313
m_searchParams.setCategories(new CmsHookListSearchCategory(m_searchParams, m_searchParams.getCategories()));
314             m_search = new CmsSearch();
315         } else {
316             Map JavaDoc dialogObject = (Map JavaDoc)o;
317             m_searchParams = (CmsSearchParameters)dialogObject.get(PARAM_SEARCH_PARAMS);
318             if (m_searchParams == null) {
319                 m_searchParams = new CmsSearchParameters();
320             }
321             m_search = (CmsSearch)dialogObject.get(PARAM_SEARCH_OBJECT);
322             if (m_search == null) {
323                 m_search = new CmsSearch();
324             }
325         }
326         m_searchParams.setSearchIndex(m_index);
327     }
328
329     /**
330      * Additionally saves <code>{@link #PARAM_SEARCH_PARAMS}</code> to the dialog object map.<p>
331      *
332      * @see org.opencms.workplace.CmsWorkplace#initWorkplaceRequestValues(org.opencms.workplace.CmsWorkplaceSettings, javax.servlet.http.HttpServletRequest)
333      */

334     protected void initWorkplaceRequestValues(CmsWorkplaceSettings settings, HttpServletRequest JavaDoc request) {
335
336         super.initWorkplaceRequestValues(settings, request);
337         Map JavaDoc dialogMap = (Map JavaDoc)getDialogObject();
338         if (dialogMap != null) {
339             dialogMap.put(PARAM_SEARCH_PARAMS, m_searchParams);
340             dialogMap.put(PARAM_SEARCH_OBJECT, m_search);
341         }
342
343     }
344
345     /**
346      * Returns the hmtl for the category search results.<p>
347      *
348      * Note that a valid search (<code>{@link CmsSearch#getSearchResult()}</code> with
349      * correct settings and inited) has to be triggered before this call or an empty
350      * String will be returned. <p>
351      *
352      * @param search the preconfigured search bean
353      *
354      * @return the hmtl for the category search results
355      */

356     private String JavaDoc createCategorySearchResultHtml() {
357
358         StringBuffer JavaDoc result = new StringBuffer JavaDoc();
359         if (m_searchParams.isCalculateCategories()) {
360             // trigger calculation of categories, even if we don't need search results
361
// this is cached unless more set operation on CmsSearch are performed
362
Map JavaDoc categoryMap = m_search.getSearchResultCategories();
363             if (categoryMap != null) {
364                 result.append(dialogContentStart(null));
365                 result.append(result.append(createWidgetTableStart()));
366                 // first block "Query for index...."
367
result.append(dialogBlockStart(key(
368                     Messages.GUI_LABEL_SEARCHINDEX_BLOCK_SEARCH_CATEGORIES_1,
369                     new Object JavaDoc[] {m_searchParams.getQuery()})));
370                 result.append(createWidgetTableStart());
371
372                 // categories:
373
result.append("\n<p>\n");
374                 Map.Entry JavaDoc entry;
375                 Iterator JavaDoc it = categoryMap.entrySet().iterator();
376                 while (it.hasNext()) {
377                     entry = (Map.Entry JavaDoc)it.next();
378                     result.append(" ").append("<a class=\"searchcategory\" HREF=\"#\" onClick=\"filterCategory('");
379                     result.append(entry.getKey()).append("')\")>");
380                     result.append(entry.getKey());
381                     result.append("</a> : ");
382                     result.append(entry.getValue()).append("<br>\n");
383                 }
384                 result.append("</p>\n");
385
386                 result.append(createWidgetTableEnd());
387                 result.append(dialogBlockEnd());
388                 result.append(createWidgetTableEnd());
389                 result.append(dialogContentEnd());
390             }
391         }
392         return result.toString();
393     }
394
395     private String JavaDoc createSearchResults() {
396
397         String JavaDoc query = m_searchParams.getQuery();
398         StringBuffer JavaDoc result = new StringBuffer JavaDoc();
399         if (!CmsStringUtil.isEmptyOrWhitespaceOnly(query) && query.length() > 3) {
400             CmsSearchResultView resultView = new CmsSearchResultView(getJsp());
401             // proprietary workplace admin link for pagelinks of search:
402
resultView.setSearchRessourceUrl(getJsp().link(
403                 "/system/workplace/views/admin/admin-main.jsp?path=/searchindex/singleindex/search&indexname="
404                     + m_index.getName()));
405             m_search.init(getCms());
406
407             // custom parameters (non-widget controlled)
408
// these are from generated search page links
409
String JavaDoc page = getJsp().getRequest().getParameter("searchPage");
410             if (!CmsStringUtil.isEmptyOrWhitespaceOnly(page)) {
411                 m_searchParams.setSearchPage(Integer.parseInt(page));
412             }
413             String JavaDoc categories = getJsp().getRequest().getParameter("searchCategories");
414             if (!CmsStringUtil.isEmptyOrWhitespaceOnly(categories)) {
415                 m_searchParams.setCategories(CmsStringUtil.splitAsList(categories, ','));
416             }
417
418             String JavaDoc searchRoots = getJsp().getRequest().getParameter("searchRoots");
419             if (!CmsStringUtil.isEmptyOrWhitespaceOnly(searchRoots)) {
420                 m_searchParams.setSearchRoots(searchRoots);
421             }
422             m_search.setParameters(m_searchParams);
423             result.append("<div style=\"padding:12px;\">\n").append(resultView.displaySearchResult(m_search)).append(
424                 "\n</div>\n");
425         } else {
426             // Just don't perform search
427
}
428         return result.toString();
429     }
430
431     private String JavaDoc filterCategoryJS() {
432
433         StringBuffer JavaDoc result = new StringBuffer JavaDoc();
434         // fool the widget with a hidden categories input field
435
result.append("<input name=\"dummysearchcategory\" id=\"dummysearchcategory\" type=\"hidden\" value=\"\">\n");
436         result.append("<input name=\"dummysearchpage\" id=\"dummysearchpage\" type=\"hidden\" value=\"\">\n");
437         // delete all other chosen "cateogries.x" values and put a value here
438
result.append("<script type=\"text/javascript\">\n");
439         result.append(" function filterCategory(category) {\n");
440         result.append(" var searchform = document.forms['EDITOR'];\n");
441         result.append(" var inputFields = searchform.elements;\n");
442         result.append(" for (var i=0; i<inputFields.length; i++) {\n");
443         result.append(" if(inputFields[i].name.indexOf('categories') != -1) {\n");
444         result.append(" inputFields[i].value='';\n");
445         result.append(" inputFields[i].name='invalidsearchcategory';\n");
446         result.append(" }\n");
447         result.append(" }\n");
448         // if we found a category field use it, if not, set the name of our
449
// fooling field to "categories.0" or the widget filling will fail
450
result.append(" var categoryField = inputFields['dummysearchcategory'];\n");
451         result.append(" categoryField.name = 'categories.0';\n");
452         result.append(" categoryField.value = category;\n");
453         // additionally set searchpage to zero because filtered results may / will be smaller
454
result.append(" inputFields['dummysearchpage'].value = '0';\n");
455         result.append(" inputFields['dummysearchpage'].name = 'searchpage.0';\n");
456         result.append(" validateQuery();\n");
457         result.append(" searchform.submit();\n");
458         result.append(" }\n");
459         result.append("</script>\n");
460         return result.toString();
461     }
462
463     /**
464      * Returns the different select options for sort search result criteria. <p>
465      *
466      * @return the different select options for sort search result criteria
467      */

468     private List JavaDoc getSortWidgetConfiguration() {
469
470         List JavaDoc result = new LinkedList JavaDoc();
471         CmsMessages messages = Messages.get().getBundle(getLocale());
472         result.add(new CmsSelectWidgetOption(
473             CmsSearchParameters.SORT_NAMES[0],
474             true,
475             messages.key(Messages.GUI_SELECT_LABEL_SEARCH_SORT_SCORE_0)));
476         result.add(new CmsSelectWidgetOption(
477             CmsSearchParameters.SORT_NAMES[1],
478             false,
479             messages.key(Messages.GUI_SELECT_LABEL_SEARCH_SORT_DATE_CREATED_0)));
480         result.add(new CmsSelectWidgetOption(
481             CmsSearchParameters.SORT_NAMES[2],
482             false,
483             messages.key(Messages.GUI_SELECT_LABEL_SEARCH_SORT_DATE_LAST_MODIFIED_0)));
484         result.add(new CmsSelectWidgetOption(
485             CmsSearchParameters.SORT_NAMES[3],
486             false,
487             messages.key(Messages.GUI_SELECT_LABEL_SEARCH_SORT_TITLE_0)));
488         return result;
489     }
490
491     private String JavaDoc normalizePreviousQueryJS() {
492
493         StringBuffer JavaDoc result = new StringBuffer JavaDoc();
494         result.append("<script type=\"text/javascript\">\n");
495         result.append(" function normalizeQueryValue() {\n");
496         result.append(" var searchform = document.forms['EDITOR'];\n");
497         result.append(" var query = searchform.elements['query.0'].value;\n");
498         result.append(" query = decodeURI(query);\n");
499         result.append(" searchform.elements['query.0'].value = query;\n");
500         result.append(" return true;\n");
501         result.append(" }\n");
502         result.append(" normalizeQueryValue();\n");
503         result.append("</script>\n");
504         return result.toString();
505     }
506
507     private String JavaDoc submitJS() {
508
509         StringBuffer JavaDoc result = new StringBuffer JavaDoc();
510         result.append(" function validateQuery() {\n");
511         result.append(" var searchform = document.getElementById(\"EDITOR\");\n");
512         result.append(" var query = searchform.elements['query.0'].value;\n");
513         result.append(" searchform.elements['query.0'].value = query;\n");
514         result.append(" return true;\n");
515         result.append(" }\n");
516         return result.toString();
517     }
518 }
519
Popular Tags