KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > opencms > workplace > help > CmsHelpSearchResultView


1 /*
2  * File : $Source: /usr/local/cvs/opencms/src/org/opencms/workplace/help/CmsHelpSearchResultView.java,v $
3  * Date : $Date: 2006/03/27 14:53:04 $
4  * Version: $Revision: 1.6 $
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.help;
33
34 import org.opencms.file.CmsObject;
35 import org.opencms.file.CmsProject;
36 import org.opencms.i18n.CmsEncoder;
37 import org.opencms.i18n.CmsLocaleManager;
38 import org.opencms.i18n.CmsMessages;
39 import org.opencms.jsp.CmsJspActionElement;
40 import org.opencms.main.CmsException;
41 import org.opencms.search.CmsSearch;
42 import org.opencms.search.CmsSearchResult;
43 import org.opencms.util.CmsStringUtil;
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 import java.util.SortedMap JavaDoc;
50 import java.util.StringTokenizer JavaDoc;
51 import java.util.TreeMap JavaDoc;
52
53 import javax.servlet.ServletRequest JavaDoc;
54 import javax.servlet.http.HttpServletRequest JavaDoc;
55 import javax.servlet.http.HttpServletResponse JavaDoc;
56 import javax.servlet.jsp.PageContext JavaDoc;
57
58 /**
59  * Displays the result of a <code>{@link org.opencms.search.CmsSearch}</code>.<p>
60  *
61  * Requires the following request parameters (see constructor):
62  * <ul>
63  * <li>
64  * index:<br>the String identifying the required search index.
65  * <li>
66  * query:<br>the search query to run.
67  * </ul>
68  * <p>
69  *
70  * @author Achim Westermann
71  *
72  * @version $Revision: 1.6 $
73  *
74  * @since 6.0.0
75  */

76 public class CmsHelpSearchResultView {
77
78     /** The project that forces evaluation of all dynamic content. */
79     protected CmsProject m_offlineProject;
80
81     /** The project that allows static export. */
82     protected CmsProject m_onlineProject;
83
84     /** The flag that decides wethter links to search result point to their exported version or not. */
85     private boolean m_exportLinks = false;
86
87     /**
88      * A small cache for the forms generated by <code>{@link #toPostParameters(String)}</code> during a request. <p>
89      *
90      * Avoids duplicate forms.</p>
91      *
92      */

93     private SortedMap JavaDoc m_formCache;
94
95     /** The CmsJspActionElement to use. **/
96     private CmsJspActionElement m_jsp;
97
98     /** The url to a proprietary search url (different from m_jsp.getRequestContext().getUri). **/
99     private String JavaDoc m_searchRessourceUrl;
100
101     /**
102      * Constructor with the action element to use. <p>
103      *
104      * @param action the action element to use
105      */

106     public CmsHelpSearchResultView(CmsJspActionElement action) {
107
108         m_jsp = action;
109         this.m_formCache = new TreeMap JavaDoc();
110         try {
111             m_onlineProject = m_jsp.getCmsObject().readProject(CmsProject.ONLINE_PROJECT_ID);
112             m_offlineProject = m_jsp.getRequestContext().currentProject();
113         } catch (CmsException e) {
114             // failed to get online project, at least avoid NPE
115
m_onlineProject = m_offlineProject;
116         }
117
118     }
119
120     /**
121      * Constructor with arguments for construction of a <code>{@link CmsJspActionElement}</code>. <p>
122      *
123      * @param pageContext the page context to use
124      * @param request the current request
125      * @param response the current response
126      */

127     public CmsHelpSearchResultView(PageContext JavaDoc pageContext, HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
128
129         this(new CmsJspActionElement(pageContext, request, response));
130
131     }
132
133     /**
134      * Returns the formatted search results.<p>
135      *
136      * @param search the preconfigured search bean
137      * @return the formatted search results
138      */

139     public String JavaDoc displaySearchResult(CmsSearch search) {
140
141         initSearch(search);
142         StringBuffer JavaDoc result = new StringBuffer JavaDoc(800);
143         CmsMessages messages = org.opencms.search.Messages.get().getBundle(m_jsp.getRequestContext().getLocale());
144
145         result.append("<h1>\n");
146         result.append(messages.key(org.opencms.search.Messages.GUI_HELP_SEARCH_RESULT_TITLE_0));
147         result.append("\n</h1>\n");
148         List JavaDoc searchResult;
149         if (CmsStringUtil.isEmptyOrWhitespaceOnly(search.getQuery())) {
150             search.setQuery("");
151             searchResult = new ArrayList JavaDoc();
152         } else {
153             searchResult = search.getSearchResult();
154         }
155
156         HttpServletRequest JavaDoc request = m_jsp.getRequest();
157         // get the action to perform from the request
158
String JavaDoc action = request.getParameter("action");
159
160         if (action != null && searchResult == null) {
161             result.append("<p class=\"formerror\">\n");
162             if (search.getLastException() != null) {
163
164                 result.append(messages.key(org.opencms.search.Messages.GUI_HELP_SEARCH_UNAVAILABLE_0));
165                 result.append("\n<!-- ").append(search.getLastException().toString());
166                 result.append(" //-->\n");
167             } else {
168                 result.append(messages.key(org.opencms.search.Messages.GUI_HELP_SEARCH_NOMATCH_1, search.getQuery()));
169                 result.append("\n");
170             }
171             result.append("</p>\n");
172         } else if (action != null && searchResult.size() <= 0) {
173             result.append("<p class=\"formerror\">\n");
174             result.append(messages.key(org.opencms.search.Messages.GUI_HELP_SEARCH_NOMATCH_1, search.getQuery()));
175             result.append("\n");
176             result.append("</p>\n");
177         } else if (action != null && searchResult.size() > 0) {
178             result.append("<p>\n");
179             result.append(messages.key(org.opencms.search.Messages.GUI_HELP_SEARCH_RESULT_START_0));
180             result.append("\n");
181             result.append("</p>\n<p>\n");
182
183             Iterator JavaDoc iterator = searchResult.iterator();
184
185             try {
186                 if (m_exportLinks) {
187                     m_jsp.getRequestContext().setCurrentProject(m_onlineProject);
188                 }
189
190                 while (iterator.hasNext()) {
191                     CmsSearchResult entry = (CmsSearchResult)iterator.next();
192                     result.append("\n<div class=\"searchResult\"><a class=\"navhelp\" HREF=\"");
193
194                     result.append(m_jsp.link(new StringBuffer JavaDoc(
195                         "/system/modules/org.opencms.workplace.help/jsptemplates/help_body.jsp?helpresource=").append(
196                         m_jsp.getRequestContext().removeSiteRoot(entry.getPath())).append("&").append(
197                         CmsLocaleManager.PARAMETER_LOCALE).append("=").append(m_jsp.getRequestContext().getLocale()).toString()));
198                     result.append("\">\n");
199                     result.append(entry.getTitle());
200                     result.append("</a>");
201                     result.append("&nbsp;(").append(entry.getScore()).append("&nbsp;%)\n");
202                     result.append("<span class=\"searchExcerpt\">\n");
203                     result.append(entry.getExcerpt()).append('\n');
204                     result.append("</span>\n");
205                     result.append("</div>\n");
206                 }
207             } finally {
208                 m_jsp.getRequestContext().setCurrentProject(m_offlineProject);
209             }
210
211             result.append("</p>\n");
212
213             // search page links below results
214
if (search.getPreviousUrl() != null || search.getNextUrl() != null) {
215                 result.append("<p>");
216                 if (search.getPreviousUrl() != null) {
217
218                     result.append("<a HREF=\"");
219                     result.append(getSearchPageLink(m_jsp.link(new StringBuffer JavaDoc(search.getPreviousUrl()).append('&').append(
220                         CmsLocaleManager.PARAMETER_LOCALE).append("=").append(m_jsp.getRequestContext().getLocale()).toString())));
221                     result.append("\">");
222                     result.append(messages.key(org.opencms.search.Messages.GUI_HELP_BUTTON_BACK_0));
223                     result.append(" &lt;&lt;</a>&nbsp;&nbsp;\n");
224                 }
225                 Map JavaDoc pageLinks = search.getPageLinks();
226                 Iterator JavaDoc i = pageLinks.keySet().iterator();
227                 while (i.hasNext()) {
228                     int pageNumber = ((Integer JavaDoc)i.next()).intValue();
229
230                     result.append(" ");
231                     if (pageNumber != search.getSearchPage()) {
232                         result.append("<a HREF=\"").append(
233                             getSearchPageLink(m_jsp.link(new StringBuffer JavaDoc(
234                                 (String JavaDoc)pageLinks.get(new Integer JavaDoc(pageNumber))).append('&').append(
235                                 CmsLocaleManager.PARAMETER_LOCALE).append("=").append(
236                                 m_jsp.getRequestContext().getLocale()).toString())));
237                         result.append("\" target=\"_self\">").append(pageNumber).append("</a>\n");
238                     } else {
239                         result.append(pageNumber);
240                     }
241                 }
242                 if (search.getNextUrl() != null) {
243                     result.append("&nbsp;&nbsp;&nbsp;<a HREF=\"");
244                     result.append(getSearchPageLink(new StringBuffer JavaDoc(m_jsp.link(search.getNextUrl())).append('&').append(
245                         CmsLocaleManager.PARAMETER_LOCALE).append("=").append(m_jsp.getRequestContext().getLocale()).toString()));
246                     result.append("\">&gt;&gt;");
247                     result.append(messages.key(org.opencms.search.Messages.GUI_HELP_BUTTON_NEXT_0));
248                     result.append("</a>\n");
249                 }
250                 result.append("</p>\n");
251             }
252
253         }
254
255         // include the post forms for the page links:
256
Iterator JavaDoc values = m_formCache.values().iterator();
257         while (values.hasNext()) {
258             result.append(values.next());
259         }
260         return result.toString();
261
262     }
263
264     /**
265      * Returns true if the links to search results shall point to exported content, false else. <p>
266      * @return true if the links to search results shall point to exported content, false else
267      */

268     public boolean isExportLinks() {
269
270         return m_exportLinks;
271     }
272
273     /**
274      * Set wether the links to search results point to exported content or not. <p>
275      *
276      * @param exportLinks The value that decides Set wether the links to search results point to exported content or not.
277      */

278     public void setExportLinks(boolean exportLinks) {
279
280         this.m_exportLinks = exportLinks;
281     }
282
283     /**
284      * Set a proprietary resource uri for the search page. <p>
285      *
286      * This is optional but allows to override the standard search result links
287      * (for next or previous pages) that point to
288      * <code>getJsp().getRequestContext().getUri()</code> whenever the search
289      * uri is element of some template and should not be linked directly.<p>
290      *
291      * @param uri the proprietary resource uri for the search page
292      */

293     public void setSearchRessourceUrl(String JavaDoc uri) {
294
295         this.m_searchRessourceUrl = uri;
296     }
297
298     /**
299      * Returns the resource uri to the search page with respect to the
300      * optionally configured value <code>{@link #setSearchRessourceUrl(String)}</code>
301      * with the request parameters of the given argument.<p>
302      *
303      * This is a workaround for Tomcat bug 35775
304      * (http://issues.apache.org/bugzilla/show_bug.cgi?id=35775). After it has been
305      * fixed the version 1.1 should be restored (or at least this codepath should be switched back.<p>
306      *
307      *
308      * @param link the suggestion of the search result bean ( a previous, next or page number url)
309      * @return the resource uri to the search page with respect to the
310      * optionally configured value <code>{@link #setSearchRessourceUrl(String)}</code>
311      * with the request parameters of the given argument
312      */

313     private String JavaDoc getSearchPageLink(String JavaDoc link) {
314
315         if (m_searchRessourceUrl != null) {
316             // for the form to generate we need params.
317
String JavaDoc pageParams = "";
318             int paramIndex = link.indexOf('?');
319             if (paramIndex > 0) {
320                 pageParams = link.substring(paramIndex);
321             }
322             String JavaDoc formurl = new StringBuffer JavaDoc(m_searchRessourceUrl).append(pageParams).toString();
323             toPostParameters(formurl);
324
325             link = new StringBuffer JavaDoc("javascript:document.forms['").append("form").append(m_formCache.size() - 1).append(
326                 "'].submit()").toString();
327         }
328         return link;
329     }
330
331     private void initSearch(CmsSearch search) {
332
333         // Collect the objects required to access the OpenCms VFS from the request
334
CmsObject cmsObject = m_jsp.getCmsObject();
335
336         ServletRequest JavaDoc request = m_jsp.getRequest();
337         search.init(cmsObject);
338         search.setField(new String JavaDoc[] {"title", "keywords", "description", "content"});
339         search.setMatchesPerPage(5);
340         search.setDisplayPages(7);
341         search.setSearchRoot(new StringBuffer JavaDoc("/system/workplace/locales/").append(
342             m_jsp.getRequestContext().getLocale()).append("/help/").toString());
343
344         String JavaDoc query = request.getParameter("query");
345         search.setQuery(query);
346     }
347
348     /**
349      * Generates a html form (named form&lt;n&gt;) with parameters found in
350      * the given GET request string (appended params with "?value=param&value2=param2).
351      * &gt;n&lt; is the number of forms that already have been generated.
352      * This is a content-expensive bugfix for http://issues.apache.org/bugzilla/show_bug.cgi?id=35775
353      * and should be replaced with the 1.1 revision as soon that bug is fixed.<p>
354      *
355      * The forms action will point to the given uri's path info part: All links in the page
356      * that includes this generated html and that are related to the get request should
357      * have "src='#'" and "onclick=documents.forms['&lt;getRequestUri&gt;'].submit()". <p>
358      *
359      * The generated form lands in the internal <code>Map {@link #m_formCache}</code> as mapping
360      * from uris to Strings and has to be appended to the output at a valid position. <p>
361      *
362      * Warning: Does not work with multiple values mapped to one parameter ("key = value1,value2..").<p>
363      *
364      *
365      *
366      * @param getRequestUri a request uri with optional query, will be used as name of the form too.
367      */

368     private void toPostParameters(String JavaDoc getRequestUri) {
369
370         StringBuffer JavaDoc result;
371         if (!m_formCache.containsKey(getRequestUri)) {
372
373             result = new StringBuffer JavaDoc();
374             int index = getRequestUri.indexOf('?');
375             String JavaDoc query = "";
376             String JavaDoc path = "";
377             if (index > 0) {
378                 query = getRequestUri.substring(index + 1);
379                 path = getRequestUri.substring(0, index);
380                 result.append("\n<form method=\"post\" name=\"form").append(m_formCache.size()).append("\" action=\"");
381                 result.append(path).append("\">\n");
382
383                 // "key=value" pairs as tokens:
384
StringTokenizer JavaDoc entryTokens = new StringTokenizer JavaDoc(query, "&", false);
385                 while (entryTokens.hasMoreTokens()) {
386                     StringTokenizer JavaDoc keyValueToken = new StringTokenizer JavaDoc(entryTokens.nextToken(), "=", false);
387                     if (keyValueToken.countTokens() != 2) {
388                         continue;
389                     }
390                     // Undo the possible already performed url encoding for the given url
391
String JavaDoc key = CmsEncoder.decode(keyValueToken.nextToken());
392                     String JavaDoc value = CmsEncoder.decode(keyValueToken.nextToken());
393                     result.append(" <input type=\"hidden\" name=\"");
394                     result.append(key).append("\" value=\"");
395                     result.append(value).append("\" />\n");
396                 }
397                 result.append("</form>\n");
398                 m_formCache.put(getRequestUri, result.toString());
399             }
400         }
401     }
402 }
Popular Tags