View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.myfaces.commons.util;
20  
21  
22  import org.apache.commons.logging.Log;
23  import org.apache.commons.logging.LogFactory;
24  
25  import java.text.DateFormat;
26  import java.text.ParseException;
27  import java.text.SimpleDateFormat;
28  
29  import java.util.ArrayList;
30  import java.util.Date;
31  import java.util.Locale;
32  
33  import javax.el.ELContext;
34  import javax.el.ExpressionFactory;
35  import javax.el.ValueExpression;
36  import javax.faces.context.FacesContext;
37  
38  /**
39   * Utility class for Tag classes
40   *
41   * @version $Name:  $ ($Revision: adfrt/faces/adf-faces-impl/src/main/java/oracle/adfinternal/view/faces/taglib/util/TagUtils.java#1 $) $Date: 11-nov-2005.14:59:38 $
42   *
43   */
44  public final class TagUtils
45  {
46    private static final Log LOG = LogFactory.getLog(TagUtils.class);
47  
48    private TagUtils()
49    {
50    }
51  
52    public static ValueExpression getValueExpression(String valueExpression, Class<?> expectedType)
53    {
54      FacesContext context = FacesContext.getCurrentInstance();
55      ELContext elContext = context.getELContext();
56      ExpressionFactory fact = context.getApplication().getExpressionFactory();
57      
58      return fact.createValueExpression(elContext, valueExpression, expectedType);
59    }
60  
61    public static void assertNotNull(Object object)
62    {
63      if (null == object)
64        throw new NullPointerException();
65    }
66  
67    // Helpful with tag auto generation. Though this isn't really required.
68    /**
69     * Return the same string. It is there for convenience and makes life easy
70     * while auto generating tags.
71     * @param value
72     * @return
73     */
74    public static String getString(
75      Object value)
76    {
77      if (value == null)
78        return null;
79  
80      return value.toString();
81    }
82  
83    /**
84     * String --> boolean
85     * @param value
86     * @return
87     */
88    public static boolean getBoolean(
89      Object  value)
90    {
91      if (value == null)
92        return false;
93      
94      if (value instanceof Boolean)
95        return ((Boolean) value).booleanValue();
96  
97      return Boolean.valueOf(value.toString()).booleanValue();
98    }
99  
100   /**
101    * String --> int
102    * @param value
103    * @return
104    */
105   public static int getInteger(
106     Object  value)
107   {
108     if (value == null)
109       return 0;
110 
111     if (value instanceof Number)
112       return ((Number) value).intValue();
113 
114     return Integer.valueOf(value.toString()).intValue();
115 
116   }
117 
118   /**
119    * String --> long
120    * @param value
121    * @return
122    */
123   public static long getLong(
124     Object      value)
125   {
126     if (value == null)
127       return 0;
128 
129     return Long.valueOf(value.toString()).longValue();
130   }
131 
132   /**
133    * String --> long
134    * @param value
135    * @return
136    */
137   public static double getDouble(
138     Object      value)
139   {
140     if (value == null)
141       return 0;
142 
143     return Double.valueOf(value.toString()).doubleValue();
144 
145   }
146 
147   /**
148    * String --> long
149    * @param value
150    * @return
151    */
152   public static float getFloat(
153     Object      value)
154   {
155     if (value == null)
156       return 0;
157 
158     return Float.valueOf(value.toString()).floatValue();
159   }
160 
161   /**
162    * These are normally NMTOKEN type in attributes
163    * String --> String[]
164    * @param value
165    * @return
166    */
167   /**
168    * These are normally NMTOKEN type in attributes
169    * String --> String[]
170    * @param value
171    * @return
172    */
173   public static String[] getStringArray(
174     Object  value) throws ParseException
175   {
176     if (value == null)
177       return null;
178 
179     return getTokensArray(value.toString());
180   }
181 
182   /**
183    *  ISO Date String --> Date
184    * @param value
185    * @return
186    */
187   public static Date getDate(
188     Object   value)
189   {
190     if (value == null)
191       return null;
192 
193     if (value instanceof Date)
194       return ((Date) value);
195 
196     return parseISODate(value.toString());
197   }
198 
199   /**
200    * String --> Locale
201    * @param value
202    * @return
203    */
204   public static Locale getLocale(
205     Object      value)
206   {
207     if (value == null)
208       return null;
209 
210     if (value instanceof Locale)
211       return ((Locale) value);
212 
213     return getLocaleInternal(value.toString());
214   }
215 
216   /**
217    * String --> TimeZone
218    * @param value
219    * @return
220 
221   public static TimeZone getTimeZone(
222     String value)
223   {
224     return DateUtils.getSupportedTimeZone(value);
225   }
226    */
227 
228   public static boolean isValueReference(String expression)
229   {
230     if (null != expression)
231     {
232       int start = expression.indexOf("#{");
233       if ((start >= 0) && (expression.indexOf('}', start + 1) >= 0))
234         return true;
235     }
236 
237     return false;
238   }
239 
240 
241 
242   /**
243    * Takes a string that is a composite of tokens, extracts tokens delimited
244    *  by any whitespace character sequence combination and returns a String
245    *  array of such tokens.
246    * @throws ParseException In case of invalid character in the specified
247    *           composite. The only invalid character is a comma (',').
248    */
249   private static String[] getTokensArray(String tokenComposite)
250     throws ParseException
251   {
252     if (tokenComposite == null || "".equals(tokenComposite))
253       return null;
254 
255     return parseNameTokens(tokenComposite);
256   }
257 
258   /**
259    * Parse a string into a java.util.Date object.  The
260    * string must be in ISO 9601 format (yyyy-MM-dd).
261    * @todo why not throw the exception in a different format?
262    *       why do we kill it here and return null?
263    */
264   static private final Date parseISODate(String stringValue)
265   {
266     try
267     {
268       return getDateFormat().parse(stringValue);
269     }
270     catch (ParseException pe)
271     {
272       if (LOG.isInfoEnabled()) {
273         LOG.info("CANNOT_PARSE_VALUE_INTO_DATE_WITH_YYYY_MM_DD_PATTERN "+ stringValue, pe);
274       }
275       return null;
276     }
277   }
278   
279   /**
280    * Parses a whitespace separated series of name tokens.
281    * @param stringValue the full string
282    * @return an array of each constituent value, or null
283    *  if there are no tokens (that is, the string is empty or
284    *  all whitespace)
285    */
286   static public String[] parseNameTokens(String stringValue)
287   {
288     if (stringValue == null)
289       return null;
290 
291     ArrayList<String> list = new ArrayList<String>(5);
292 
293     int     length = stringValue.length();
294     boolean inSpace = true;
295     int     start = 0;
296     for (int i = 0; i < length; i++)
297     {
298       char ch = stringValue.charAt(i);
299 
300       // We're in whitespace;  if we've just departed
301       // a run of non-whitespace, append a string.
302       // Now, why do we use the supposedly deprecated "Character.isSpace()"
303       // function instead of "isWhitespace"?  We're following XML rules
304       // here for the meaning of whitespace, which specifically
305       // EXCLUDES general Unicode spaces.
306       if (Character.isWhitespace(ch))
307       {
308         if (!inSpace)
309         {
310           list.add(stringValue.substring(start, i));
311           inSpace = true;
312         }
313       }
314       // We're out of whitespace;  if we've just departed
315       // a run of whitespace, start keeping track of this string
316       else
317       {
318         if (inSpace)
319         {
320           start = i;
321           inSpace = false;
322         }
323       }
324     }
325 
326     if (!inSpace)
327       list.add(stringValue.substring(start));
328 
329     if (list.isEmpty())
330       return null;
331 
332     return list.toArray(new String[list.size()]);
333   }
334   
335 
336   private static Locale getLocaleInternal(String locale)
337   {
338     String localeStr = locale.replace('-','_');
339     String[] tokens = localeStr.split("[_]", 3);
340     Locale locl = null;
341 
342     if ( tokens.length == 1)
343     {
344       locl = new Locale(tokens[0]); //lang
345     }
346     else if (tokens.length == 2)
347     {
348       locl = new Locale(tokens[0], tokens[1]); // lang + country
349     }
350     else if (tokens.length == 3 )
351     {
352       locl = new Locale(tokens[0], tokens[1], tokens[2]); // lang + country + variant
353     }
354     else
355     {
356       if(LOG.isWarnEnabled())
357         LOG.warn("tokens length should not be greater than 3.");
358     }
359     return locl;
360   }
361 
362   // We rely strictly on ISO 8601 formats
363   private static DateFormat getDateFormat()
364   {
365     return new SimpleDateFormat("yyyy-MM-dd");
366   }
367 }