KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > opencms > frontend > templateone > modules > CmsTemplateModules


1 /*
2  * File : $Source: /usr/local/cvs/opencms/src-modules/org/opencms/frontend/templateone/modules/CmsTemplateModules.java,v $
3  * Date : $Date: 2006/03/27 14:52:59 $
4  * Version: $Revision: 1.15 $
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.modules;
33
34 import org.opencms.file.CmsPropertyDefinition;
35 import org.opencms.file.CmsResource;
36 import org.opencms.file.CmsResourceFilter;
37 import org.opencms.file.types.CmsResourceTypeFolder;
38 import org.opencms.file.types.I_CmsResourceType;
39 import org.opencms.frontend.templateone.CmsPropertyTemplateOne;
40 import org.opencms.frontend.templateone.CmsTemplateBase;
41 import org.opencms.jsp.CmsJspNavElement;
42 import org.opencms.main.CmsException;
43 import org.opencms.main.CmsLog;
44 import org.opencms.main.OpenCms;
45 import org.opencms.util.CmsStringUtil;
46
47 import java.util.Calendar JavaDoc;
48 import java.util.Date JavaDoc;
49 import java.util.GregorianCalendar JavaDoc;
50 import java.util.List JavaDoc;
51
52 import javax.servlet.http.HttpServletRequest JavaDoc;
53 import javax.servlet.http.HttpServletResponse JavaDoc;
54 import javax.servlet.jsp.PageContext JavaDoc;
55
56 import org.apache.commons.logging.Log;
57
58 /**
59  * A helper bean for the template one modules.<p>
60  *
61  * Provides methods to create list views with category browsing and
62  * convenience methods to display date values and links.<p>
63  *
64  * @author Thomas Weckert
65  * @author Andreas Zahner
66  *
67  * @version $Revision: 1.15 $
68  *
69  * @since 6.0.0
70  */

71 public class CmsTemplateModules extends CmsTemplateBase {
72
73     /** Request parameter name for the category folder. */
74     public static final String JavaDoc PARAM_CATEGORYFOLDER = "categoryfolder";
75
76     /** Request parameter name for the collector. */
77     public static final String JavaDoc PARAM_COLLECTOR = "collector";
78
79     /** Request parameter name for the list count. */
80     public static final String JavaDoc PARAM_COUNT = "count";
81
82     /** Request parameter name maximum number of elements to show. */
83     public static final String JavaDoc PARAM_ELEMENTCOUNT = "elementcount";
84
85     /** Request parameter name for the xmlcontent folder. */
86     public static final String JavaDoc PARAM_FOLDER = "folder";
87
88     /** The log object for this class. */
89     private static final Log LOG = CmsLog.getLog(CmsPropertyTemplateOne.class);
90
91     private String JavaDoc m_categoryFolder;
92     private boolean m_hasCategoryFolders;
93
94     /**
95      * @see org.opencms.jsp.CmsJspActionElement#CmsJspActionElement(PageContext, HttpServletRequest, HttpServletResponse)
96      */

97     public CmsTemplateModules(PageContext JavaDoc context, HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc res) {
98
99         super(context, req, res);
100     }
101
102     /**
103      * Creates a html breadcrumb navigation.<p>
104      *
105      * Instead of the NavText properties the title properties are used as anchor texts in this breadcrumb navigation!
106      * The navigation starts from a folder as specified in the request parameter "folder" and
107      * goes to the folder specified in the request parameter "categoryfolder".<p>
108      *
109      * @param separator a String to separate the anchors in the breadcrumb navigation
110      * @return the html for the breadcrumb navigation
111      */

112     public String JavaDoc buildHtmlNavBreadcrumb(String JavaDoc separator) {
113
114         StringBuffer JavaDoc result = new StringBuffer JavaDoc(16);
115         // get the value of the start folder request parameter
116
String JavaDoc startfolder = getRequest().getParameter(PARAM_FOLDER);
117         // calculate levels to go down
118
int displayLevels = -(CmsResource.getPathLevel(getCategoryFolder()) - CmsResource.getPathLevel(startfolder) + 1);
119         // get the navigation list
120
List JavaDoc breadcrumb = getNavigation().getNavigationBreadCrumb(getCategoryFolder(), displayLevels, -1, true);
121
122         for (int i = 0, n = breadcrumb.size(); i < n; i++) {
123             CmsJspNavElement navElement = (CmsJspNavElement)breadcrumb.get(i);
124             // get the title of the current navigation element
125
String JavaDoc title = navElement.getTitle();
126             if (CmsStringUtil.isEmptyOrWhitespaceOnly(title)) {
127                 if (LOG.isWarnEnabled()) {
128                     LOG.warn(Messages.get().getBundle().key(
129                         Messages.LOG_ERR_MISSING_PROP_2,
130                         navElement.getResourceName(),
131                         CmsPropertyDefinition.PROPERTY_TITLE));
132                 }
133                 title = CmsResource.getName(navElement.getResourceName());
134             }
135             // generate the link for the navigation element
136
String JavaDoc folderUri = link(getRequestContext().getUri()
137                 + "?"
138                 + PARAM_CATEGORYFOLDER
139                 + "="
140                 + navElement.getResourceName());
141
142             // append the anchor
143
result.append("<a HREF=\"");
144             result.append(folderUri);
145             result.append("\">");
146             result.append(title);
147             result.append("</a>");
148
149             // append the separator
150
if (i < (n - 1)) {
151                 result.append(separator);
152             }
153         }
154
155         return result.toString();
156     }
157
158     /**
159      * Creates a html &lt;li&gt; list of all folders inside the current folder.<p>
160      *
161      * Additionally, behind each folder the number of resources of a specified resource type gets listed.<p>
162      *
163      * @param resourceTypeId the resource type to count resources inside folders
164      * @param attrs optional html attributes to use in the &lt;ul&gt; tag
165      * @return a html &lt;li&gt; list of all folders inside the current folder
166      * @throws CmsException if something goes wrong
167      */

168     public String JavaDoc buildHtmlNavList(int resourceTypeId, String JavaDoc attrs) throws CmsException {
169
170         // get the start folder from request
171
String JavaDoc startfolder = getCategoryFolder();
172
173         if (LOG.isDebugEnabled()) {
174             LOG.debug(Messages.get().getBundle().key(
175                 Messages.LOG_DEBUG_BUILD_HTML_NAVLIST_2,
176                 startfolder,
177                 new Integer JavaDoc(resourceTypeId)));
178         }
179
180         // read the resource tree
181
CmsResourceFilter filter = CmsResourceFilter.DEFAULT.addRequireType(CmsResourceTypeFolder.RESOURCE_TYPE_ID);
182         List JavaDoc resourceTree = getCmsObject().readResources(startfolder, filter, true);
183
184         String JavaDoc indent = "&nbsp;&nbsp;";
185         StringBuffer JavaDoc result = new StringBuffer JavaDoc(32);
186
187         if (resourceTree.size() > 0) {
188
189             // open the list
190
result.append("<ul");
191             if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(attrs)) {
192                 // append additional attributes
193
result.append(" ").append(attrs);
194             }
195
196             result.append(">\n");
197
198             int indentCount = 0;
199             int startLevel = CmsResource.getPathLevel(getCmsObject().getSitePath((CmsResource)resourceTree.get(0)));
200             int lastLevel = startLevel;
201             // set flag that category folders are present
202
m_hasCategoryFolders = true;
203
204             for (int i = 0, n = resourceTree.size(); i < n; i++) {
205
206                 CmsResource resource = (CmsResource)resourceTree.get(i);
207                 String JavaDoc resourceName = getCmsObject().getSitePath(resource);
208
209                 // skip files
210
if (!resource.isFolder()) {
211                     continue;
212                 }
213
214                 // count resources of the specified type inside folder
215
int faqCount = getResourceCount(resourceName, resourceTypeId);
216
217                 int level = CmsResource.getPathLevel(resourceName);
218
219                 if (lastLevel < level) {
220                     // increase indentation level
221
indentCount++;
222                 } else if (lastLevel > level) {
223                     // decrease indentation level
224
indentCount--;
225                 }
226
227                 // open a new list item (by closing a previous list item first eventually)
228
if (level == startLevel) {
229                     if (i == 0) {
230                         result.append("<li>\n");
231                     } else {
232                         result.append("<br>&nbsp;&nbsp;\n");
233                         result.append("</li>\n");
234                         result.append("<li>\n");
235                     }
236                 }
237
238                 // append a line break on sub-FAQs
239
if (level > startLevel) {
240                     result.append("<br>");
241                 }
242
243                 // append indentation for sub-FAQs
244
for (int j = 0; j < indentCount; j++) {
245                     result.append(indent);
246                 }
247
248                 String JavaDoc faqUri = link(getRequestContext().getUri() + "?" + PARAM_CATEGORYFOLDER + "=" + resourceName);
249
250                 String JavaDoc title = getCmsObject().readPropertyObject(
251                     resourceName,
252                     CmsPropertyDefinition.PROPERTY_TITLE,
253                     false).getValue(null);
254
255                 if (CmsStringUtil.isEmptyOrWhitespaceOnly(title)) {
256                     if (LOG.isWarnEnabled()) {
257                         LOG.warn(Messages.get().getBundle().key(
258                             Messages.LOG_ERR_MISSING_PROP_2,
259                             resourceName,
260                             CmsPropertyDefinition.PROPERTY_TITLE));
261                     }
262                     title = resource.getName();
263                 }
264
265                 // append the anchor
266
result.append("<a HREF=\"");
267                 result.append(faqUri);
268                 result.append("\">");
269                 if (level == startLevel) {
270                     result.append("<b>").append(title).append("</b>");
271                 } else {
272                     result.append(title);
273                 }
274                 result.append("</a>");
275
276                 // append number of FAQ articles on "top-level" FAQs
277
if (level == startLevel) {
278                     result.append("&nbsp;&nbsp;(");
279                     result.append(faqCount);
280                     result.append(")\n");
281                 }
282
283                 result.append("\n");
284                 lastLevel = level;
285             }
286
287             // close the last open list item
288
result.append("</li>\n");
289
290             // close the list
291
result.append("</ul>\n");
292         }
293
294         return result.toString();
295     }
296
297     /**
298      * Creates a html &lt;li&gt; list of all folders inside the current folder.<p>
299      *
300      * Additionally, behind each folder the number of resources of a specified resource type gets listed.<p>
301      *
302      * @param resourceTypeName the resource type name to count resources inside folders
303      * @param attrs optional html attributes to use in the &lt;ul&gt; tag
304      * @return a html &lt;li&gt; list of all folders inside the current folder
305      * @throws CmsException if something goes wrong
306      */

307     public String JavaDoc buildHtmlNavList(String JavaDoc resourceTypeName, String JavaDoc attrs) throws CmsException {
308
309         I_CmsResourceType resType = OpenCms.getResourceManager().getResourceType(resourceTypeName);
310         return buildHtmlNavList(resType.getTypeId(), attrs);
311     }
312
313     /**
314      * Creates a HTML anchor from the values of three page context attribute names.
315      *
316      * @param hrefAttrib the name of the page context attribute containing the link URL
317      * @param descrAttrib the name of the page context attribute containing the link description
318      * @param targetAttrib the name of the page context attribute containing the link target
319      * @return an HTML anchor
320      */

321     public String JavaDoc getAnchor(String JavaDoc hrefAttrib, String JavaDoc descrAttrib, String JavaDoc targetAttrib) {
322
323         String JavaDoc attribHref = (String JavaDoc)getJspContext().getAttribute(hrefAttrib);
324         String JavaDoc attribDescr = (String JavaDoc)getJspContext().getAttribute(descrAttrib);
325         boolean openBlank = Boolean.valueOf((String JavaDoc)getJspContext().getAttribute(targetAttrib)).booleanValue();
326
327         String JavaDoc description = attribDescr;
328         if (CmsStringUtil.isEmpty(attribDescr) || attribDescr.startsWith("???")) {
329             description = attribHref;
330         }
331
332         String JavaDoc href = attribHref;
333         if (!attribHref.toLowerCase().startsWith("http")) {
334             href = link(attribHref);
335         }
336
337         String JavaDoc target = "";
338         if (openBlank) {
339             target = "_blank";
340         }
341
342         StringBuffer JavaDoc anchor = new StringBuffer JavaDoc();
343         anchor.append("<a HREF=\"").append(href).append("\"");
344
345         if (CmsStringUtil.isNotEmpty(description)) {
346             anchor.append(" title=\"").append(description).append("\"");
347         }
348
349         if (CmsStringUtil.isNotEmpty(target)) {
350             anchor.append(" target=\"").append(target).append("\"");
351         }
352
353         anchor.append(">").append(description).append("</a>");
354
355         return anchor.toString();
356     }
357
358     /**
359      * Returns the URI of the currently displayed category folder.<p>
360      *
361      * @return the URI of the currently displayed category folder
362      */

363     public String JavaDoc getCategoryFolder() {
364
365         if (m_categoryFolder == null) {
366             // get the category folder from request
367
m_categoryFolder = getRequest().getParameter(PARAM_CATEGORYFOLDER);
368             if (CmsStringUtil.isEmptyOrWhitespaceOnly(m_categoryFolder)) {
369                 // no folder found in request, use folder parameter
370
m_categoryFolder = getRequest().getParameter(PARAM_FOLDER);
371             }
372         }
373         return m_categoryFolder;
374     }
375
376     /**
377      * Returns the number of resources with a given resource type inside a folder.<p>
378      *
379      * @param foldername the folder to read resources
380      * @param resourceTypeId the desired resource type ID
381      *
382      * @return the number of resources
383      */

384     public int getResourceCount(String JavaDoc foldername, int resourceTypeId) {
385
386         int result = -1;
387
388         try {
389             // filter the resources with the specified id
390
CmsResourceFilter filter = CmsResourceFilter.DEFAULT.addRequireType(resourceTypeId);
391             List JavaDoc resources = getCmsObject().readResources(foldername, filter, false);
392             result = resources.size();
393         } catch (CmsException e) {
394             // error reading the resources
395
if (LOG.isErrorEnabled()) {
396                 LOG.error(org.opencms.db.Messages.get().getBundle().key(
397                     org.opencms.db.Messages.ERR_READ_RESOURCES_WITH_TYPE_2,
398                     new Integer JavaDoc(resourceTypeId),
399                     foldername), e);
400             }
401             result = -1;
402         }
403
404         return result;
405     }
406
407     /**
408      * Returns the number of resources with a given resource type inside a folder.<p>
409      *
410      * @param foldername the folder to read resources
411      * @param resourceTypeName the desired resource type name
412      *
413      * @return the number of resources
414      */

415     public int getResourceCount(String JavaDoc foldername, String JavaDoc resourceTypeName) {
416
417         try {
418             I_CmsResourceType resType = OpenCms.getResourceManager().getResourceType(resourceTypeName);
419             return getResourceCount(foldername, resType.getTypeId());
420         } catch (CmsException e) {
421             // error getting resource type ID
422
if (LOG.isErrorEnabled()) {
423                 LOG.error(org.opencms.db.Messages.get().getBundle().key(
424                     org.opencms.loader.Messages.ERR_UNKNOWN_RESTYPE_NAME_REQ_1,
425                     resourceTypeName), e);
426             }
427             return -1;
428         }
429     }
430
431     /**
432      * Returns true if the currently displayed folder contains subfolders which are used as category folders.<p>
433      *
434      * This method has to be called after the method {@link CmsTemplateModules#buildHtmlNavList(int, String)}.<p>
435      *
436      * @return true if the currently displayed folder contains subfolders which are used as category folders
437      */

438     public boolean hasCategoryFolders() {
439
440         return m_hasCategoryFolders;
441     }
442
443     /**
444      * Checks if two dates in the page context attributes have the same date and differ only from their time.<p>
445      *
446      * @param startDateAttrib the name of the page context attribute containing the start date string
447      * @param endDateAttrib the name of the page context attribute containing the end date string
448      * @return true if the two dates differ only in time, otherwise false
449      */

450     public boolean isSameDate(String JavaDoc startDateAttrib, String JavaDoc endDateAttrib) {
451
452         String JavaDoc timeString = (String JavaDoc)getJspContext().getAttribute(startDateAttrib);
453         long timestamp = (new Long JavaDoc(timeString)).longValue();
454         Calendar JavaDoc calStart = new GregorianCalendar JavaDoc();
455         calStart.setTimeInMillis(timestamp);
456
457         timeString = (String JavaDoc)getJspContext().getAttribute(endDateAttrib);
458         timestamp = (new Long JavaDoc(timeString)).longValue();
459         Calendar JavaDoc calEnd = new GregorianCalendar JavaDoc();
460         calEnd.setTimeInMillis(timestamp);
461
462         return ((calStart.get(Calendar.DAY_OF_YEAR) == calEnd.get(Calendar.DAY_OF_YEAR)) && (calStart.get(Calendar.YEAR) == calEnd.get(Calendar.YEAR)));
463     }
464
465     /**
466      * Saves a {@link Date} object in the page context that was created from the value of
467      * a specified page context attribute.<p>
468      *
469      * @param dateAttrib the name of the page context attribute containing the date string
470      */

471     public void setDate(String JavaDoc dateAttrib) {
472
473         String JavaDoc timeString = (String JavaDoc)getJspContext().getAttribute(dateAttrib);
474         long timestamp = (new Long JavaDoc(timeString)).longValue();
475         Date JavaDoc date = new Date JavaDoc(timestamp);
476         getJspContext().setAttribute("date", date);
477     }
478
479     /**
480      * Returns true if the bread crumb navigation should be shown.<p>
481      *
482      * This method has to be called after the method {@link CmsTemplateModules#buildHtmlNavList(int, String)}.<p>
483      *
484      * @return true if the bread crumb navigation should be shown
485      */

486     public boolean showNavBreadCrumb() {
487
488         return hasCategoryFolders() || !getRequest().getParameter(PARAM_FOLDER).equals(getCategoryFolder());
489     }
490 }
Popular Tags