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