KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > opencms > frontend > templateone > CmsTemplateSearch


1 /*
2  * File : $Source: /usr/local/cvs/opencms/src-modules/org/opencms/frontend/templateone/CmsTemplateSearch.java,v $
3  * Date : $Date: 2006/03/27 14:52:51 $
4  * Version: $Revision: 1.13 $
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.frontend.templateone;
33
34 import org.opencms.file.CmsPropertyDefinition;
35 import org.opencms.file.CmsResource;
36 import org.opencms.i18n.CmsEncoder;
37 import org.opencms.i18n.CmsLocaleManager;
38 import org.opencms.main.CmsException;
39 import org.opencms.search.CmsSearch;
40 import org.opencms.search.CmsSearchResult;
41 import org.opencms.search.Messages;
42 import org.opencms.util.CmsStringUtil;
43 import org.opencms.workplace.CmsWorkplace;
44
45 import java.util.ArrayList JavaDoc;
46 import java.util.Iterator JavaDoc;
47 import java.util.List JavaDoc;
48 import java.util.Map JavaDoc;
49
50 import javax.servlet.http.HttpServletRequest JavaDoc;
51 import javax.servlet.http.HttpServletResponse JavaDoc;
52 import javax.servlet.jsp.JspException JavaDoc;
53 import javax.servlet.jsp.PageContext JavaDoc;
54
55 /**
56  * Provides methods for the search result JSP page.<p>
57  *
58  * @author Andreas Zahner
59  *
60  * @version $Revision: 1.13 $
61  *
62  * @since 6.0.0
63  */

64 public class CmsTemplateSearch extends CmsTemplateBean {
65
66     /** Request parameter name for the search entire website flag.<p> */
67     public static final String JavaDoc PARAM_SEARCHALL = "entire";
68
69     /** Stores the URI of the page calling the search result page.<p> */
70     private String JavaDoc m_pageUri;
71
72     /** The search entire website flag.<p> */
73     private boolean m_searchAll;
74
75     /**
76      * Empty constructor, required for every JavaBean.<p>
77      */

78     public CmsTemplateSearch() {
79
80         super();
81     }
82
83     /**
84      * Constructor, with parameters.<p>
85      *
86      * Use this constructor for the template.<p>
87      *
88      * @param context the JSP page context object
89      * @param req the JSP request
90      * @param res the JSP response
91      */

92     public CmsTemplateSearch(PageContext JavaDoc context, HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc res) {
93
94         super();
95         init(context, req, res);
96     }
97
98     /**
99      * Builds the html to display error messages on the search result page.<p>
100      *
101      * If no error occurs, an empty String will be returned.<p>
102      *
103      * @param search the search result object holding all necessary information
104      * @param results the list of result objects to display
105      * @return the html to display error messages
106      */

107     public String JavaDoc buildSearchErrorMessages(CmsSearch search, List JavaDoc results) {
108
109         StringBuffer JavaDoc result = new StringBuffer JavaDoc(32);
110         if (search.getLastException() != null) {
111             // the search did not run properly, create error output
112
String JavaDoc errorMessage = "";
113             if (((CmsException)search.getLastException()).getMessageContainer().getKey().equals(
114                 Messages.ERR_QUERY_TOO_SHORT_1)) {
115                 // query String was too short
116
errorMessage = key("search.error.wordlength");
117             } else {
118                 // other error
119
errorMessage = key("search.error.details");
120             }
121             result.append("<h3>");
122             result.append(key("search.error"));
123             result.append("</h3>\n");
124             result.append("<p>");
125             result.append(errorMessage);
126             result.append("</p>\n");
127             result.append("<!-- Exception message: ");
128             result.append(search.getLastException().toString());
129             result.append("// -->\n");
130         } else if (results == null || results.size() == 0) {
131             // no results were found for the current query
132
result.append("<h3>");
133             result.append(key("search.error.nomatch"));
134             result.append("</h3>\n");
135         }
136         return result.toString();
137     }
138
139     /**
140      * Builds the html for the search result page headline.<p>
141      *
142      * @return the html for the search result page headline
143      */

144     public String JavaDoc buildSearchHeadline() {
145
146         StringBuffer JavaDoc result = new StringBuffer JavaDoc(32);
147         result.append(key("search.headline"));
148         if (!isSearchAll() && !"/".equals(getStartFolder())) {
149             result.append(key("search.headline.area"));
150             result.append(getAreaName());
151         } else {
152             result.append(key("search.headline.all"));
153         }
154         return result.toString();
155     }
156
157     /**
158      * Builds the html for the links to previous and next search result pages.<p>
159      *
160      * @param search the search result object holding all necessary information
161      * @return the html for the links to previous and next search result pages
162      */

163     public String JavaDoc buildSearchLinks(CmsSearch search) {
164
165         StringBuffer JavaDoc result = new StringBuffer JavaDoc(32);
166         boolean showPageLinks = false;
167         // additional parameters for search result page in module folder
168
StringBuffer JavaDoc additionalParams = new StringBuffer JavaDoc(16);
169         if (search.getPreviousUrl() != null || search.getNextUrl() != null) {
170             // there is at least one previous or next page, build page links
171
showPageLinks = true;
172             result.append("<div class=\"searchlinks\">\n");
173             // fill additional parameters
174
additionalParams.append("&uri=");
175             additionalParams.append(CmsEncoder.encode(getRequestContext().getUri()));
176             additionalParams.append("&");
177             additionalParams.append(CmsLocaleManager.PARAMETER_LOCALE);
178             additionalParams.append("=");
179             additionalParams.append(getRequestContext().getLocale());
180             additionalParams.append("&");
181             additionalParams.append(PARAM_SEARCHALL);
182             additionalParams.append("=");
183             additionalParams.append(isSearchAll());
184         }
185         if (search.getPreviousUrl() != null) {
186             // build the link to the previous page
187
result.append("\t<input type=\"button\" class=\"formbutton\" value=\"&lt;&lt; ");
188             result.append(key("search.previous"));
189             result.append("\" onclick=\"location.href=\'");
190             result.append(link(search.getPreviousUrl()));
191             result.append(additionalParams);
192             result.append("\';\">");
193         }
194         Map JavaDoc pageLinks;
195         try {
196             // first set request context URI to form URI to obtain right page links
197
getRequestContext().setUri(CmsWorkplace.VFS_PATH_MODULES + MODULE_NAME + "/pages/search.html");
198             pageLinks = search.getPageLinks();
199         } finally {
200             // reset URI to page
201
getRequestContext().setUri(getPageUri());
202         }
203         Iterator JavaDoc i = pageLinks.keySet().iterator();
204         while (i.hasNext()) {
205             // show the page links
206
int pageNumber = ((Integer JavaDoc)i.next()).intValue();
207             String JavaDoc pageLink = link((String JavaDoc)pageLinks.get(new Integer JavaDoc(pageNumber)));
208             result.append("&nbsp;&nbsp;");
209             if (pageNumber != search.getSearchPage()) {
210                 // create a link to the page
211
result.append("<a HREF=\"");
212                 result.append(pageLink);
213                 result.append(additionalParams);
214                 result.append("\">");
215                 result.append(pageNumber);
216                 result.append("</a>");
217             } else {
218                 // show currently active page, but not as link
219
result.append(pageNumber);
220             }
221         }
222         if (search.getNextUrl() != null) {
223             // build the link to the next page
224
result.append("&nbsp;&nbsp;<input type=\"button\" class=\"formbutton\" value=\"");
225             result.append(key("search.next"));
226             result.append(" &gt;&gt;\" onclick=\"location.href=\'");
227             result.append(link(search.getNextUrl()));
228             result.append(additionalParams);
229             result.append("\';\">");
230         }
231         if (showPageLinks) {
232             result.append("\n</div>\n");
233         }
234         return result.toString();
235     }
236
237     /**
238      * Builds the html for the search result list for a single page.<p>
239      *
240      * @param results the list of result objects to display
241      * @return the html for the search result list
242      */

243     public String JavaDoc buildSearchResultList(List JavaDoc results) {
244
245         StringBuffer JavaDoc result = new StringBuffer JavaDoc(128);
246         Iterator JavaDoc iterator = results.iterator();
247         while (iterator.hasNext()) {
248             // create the output for a single result
249
CmsSearchResult entry = (CmsSearchResult)iterator.next();
250             result.append("<div class=\"searchresult\">");
251             String JavaDoc path = entry.getPath();
252             // remove the site root from the path of the result
253
path = getRequestContext().removeSiteRoot(path);
254             // get the file icon
255
String JavaDoc fileIcon = getFileIcon(path);
256             if (CmsStringUtil.isNotEmpty(fileIcon)) {
257                 result.append("<a HREF=\"");
258                 result.append(link(path));
259                 result.append("\">");
260                 result.append(fileIcon);
261                 result.append("</a>&nbsp;");
262             }
263
264             result.append("<a HREF=\"");
265             result.append(link(path));
266             result.append("\">");
267             String JavaDoc title = entry.getTitle();
268             if (CmsStringUtil.isEmpty(title)) {
269                 // title is not set, show file name instead
270
title = CmsResource.getName(path);
271             }
272             result.append(title);
273             result.append("</a>&nbsp;(");
274             result.append(entry.getScore());
275             result.append("%)<br>");
276             if (entry.getExcerpt() != null) {
277                 // add the excerpt
278
result.append(entry.getExcerpt());
279             }
280             if (entry.getKeywords() != null) {
281                 // add the keywords
282
result.append("<br>");
283                 result.append(key("search.keywords"));
284                 result.append(": ");
285                 result.append(entry.getKeywords());
286             }
287             if (entry.getDescription() != null) {
288                 // add the file description
289
result.append("<br>");
290                 result.append(key("search.description"));
291                 result.append(": ");
292                 result.append(entry.getDescription());
293             }
294             // add the last modification date of the result
295
result.append("<br>");
296             result.append(messages().getDateTime(entry.getDateLastModified().getTime()));
297             result.append("</div>\n");
298         }
299         return result.toString();
300     }
301
302     /**
303      * Returns the HTML of the file icon for the given resource name or an empty String if no icon can be found.<p>
304      *
305      * @param fileName the filename to check
306      * @return the HTML of the file icon for the given resource name or an empty String
307      */

308     public String JavaDoc getFileIcon(String JavaDoc fileName) {
309
310         int lastDot = fileName.lastIndexOf('.');
311         String JavaDoc extension = "";
312         // get the file extension
313
if ((lastDot > 0) && (lastDot < (fileName.length() - 1))) {
314             extension = fileName.substring(lastDot + 1).toLowerCase();
315             String JavaDoc iconPath = CmsWorkplace.VFS_PATH_MODULES
316                 + MODULE_NAME
317                 + "/resources/icons/ic_app_"
318                 + extension
319                 + ".gif";
320             // check if an icon exists
321
if (getCmsObject().existsResource(iconPath)) {
322                 StringBuffer JavaDoc result = new StringBuffer JavaDoc(8);
323                 String JavaDoc title = property(CmsPropertyDefinition.PROPERTY_TITLE, iconPath, "");
324                 result.append("<img SRC=\"");
325                 result.append(link(iconPath));
326                 result.append("\" border=\"0\" alt=\"");
327                 result.append(title);
328                 result.append("\" title=\"");
329                 result.append(title);
330                 result.append("\" align=\"left\" hspace=\"2\">");
331                 return result.toString();
332             }
333         }
334         return "";
335
336     }
337
338     /**
339      * Returns the URI of the page calling the search result page.<p>
340      *
341      * @return the URI of the page calling the search result page
342      */

343     public String JavaDoc getPageUri() {
344
345         return m_pageUri;
346     }
347
348     /**
349      * Returns the "checked" attribute String if the user checked the "search all" checkbox.<p>
350      *
351      * @return the "checked" attribute String or an empty String
352      */

353     public String JavaDoc getSearchAllChecked() {
354
355         if (isSearchAll() || "/".equals(getStartFolder())) {
356             return " checked=\"checked\"";
357         }
358         return "";
359     }
360
361     /**
362      * Returns the list of search results depending on the search root and the form data.<p>
363      *
364      * Either returns the results of the entire website or of the search root.<p>
365      *
366      * @param search the instanciated search object
367      * @return the results of the entire website or of the search root
368      */

369     public List JavaDoc getSearchResults(CmsSearch search) {
370
371         List JavaDoc result;
372         if (isSearchAll()) {
373             // set search root to root folder to get all search results
374
search.setSearchRoot("/");
375         } else {
376             // set search root to start folder
377
search.setSearchRoot(getStartFolder());
378         }
379         String JavaDoc queryString = search.getQuery();
380         try {
381             if (CmsStringUtil.isEmptyOrWhitespaceOnly(queryString)) {
382                 // no query String found, return empty list
383
queryString = "";
384                 search.setQuery("");
385                 result = new ArrayList JavaDoc();
386             } else {
387                 // first set request context URI to form URI to obtain right page links
388
getRequestContext().setUri(CmsWorkplace.VFS_PATH_MODULES + MODULE_NAME + "/pages/search.html");
389                 result = search.getSearchResult();
390             }
391         } finally {
392             // reset URI to page
393
getRequestContext().setUri(getPageUri());
394         }
395         return result;
396     }
397
398     /**
399      * Includes the specified template element with the page URI specified in the request parameter "uri".<p>
400      *
401      * After inclusion, the request context URI is reset to the old value.<p>
402      *
403      * @param element the element (template selector) to display from the target template
404      * @throws JspException if including the target fails
405      */

406     public void includeWithPageUri(String JavaDoc element) throws JspException JavaDoc {
407
408         String JavaDoc template = property(CmsPropertyDefinition.PROPERTY_TEMPLATE, "search", null);
409         // include target
410
include(template, element);
411     }
412
413     /**
414      * Initialize this bean with the current page context, request and response.<p>
415      *
416      * It is required to call one of the init() methods before you can use the
417      * instance of this bean.
418      *
419      * @param context the JSP page context object
420      * @param req the JSP request
421      * @param res the JSP response
422      */

423     public void init(PageContext JavaDoc context, HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc res) {
424
425         // call initialization of super class
426
super.init(context, req, res);
427         // initialize members from request
428
m_pageUri = req.getParameter(CmsTemplateBean.PARAM_URI);
429         if (m_pageUri == null) {
430             m_pageUri = getRequestContext().getUri();
431         }
432         m_searchAll = Boolean.valueOf(req.getParameter(PARAM_SEARCHALL)).booleanValue();
433         // change URI to point at page that called the search
434
getRequestContext().setUri(m_pageUri);
435     }
436
437     /**
438      * Returns true if the entire website should be searched.<p>
439      *
440      * @return true if the entire website should be searched, otherwise false
441      */

442     public boolean isSearchAll() {
443
444         return m_searchAll;
445     }
446
447     /**
448      * Returns true if the checkbox to search the entire website should be displayed.<p>
449      *
450      * @return true if the checkbox to search the entire website should be displayed, otherwise false
451      */

452     public boolean isSearchAllDisplayed() {
453
454         return !"/".equals(getStartFolder());
455     }
456
457     /**
458      * Sets if the entire website should be searched.<p>
459      *
460      * @param searchAll true if the entire website should be searched, otherwise false
461      */

462     public void setSearchAll(boolean searchAll) {
463
464         m_searchAll = searchAll;
465     }
466
467 }
Popular Tags