KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > dspace > app > webui > jsptag > ItemListTag


1 /*
2  * ItemListTag.java
3  *
4  * Version: $Revision: 1.30 $
5  *
6  * Date: $Date: 2006/04/05 02:15:45 $
7  *
8  * Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts
9  * Institute of Technology. All rights reserved.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions are
13  * met:
14  *
15  * - Redistributions of source code must retain the above copyright
16  * notice, this list of conditions and the following disclaimer.
17  *
18  * - Redistributions in binary form must reproduce the above copyright
19  * notice, this list of conditions and the following disclaimer in the
20  * documentation and/or other materials provided with the distribution.
21  *
22  * - Neither the name of the Hewlett-Packard Company nor the name of the
23  * Massachusetts Institute of Technology nor the names of their
24  * contributors may be used to endorse or promote products derived from
25  * this software without specific prior written permission.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
28  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
29  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
30  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
31  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
32  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
33  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
34  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
35  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
36  * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
37  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
38  * DAMAGE.
39  */

40 package org.dspace.app.webui.jsptag;
41
42 import org.dspace.app.webui.util.UIUtil;
43
44 import org.dspace.authorize.AuthorizeManager;
45
46 import org.dspace.content.Bitstream;
47 import org.dspace.content.Bundle;
48 import org.dspace.content.DCDate;
49 import org.dspace.content.DCValue;
50 import org.dspace.content.Item;
51
52 import org.dspace.core.ConfigurationManager;
53 import org.dspace.core.Constants;
54 import org.dspace.core.Context;
55 import org.dspace.core.Utils;
56
57 import org.dspace.storage.bitstore.BitstreamStorageManager;
58
59 import java.awt.image.BufferedImage JavaDoc;
60
61 import java.io.IOException JavaDoc;
62 import java.io.InputStream JavaDoc;
63 import java.io.UnsupportedEncodingException JavaDoc;
64
65 import java.sql.SQLException JavaDoc;
66 import java.util.StringTokenizer JavaDoc;
67
68 import javax.imageio.ImageIO JavaDoc;
69
70 import javax.servlet.http.HttpServletRequest JavaDoc;
71 import javax.servlet.jsp.JspException JavaDoc;
72 import javax.servlet.jsp.JspWriter JavaDoc;
73 import javax.servlet.jsp.jstl.fmt.LocaleSupport;
74 import javax.servlet.jsp.tagext.TagSupport JavaDoc;
75
76 /**
77  * Tag for display a list of items
78  *
79  * @author Robert Tansley
80  * @version $Revision: 1.30 $
81  */

82 public class ItemListTag extends TagSupport JavaDoc
83 {
84     /** Items to display */
85     private Item[] items;
86
87     /** Row to highlight, -1 for no row */
88     private int highlightRow = -1;
89
90     /** Column to emphasise - null, "title" or "date" */
91     private String JavaDoc emphColumn;
92
93     /** Config value of thumbnail view toggle */
94     private boolean showThumbs;
95
96     /** Config browse/search width and height */
97     private int thumbItemListMaxWidth;
98
99     private int thumbItemListMaxHeight;
100
101     /** Config browse/search thumbnail link behaviour */
102     private boolean linkToBitstream = false;
103     
104     /** The default fields to be displayed when listing items */
105     private static String JavaDoc listFields = "dc.date.issued(date), dc.title, dc.contributor.*";
106     
107     /** The default field which is bound to the browse by date */
108     private static String JavaDoc dateField = "dc.date.issued";
109     
110     /** The default field which is bound to the browse by title */
111     private static String JavaDoc titleField = "dc.title";
112     
113     public ItemListTag()
114     {
115         super();
116         getThumbSettings();
117     }
118
119     public int doStartTag() throws JspException JavaDoc
120     {
121         JspWriter JavaDoc out = pageContext.getOut();
122         HttpServletRequest JavaDoc hrq = (HttpServletRequest JavaDoc) pageContext.getRequest();
123         
124         boolean emphasiseDate = false;
125         boolean emphasiseTitle = false;
126
127         if (emphColumn != null)
128         {
129             emphasiseDate = emphColumn.equalsIgnoreCase("date");
130             emphasiseTitle = emphColumn.equalsIgnoreCase("title");
131         }
132         
133         // get the elements to display
134
String JavaDoc configLine = ConfigurationManager.getProperty("webui.itemlist.columns");
135         if (configLine != null)
136         {
137             listFields = configLine;
138         }
139         
140         // get the date and title fields
141
String JavaDoc dateLine = ConfigurationManager.getProperty("webui.browse.index.date");
142         if (dateLine != null)
143         {
144             dateField = dateLine;
145         }
146         
147         String JavaDoc titleLine = ConfigurationManager.getProperty("webui.browse.index.title");
148         if (titleLine != null)
149         {
150             titleField = titleLine;
151         }
152         
153         StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(listFields, ",");
154         
155 // make an array to hold all the frags that we will use
156
int columns = st.countTokens();
157         String JavaDoc[] frags = new String JavaDoc[columns * items.length];
158         
159         try
160         {
161             out.println("<table align=\"center\" class=\"miscTable\" summary=\"This table browse all dspace content\">");
162             out.println("<tr>");
163             
164             // Write the column headings
165
int colCount = 1;
166             boolean isDate = false;
167             boolean emph = false;
168             
169             while (st.hasMoreTokens())
170             {
171                 String JavaDoc field = st.nextToken().toLowerCase().trim();
172                 String JavaDoc cOddOrEven = ((colCount % 2) == 0 ? "Odd" : "Even");
173                 
174                 // find out if the field is a date
175
if (field.indexOf("(date)") > 0)
176                 {
177                     field = field.replaceAll("\\(date\\)", "");
178                     isDate = true;
179                 }
180                 
181                 // get the schema and the element qualifier pair
182
// (Note, the schema is not used for anything yet)
183
// (second note, I hate this bit of code. There must be
184
// a much more elegant way of doing this. Tomcat has
185
// some weird problems with variations on this code that
186
// I tried, which is why it has ended up the way it is)
187
StringTokenizer JavaDoc eq = new StringTokenizer JavaDoc(field, ".");
188                 
189                 String JavaDoc[] tokens = { "", "", "" };
190                 int k = 0;
191                 while(eq.hasMoreTokens())
192                 {
193                     tokens[k] = eq.nextToken().toLowerCase().trim();
194                     k++;
195                 }
196                 String JavaDoc schema = tokens[0];
197                 String JavaDoc element = tokens[1];
198                 String JavaDoc qualifier = tokens[2];
199                 
200                 // find out if we are emphasising this field
201
if ((field.equals(dateField) && emphasiseDate) ||
202                         (field.equals(titleField) && emphasiseTitle))
203                 {
204                     emph = true;
205                 }
206                 
207                 // prepare the strings for the header
208
String JavaDoc id = "t" + Integer.toString(colCount);
209                 String JavaDoc css = "oddRow" + cOddOrEven + "Col";
210                 String JavaDoc message = "itemlist." + field;
211                 
212                 // output the header
213
out.print("<th id=\"" + id + "\" class=\"" + css + "\">"
214                         + (emph ? "<strong>" : "")
215                         + LocaleSupport.getLocalizedMessage(pageContext, message)
216                         + (emph ? "</strong>" : "") + "</th>");
217                 
218                 // now prepare the frags for each of the table elements
219
for (int i = 0; i < items.length; i++)
220                 {
221                     // first get hold of the relevant metadata for this column
222
DCValue[] metadataArray;
223                     if (qualifier.equals("*"))
224                     {
225                         metadataArray = items[i].getMetadata(schema, element, Item.ANY, Item.ANY);
226                     }
227                     else if (qualifier.equals(""))
228                     {
229                         metadataArray = items[i].getMetadata(schema, element, null, Item.ANY);
230                     }
231                     else
232                     {
233                         metadataArray = items[i].getMetadata(schema, element, qualifier, Item.ANY);
234                     }
235                     
236                     // now prepare the content of the table division
237
String JavaDoc metadata = "-";
238                     if (metadataArray.length > 0)
239                     {
240                         // format the date field correctly
241
if (isDate)
242                         {
243                             // this is to be consistent with the existing setup.
244
// seems like an odd place to put it though (FIXME)
245
String JavaDoc thumbs = "";
246                             if (showThumbs)
247                             {
248                                 thumbs = getThumbMarkup(hrq, items[i]);
249                             }
250                             DCDate dd = new DCDate(metadataArray[0].value);
251                             metadata = UIUtil.displayDate(dd, false, false) + thumbs;
252                         }
253                         // format the title field correctly
254
else if (field.equals(titleField))
255                         {
256                             metadata = "<a HREF=\"" + hrq.getContextPath() + "/handle/"
257                             + items[i].getHandle() + "\">"
258                             + Utils.addEntities(metadataArray[0].value)
259                             + "</a>";
260                         }
261                         // format all other fields
262
else
263                         {
264                             StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
265                             for (int j = 0; j < metadataArray.length; j++)
266                             {
267                                 sb.append(Utils.addEntities(metadataArray[j].value));
268                                 if (j < (metadataArray.length - 1))
269                                 {
270                                     sb.append("; ");
271                                 }
272                             }
273                             metadata = "<em>" + sb.toString() + "</em>";
274                         }
275                     }
276                     
277                     // now prepare the XHTML frag for this division
278
String JavaDoc rOddOrEven;
279                     if (i == highlightRow)
280                     {
281                         rOddOrEven = "highlight";
282                     }
283                     else
284                     {
285                         rOddOrEven = ((i % 2) == 1 ? "odd" : "even");
286                     }
287                     
288                     // prepare extra special layout requirements for dates
289
String JavaDoc extras = "";
290                     if (isDate)
291                     {
292                         extras = "nowrap=\"nowrap\" align=\"right\"";
293                     }
294                     
295                     int idx = ((i + 1) * columns) - columns + colCount - 1;
296                     frags[idx] = "<td headers=\"" + id + "\" class=\""
297                         + rOddOrEven + "Row" + cOddOrEven + "Col\" " + extras + ">"
298                         + (emph ? "<strong>" : "") + metadata + (emph ? "</strong>" : "")
299                         + "</td>";
300                     
301                 }
302                 
303                 colCount++;
304                 isDate = false;
305                 emph = false;
306             }
307             
308             out.println("</tr>");
309             
310             // now output all the frags in the right order for the page
311
for (int i = 0; i < frags.length; i++)
312             {
313                 if ((i + 1) % columns == 1)
314                 {
315                     out.println("<tr>");
316                 }
317                 out.println(frags[i]);
318                 if ((i + 1) % columns == 0)
319                 {
320                     out.println("</tr>");
321                 }
322             }
323             
324             // close the table
325
out.println("</table>");
326         }
327         catch (IOException JavaDoc ie)
328         {
329             throw new JspException JavaDoc(ie);
330         }
331
332         return SKIP_BODY;
333     }
334
335     /**
336      * Get the items to list
337      *
338      * @return the items
339      */

340     public Item[] getItems()
341     {
342         return items;
343     }
344
345     /**
346      * Set the items to list
347      *
348      * @param itemsIn
349      * the items
350      */

351     public void setItems(Item[] itemsIn)
352     {
353         items = itemsIn;
354     }
355
356     /**
357      * Get the row to highlight - null or -1 for no row
358      *
359      * @return the row to highlight
360      */

361     public String JavaDoc getHighlightrow()
362     {
363         return String.valueOf(highlightRow);
364     }
365
366     /**
367      * Set the row to highlight
368      *
369      * @param highlightRowIn
370      * the row to highlight or -1 for no highlight
371      */

372     public void setHighlightrow(String JavaDoc highlightRowIn)
373     {
374         if ((highlightRowIn == null) || highlightRowIn.equals(""))
375         {
376             highlightRow = -1;
377         }
378         else
379         {
380             try
381             {
382                 highlightRow = Integer.parseInt(highlightRowIn);
383             }
384             catch (NumberFormatException JavaDoc nfe)
385             {
386                 highlightRow = -1;
387             }
388         }
389     }
390
391     /**
392      * Get the column to emphasise - "title", "date" or null
393      *
394      * @return the column to emphasise
395      */

396     public String JavaDoc getEmphcolumn()
397     {
398         return emphColumn;
399     }
400
401     /**
402      * Set the column to emphasise - "title", "date" or null
403      *
404      * @param emphColumnIn
405      * column to emphasise
406      */

407     public void setEmphcolumn(String JavaDoc emphColumnIn)
408     {
409         emphColumn = emphColumnIn;
410     }
411
412     public void release()
413     {
414         highlightRow = -1;
415         emphColumn = null;
416         items = null;
417     }
418
419     /* get the required thumbnail config items */
420     private void getThumbSettings()
421     {
422         showThumbs = ConfigurationManager
423                 .getBooleanProperty("webui.browse.thumbnail.show");
424
425         if (showThumbs)
426         {
427             thumbItemListMaxHeight = ConfigurationManager
428                     .getIntProperty("webui.browse.thumbnail.maxheight");
429
430             if (thumbItemListMaxHeight == 0)
431             {
432                 thumbItemListMaxHeight = ConfigurationManager
433                         .getIntProperty("thumbnail.maxheight");
434             }
435
436             thumbItemListMaxWidth = ConfigurationManager
437                     .getIntProperty("webui.browse.thumbnail.maxwidth");
438
439             if (thumbItemListMaxWidth == 0)
440             {
441                 thumbItemListMaxWidth = ConfigurationManager
442                         .getIntProperty("thumbnail.maxwidth");
443             }
444         }
445
446         String JavaDoc linkBehaviour = ConfigurationManager
447                 .getProperty("webui.browse.thumbnail.linkbehaviour");
448
449         if (linkBehaviour != null)
450         {
451             if (linkBehaviour.equals("bitstream"))
452             {
453                 linkToBitstream = true;
454             }
455         }
456     }
457
458     /*
459      * Get the (X)HTML width and height attributes. As the browser is being used
460      * for scaling, we only scale down otherwise we'll get hideously chunky
461      * images. This means the media filter should be run with the maxheight and
462      * maxwidth set greater than or equal to the size of the images required in
463      * the search/browse
464      */

465     private String JavaDoc getScalingAttr(HttpServletRequest JavaDoc hrq, Bitstream bitstream)
466             throws JspException JavaDoc
467     {
468         BufferedImage JavaDoc buf;
469
470         try
471         {
472             Context c = UIUtil.obtainContext(hrq);
473
474             InputStream JavaDoc is = BitstreamStorageManager.retrieve(c, bitstream
475                     .getID());
476
477             //AuthorizeManager.authorizeAction(bContext, this, Constants.READ);
478
// read in bitstream's image
479
buf = ImageIO.read(is);
480             is.close();
481         }
482         catch (SQLException JavaDoc sqle)
483         {
484             throw new JspException JavaDoc(sqle.getMessage());
485         }
486         catch (IOException JavaDoc ioe)
487         {
488             throw new JspException JavaDoc(ioe.getMessage());
489         }
490
491         // now get the image dimensions
492
float xsize = (float) buf.getWidth(null);
493         float ysize = (float) buf.getHeight(null);
494
495         // scale by x first if needed
496
if (xsize > (float) thumbItemListMaxWidth)
497         {
498             // calculate scaling factor so that xsize * scale = new size (max)
499
float scale_factor = (float) thumbItemListMaxWidth / xsize;
500
501             // now reduce x size and y size
502
xsize = xsize * scale_factor;
503             ysize = ysize * scale_factor;
504         }
505
506         // scale by y if needed
507
if (ysize > (float) thumbItemListMaxHeight)
508         {
509             float scale_factor = (float) thumbItemListMaxHeight / ysize;
510
511             // now reduce x size
512
// and y size
513
xsize = xsize * scale_factor;
514             ysize = ysize * scale_factor;
515         }
516
517         StringBuffer JavaDoc sb = new StringBuffer JavaDoc("width=\"").append(xsize).append(
518                 "\" height=\"").append(ysize).append("\"");
519
520         return sb.toString();
521     }
522
523     /* generate the (X)HTML required to show the thumbnail */
524     private String JavaDoc getThumbMarkup(HttpServletRequest JavaDoc hrq, Item item)
525             throws JspException JavaDoc
526     {
527         Bundle[] original = null;
528         
529         try
530         {
531             original = item.getBundles("ORIGINAL");
532         }
533         catch(SQLException JavaDoc sqle)
534         {
535             throw new JspException JavaDoc(sqle.getMessage());
536         }
537
538         if (original.length == 0)
539         {
540             return "";
541         }
542         
543         boolean html = false;
544
545         // if multiple bitstreams, check if the primary one is HTML
546
if (original[0].getBitstreams().length > 1)
547         {
548             Bitstream[] bitstreams = original[0].getBitstreams();
549
550             for (int i = 0; (i < bitstreams.length) && !html; i++)
551             {
552                 if (bitstreams[i].getID() == original[0]
553                         .getPrimaryBitstreamID())
554                 {
555                     html = bitstreams[i].getFormat().getMIMEType().equals(
556                             "text/html");
557                 }
558             }
559         }
560
561         try
562         {
563             Bundle[] thumbs = item.getBundles("THUMBNAIL");
564
565             // if there are thumbs and we're not dealing with an HTML item
566
// then show the thumbnail
567
if ((thumbs.length > 0) && !html)
568             {
569                 Context c = UIUtil.obtainContext(hrq);
570
571                 Bitstream thumbnailBitstream;
572                 Bitstream originalBitstream;
573
574                 if ((original[0].getBitstreams().length > 1)
575                         && (original[0].getPrimaryBitstreamID() > -1))
576                 {
577                     originalBitstream = Bitstream.find(c, original[0]
578                             .getPrimaryBitstreamID());
579                     thumbnailBitstream = thumbs[0]
580                             .getBitstreamByName(originalBitstream.getName()
581                                     + ".jpg");
582                 }
583                 else
584                 {
585                     originalBitstream = original[0].getBitstreams()[0];
586                     thumbnailBitstream = thumbs[0].getBitstreams()[0];
587                 }
588
589                 if ((thumbnailBitstream != null)
590                         && (AuthorizeManager.authorizeActionBoolean(c,
591                                 thumbnailBitstream, Constants.READ)))
592                 {
593                     StringBuffer JavaDoc thumbLink;
594
595                     if (linkToBitstream)
596                     {
597                         thumbLink = new StringBuffer JavaDoc(
598                                 "<br/><a target=\"_blank\" HREF=\"").append(
599                                 hrq.getContextPath()).append("/bitstream/")
600                                 .append(item.getHandle()).append("/").append(
601                                         originalBitstream.getSequenceID())
602                                 .append("/").append(
603                                         UIUtil.encodeBitstreamName(originalBitstream
604                                                 .getName(),
605                                                 Constants.DEFAULT_ENCODING));
606                     }
607                     else
608                     {
609                         thumbLink = new StringBuffer JavaDoc("<br/><a HREF=\"").append(
610                                 hrq.getContextPath()).append("/handle/")
611                                 .append(item.getHandle());
612                     }
613
614                     thumbLink.append("\"><img SRC=\"").append(
615                             hrq.getContextPath()).append("/retrieve/").append(
616                             thumbnailBitstream.getID()).append("/").append(
617                                     UIUtil.encodeBitstreamName(thumbnailBitstream.getName(),
618                                     Constants.DEFAULT_ENCODING)).append(
619                             "\" alt=\"").append(thumbnailBitstream.getName())
620                             .append("\" ").append(
621                                     getScalingAttr(hrq, thumbnailBitstream))
622                             .append("/></a>");
623
624                     return thumbLink.toString();
625                 }
626             }
627         }
628         catch (SQLException JavaDoc sqle)
629         {
630             throw new JspException JavaDoc(sqle.getMessage());
631         }
632         catch (UnsupportedEncodingException JavaDoc e)
633         {
634             throw new JspException JavaDoc(
635                         "Server does not support DSpace's default encoding. ",
636                         e);
637         }
638
639         return "";
640     }
641 }
642
Popular Tags