View Javadoc

1   /***
2    * Copyright (c) 2003 held jointly by the individual authors.            
3    *                                                                          
4    * This library is free software; you can redistribute it and/or modify it    
5    * under the terms of the GNU Lesser General Public License as published      
6    * by the Free Software Foundation; either version 2.1 of the License, or 
7    * (at your option) any later version.                                            
8    *                                                                            
9    * This library is distributed in the hope that it will be useful, but 
10   * WITHOUT ANY WARRANTY; with out even the implied warranty of 
11   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
12   * GNU Lesser General Public License for more details.                                                  
13   *                                                                           
14   * You should have received a copy of the GNU Lesser General Public License   
15   * along with this library;  if not, write to the Free Software Foundation,   
16   * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA.              
17   *                                                                            
18   * > http://www.gnu.org/copyleft/lesser.html                                  
19   * > http://www.opensource.org/licenses/lgpl-license.php
20   */
21  package net.mlw.vlh.web.util;
22  
23  import java.io.IOException;
24  import java.text.MessageFormat;
25  import java.util.ArrayList;
26  import java.util.Calendar;
27  import java.util.Collection;
28  import java.util.Collections;
29  import java.util.Iterator;
30  import java.util.Locale;
31  import java.util.Map;
32  import java.util.StringTokenizer;
33  
34  import javax.servlet.jsp.JspException;
35  import javax.servlet.jsp.JspWriter;
36  import javax.servlet.jsp.PageContext;
37  import javax.servlet.jsp.tagext.BodyContent;
38  import javax.servlet.jsp.tagext.Tag;
39  
40  import org.apache.commons.logging.Log;
41  import org.apache.commons.logging.LogFactory;
42  
43  /***
44   * A lot of this functionality is in the Struts ResponceUtils, but I do not want
45   * to create a dependicy to struts.
46   * 
47   * @author Matthew L. Wilson, Andrej Zachar
48   * @version $Revision: 1.7 $ $Date: 2005/11/23 14:32:58 $
49   */
50  public final class JspUtils
51  {
52  
53     private static final Log LOGGER = LogFactory.getLog(JspUtils.class);
54  
55     /*** Private to protect singleton. */
56     private JspUtils()
57     {
58     }
59  
60     /***
61      * Write the specified text as the response to the writer associated with
62      * this page. <strong>WARNING </strong>- If you are writing body content from
63      * the <code>doAfterBody()</code> method of a custom tag class that
64      * implements <code>BodyTag</code>, you should be calling
65      * <code>writePrevious()</code> instead.
66      * 
67      * @param pageContext
68      *           The PageContext object for this page
69      * @param text
70      *           The text to be written
71      * 
72      * @exception JspException
73      *               if an input/output error occurs
74      */
75     public static void write(PageContext pageContext, String text) throws JspException
76     {
77  
78        JspWriter writer = pageContext.getOut();
79  
80        try
81        {
82           writer.print(text);
83        }
84        catch (IOException e)
85        {
86           LOGGER.error("JspUtils.write() exception...", e);
87           throw new JspException(e);
88        }
89  
90     }
91  
92     /***
93      * Write the specified text as the response to the writer associated with the
94      * body content for the tag within which we are currently nested.
95      * 
96      * @param pageContext
97      *           The PageContext object for this page
98      * @param text
99      *           The text to be written
100     * 
101     * @exception JspException
102     *               if an input/output error occurs
103     */
104    public static void writePrevious(PageContext pageContext, String text) throws JspException
105    {
106       JspWriter writer = pageContext.getOut();
107       if (writer instanceof BodyContent)
108       {
109          writer = ((BodyContent) writer).getEnclosingWriter();
110       }
111 
112       try
113       {
114          writer.print(text);
115       }
116       catch (IOException e)
117       {
118          LOGGER.error("JspUtils.writePrevious() exception...", e);
119          throw new JspException(e);
120       }
121 
122    }
123 
124    /***
125     * Converts a stirng into a collection of strings.
126     * 
127     * @param value
128     *           The string to be parsed.
129     * @param token
130     *           The token to be used.
131     * @return A Collection of String(s).
132     */
133    public static Collection toCollection(String value, String token)
134    {
135       if (value == null || value.length() == 0)
136       {
137          return Collections.EMPTY_LIST;
138       }
139 
140       Collection elements = new ArrayList();
141       for (StringTokenizer st = new StringTokenizer(value, token); st.hasMoreElements();)
142       {
143          elements.add(st.nextToken());
144       }
145 
146       return elements;
147    }
148 
149    public static String format(Object value, String format, Locale loc)
150    {
151       if (value == null)
152       {
153          return "";
154       }
155       else
156       {
157          if (value instanceof Number)
158          {
159             if (format == null || format.length() == 0)
160             {
161                return value.toString();
162             }
163             MessageFormat mf = new MessageFormat("{0,number," + format + "}");
164             if (loc != null)
165             {
166                mf.setLocale(loc);
167                mf.applyPattern(mf.toPattern());
168             }
169 
170             return mf.format(new Object[]
171             { value });
172          }
173          else if (value instanceof java.util.Date)
174          {
175             if (format == null || format.length() == 0)
176             {
177                //TODO: get the default date format in here somehow. format =
178                // SystemProperties.getProperty("default.dateFormat", "EEE, MMM
179                // d, ''yy");
180                format = "EEE, MMM d, ''yy";
181             }
182             MessageFormat mf = new MessageFormat("{0,date," + format + "}");
183             if (loc != null)
184             {
185                mf.setLocale(loc);
186                mf.applyPattern(mf.toPattern());
187             }
188             return mf.format(new Object[]
189             { value });
190          }
191          else if (value instanceof Calendar)
192          {
193             Calendar calendar = (Calendar) value;
194             if (format == null || format.length() == 0)
195             {
196                //TODO: get the default date format in here somehow. format =
197                // SystemProperties.getProperty("default.dateFormat", "EEE, MMM
198                // d, ''yy");
199                format = "EEE, MMM d, ''yy";
200             }
201 
202             MessageFormat mf = new MessageFormat("{0,date," + format + "}");
203             if (loc != null)
204             {
205                mf.setLocale(loc);
206                mf.applyPattern(mf.toPattern());
207             }
208             return mf.format(new Object[]
209             { value });
210          }
211          else
212          {
213             return value.toString();
214          }
215 
216       }
217    }
218 
219    public static String toAttributesString(Map map)
220    {
221       StringBuffer sb = new StringBuffer();
222 
223       for (Iterator iter = map.keySet().iterator(); iter.hasNext();)
224       {
225          Object key = iter.next();
226          sb.append(key).append("=\"").append(map.get(key)).append("\" ");
227       }
228 
229       return sb.toString();
230    }
231 
232    public static Tag getParent(Tag self, Class klass) throws JspException
233    {
234       Tag tag = self.getParent();
235 
236       while (!(klass.isAssignableFrom(tag.getClass())))
237       {
238          tag = tag.getParent();
239          if (tag == null)
240          {
241             final String message = "Parent tag of class " + klass + " of the tag's class " + self + " was not found.";
242             LOGGER.error(message);
243             throw new JspException(message);
244          }
245       }
246       return tag;
247    }
248 }