KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > javax > faces > convert > NumberConverter


1 /*
2  * Copyright 2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package javax.faces.convert;
17
18 import javax.faces.component.UIComponent;
19 import javax.faces.component.StateHolder;
20 import javax.faces.context.FacesContext;
21 import java.text.DecimalFormat JavaDoc;
22 import java.text.DecimalFormatSymbols JavaDoc;
23 import java.text.NumberFormat JavaDoc;
24 import java.text.ParseException JavaDoc;
25 import java.util.Currency JavaDoc;
26 import java.util.Locale JavaDoc;
27
28 /**
29  * @author Thomas Spiegl (latest modification by $Author: svieujot $)
30  * @version $Revision: 1.12 $ $Date: 2005/04/09 19:07:02 $
31  * $Log: NumberConverter.java,v $
32  * Revision 1.12 2005/04/09 19:07:02 svieujot
33  * Closed MYFACES-177 thanks to Josh Holtzman.
34  *
35  * Revision 1.11 2004/07/01 22:00:51 mwessendorf
36  * ASF switch
37  *
38  * Revision 1.10 2004/06/07 13:40:37 mwessendorf
39  * solved Feature Request #966892
40  *
41  * Revision 1.9 2004/04/01 10:39:53 royalts
42  * implements StateHoder was missing
43  *
44  * Revision 1.8 2004/03/26 12:08:42 manolito
45  * Exceptions in getAsString now catched and
46  * more relaxed Number casting in all number converters
47  *
48  */

49 public class NumberConverter
50         implements Converter, StateHolder
51 {
52     private static final String JavaDoc CONVERSION_MESSAGE_ID = "javax.faces.convert.NumberConverter.CONVERSION";
53
54     // FIELDS
55
public static final String JavaDoc CONVERTER_ID = "javax.faces.Number";
56
57     public static final boolean JAVA_VERSION_14;
58
59     static
60     {
61         JAVA_VERSION_14 = checkJavaVersion14();
62     }
63
64     private String JavaDoc _currencyCode;
65     private String JavaDoc _currencySymbol;
66     private Locale JavaDoc _locale;
67     private int _maxFractionDigits;
68     private int _maxIntegerDigits;
69     private int _minFractionDigits;
70     private int _minIntegerDigits;
71     private String JavaDoc _pattern;
72     private String JavaDoc _type;
73     private boolean _groupingUsed = true;
74     private boolean _integerOnly = false;
75     private boolean _transient;
76
77     private boolean _maxFractionDigitsSet;
78     private boolean _maxIntegerDigitsSet;
79     private boolean _minFractionDigitsSet;
80     private boolean _minIntegerDigitsSet;
81
82
83     // CONSTRUCTORS
84
public NumberConverter()
85     {
86     }
87
88     // METHODS
89
public Object JavaDoc getAsObject(FacesContext facesContext, UIComponent uiComponent, String JavaDoc value)
90     {
91         if (facesContext == null) throw new NullPointerException JavaDoc("facesContext");
92         if (uiComponent == null) throw new NullPointerException JavaDoc("uiComponent");
93
94         if (value != null)
95         {
96             value = value.trim();
97             if (value.length() > 0)
98             {
99                 NumberFormat JavaDoc format = getNumberFormat(facesContext);
100                 format.setParseIntegerOnly(_integerOnly);
101                 try
102                 {
103                     return format.parse(value);
104                 }
105                 catch (ParseException JavaDoc e)
106                 {
107                     throw new ConverterException(_MessageUtils.getErrorMessage(facesContext,
108                                                                                CONVERSION_MESSAGE_ID,
109                                                                                new Object JavaDoc[]{uiComponent.getId(),value}), e);
110                 }
111             }
112         }
113         return null;
114     }
115
116     public String JavaDoc getAsString(FacesContext facesContext, UIComponent uiComponent, Object JavaDoc value)
117     {
118         if (facesContext == null) throw new NullPointerException JavaDoc("facesContext");
119         if (uiComponent == null) throw new NullPointerException JavaDoc("uiComponent");
120
121         if (value == null)
122         {
123             return "";
124         }
125         if (value instanceof String JavaDoc)
126         {
127             return (String JavaDoc)value;
128         }
129
130         NumberFormat JavaDoc format = getNumberFormat(facesContext);
131         format.setGroupingUsed(_groupingUsed);
132         if (_maxFractionDigitsSet) format.setMaximumFractionDigits(_maxFractionDigits);
133         if (_maxIntegerDigitsSet) format.setMaximumIntegerDigits(_maxIntegerDigits);
134         if (_minFractionDigitsSet) format.setMinimumFractionDigits(_minFractionDigits);
135         if (_minIntegerDigitsSet) format.setMinimumIntegerDigits(_minIntegerDigits);
136         formatCurrency(format);
137         try
138         {
139             return format.format(value);
140         }
141         catch (Exception JavaDoc e)
142         {
143             throw new ConverterException("Cannot convert value '" + value + "'");
144         }
145     }
146
147     private NumberFormat JavaDoc getNumberFormat(FacesContext facesContext)
148     {
149         Locale JavaDoc lokale = _locale != null ? _locale : facesContext.getViewRoot().getLocale();
150
151         if (_pattern == null && _type == null)
152         {
153             throw new ConverterException("Cannot get NumberFormat, either type or pattern needed.");
154         }
155
156         // pattern
157
if (_pattern != null)
158         {
159             return new DecimalFormat JavaDoc(_pattern, new DecimalFormatSymbols JavaDoc(lokale));
160         }
161
162         // type
163
if (_type.equals("number"))
164         {
165             return NumberFormat.getNumberInstance(lokale);
166         }
167         else if (_type.equals("currency"))
168         {
169             return NumberFormat.getCurrencyInstance(lokale);
170         }
171         else if (_type.equals("percentage"))
172         {
173             return NumberFormat.getPercentInstance(lokale);
174         }
175         throw new ConverterException("Cannot get NumberFormat, illegal type " + _type);
176     }
177
178     private void formatCurrency(NumberFormat JavaDoc format)
179     {
180         if (_currencyCode == null && _currencySymbol == null)
181         {
182             return;
183         }
184
185         boolean useCurrencyCode;
186         if (JAVA_VERSION_14)
187         {
188             useCurrencyCode = _currencyCode != null;
189         }
190         else
191         {
192             useCurrencyCode = _currencySymbol == null;
193         }
194
195         if (useCurrencyCode)
196         {
197             // set Currency
198
try
199             {
200                 format.setCurrency(Currency.getInstance(_currencyCode));
201             }
202             catch (Exception JavaDoc e)
203             {
204                 throw new ConverterException("Unable to get Currency instance for currencyCode " +
205                                              _currencyCode);
206             }
207         }
208         else if (format instanceof DecimalFormat JavaDoc)
209
210         {
211             DecimalFormat JavaDoc dFormat = (DecimalFormat JavaDoc)format;
212             DecimalFormatSymbols JavaDoc symbols = dFormat.getDecimalFormatSymbols();
213             symbols.setCurrencySymbol(_currencySymbol);
214             dFormat.setDecimalFormatSymbols(symbols);
215         }
216     }
217
218     // STATE SAVE/RESTORE
219
public void restoreState(FacesContext facesContext, Object JavaDoc state)
220     {
221         Object JavaDoc values[] = (Object JavaDoc[])state;
222         _currencyCode = (String JavaDoc)values[0];
223         _currencySymbol = (String JavaDoc)values[1];
224         _locale = (Locale JavaDoc)values[2];
225         Integer JavaDoc value = (Integer JavaDoc)values[3];
226         _maxFractionDigits = value != null ? value.intValue() : 0;
227         value = (Integer JavaDoc)values[4];
228         _maxIntegerDigits = value != null ? value.intValue() : 0;
229         value = (Integer JavaDoc)values[5];
230         _minFractionDigits = value != null ? value.intValue() : 0;
231         value = (Integer JavaDoc)values[6];
232         _minIntegerDigits = value != null ? value.intValue() : 0;
233         _pattern = (String JavaDoc)values[7];
234         _type = (String JavaDoc)values[8];
235         _groupingUsed = ((Boolean JavaDoc)values[9]).booleanValue();
236         _integerOnly = ((Boolean JavaDoc)values[10]).booleanValue();
237         _maxFractionDigitsSet = ((Boolean JavaDoc)values[11]).booleanValue();
238         _maxIntegerDigitsSet = ((Boolean JavaDoc)values[12]).booleanValue();
239         _minFractionDigitsSet = ((Boolean JavaDoc)values[13]).booleanValue();
240         _minIntegerDigitsSet = ((Boolean JavaDoc)values[14]).booleanValue();
241     }
242
243     public Object JavaDoc saveState(FacesContext facesContext)
244     {
245         Object JavaDoc values[] = new Object JavaDoc[15];
246         values[0] = _currencyCode;
247         values[1] = _currencySymbol;
248         values[2] = _locale;
249         values[3] = _maxFractionDigitsSet ? new Integer JavaDoc(_maxFractionDigits) : null;
250         values[4] = _maxIntegerDigitsSet ? new Integer JavaDoc(_maxIntegerDigits) : null;
251         values[5] = _minFractionDigitsSet ? new Integer JavaDoc(_minFractionDigits) : null;
252         values[6] = _minIntegerDigitsSet ? new Integer JavaDoc(_minIntegerDigits) : null;
253         values[7] = _pattern;
254         values[8] = _type;
255         values[9] = _groupingUsed ? Boolean.TRUE : Boolean.FALSE;
256         values[10] = _integerOnly ? Boolean.TRUE : Boolean.FALSE;
257         values[11] = _maxFractionDigitsSet ? Boolean.TRUE : Boolean.FALSE;
258         values[12] = _maxIntegerDigitsSet ? Boolean.TRUE : Boolean.FALSE;
259         values[13] = _minFractionDigitsSet ? Boolean.TRUE : Boolean.FALSE;
260         values[14] = _minIntegerDigitsSet ? Boolean.TRUE : Boolean.FALSE;
261         return values;
262     }
263
264     // GETTER & SETTER
265
public String JavaDoc getCurrencyCode()
266     {
267         return _currencyCode != null ?
268                _currencyCode :
269                getDecimalFormatSymbols().getInternationalCurrencySymbol();
270     }
271
272     public void setCurrencyCode(String JavaDoc currencyCode)
273     {
274         _currencyCode = currencyCode;
275     }
276
277     public String JavaDoc getCurrencySymbol()
278     {
279         return _currencySymbol != null ?
280                _currencySymbol :
281                getDecimalFormatSymbols().getCurrencySymbol();
282     }
283
284     public void setCurrencySymbol(String JavaDoc currencySymbol)
285     {
286         _currencySymbol = currencySymbol;
287     }
288
289     public boolean isGroupingUsed()
290     {
291         return _groupingUsed;
292     }
293
294     public void setGroupingUsed(boolean groupingUsed)
295     {
296         _groupingUsed = groupingUsed;
297     }
298
299     public boolean isIntegerOnly()
300     {
301         return _integerOnly;
302     }
303
304     public void setIntegerOnly(boolean integerOnly)
305     {
306         _integerOnly = integerOnly;
307     }
308
309     public Locale JavaDoc getLocale()
310     {
311         if (_locale != null) return _locale;
312         FacesContext context = FacesContext.getCurrentInstance();
313         return context.getViewRoot().getLocale();
314     }
315
316     public void setLocale(Locale JavaDoc locale)
317     {
318         _locale = locale;
319     }
320
321     public int getMaxFractionDigits()
322     {
323         return _maxFractionDigits;
324     }
325
326     public void setMaxFractionDigits(int maxFractionDigits)
327     {
328         _maxFractionDigitsSet = true;
329         _maxFractionDigits = maxFractionDigits;
330     }
331
332     public int getMaxIntegerDigits()
333     {
334         return _maxIntegerDigits;
335     }
336
337     public void setMaxIntegerDigits(int maxIntegerDigits)
338     {
339         _maxIntegerDigitsSet = true;
340         _maxIntegerDigits = maxIntegerDigits;
341     }
342
343     public int getMinFractionDigits()
344     {
345         return _minFractionDigits;
346     }
347
348     public void setMinFractionDigits(int minFractionDigits)
349     {
350         _minFractionDigitsSet = true;
351         _minFractionDigits = minFractionDigits;
352     }
353
354     public int getMinIntegerDigits()
355     {
356         return _minIntegerDigits;
357     }
358
359     public void setMinIntegerDigits(int minIntegerDigits)
360     {
361         _minIntegerDigitsSet = true;
362         _minIntegerDigits = minIntegerDigits;
363     }
364
365     public String JavaDoc getPattern()
366     {
367         return _pattern;
368     }
369
370     public void setPattern(String JavaDoc pattern)
371     {
372         _pattern = pattern;
373     }
374
375     public boolean isTransient()
376     {
377         return _transient;
378     }
379
380     public void setTransient(boolean aTransient)
381     {
382         _transient = aTransient;
383     }
384
385     public String JavaDoc getType()
386     {
387         return _type;
388     }
389
390     public void setType(String JavaDoc type)
391     {
392         //TODO: validate type
393
_type = type;
394     }
395
396     private static boolean checkJavaVersion14()
397     {
398         String JavaDoc version = System.getProperty("java.version");
399         if (version == null)
400         {
401             return false;
402         }
403         byte java14 = 0;
404         for (int idx = version.indexOf('.'), i = 0; idx > 0 || version != null; i++)
405         {
406             if (idx > 0)
407             {
408                 byte value = Byte.parseByte(version.substring(0, 1));
409                 version = version.substring(idx + 1, version.length());
410                 idx = version.indexOf('.');
411                 switch (i)
412                 {
413                     case 0:
414                         if (value == 1)
415                         {
416                             java14 = 1;
417                             break;
418                         }
419                         else if (value > 1)
420                         {
421                             java14 = 2;
422                         }
423                     case 1:
424                         if (java14 > 0 && value >= 4)
425                         {
426                             java14 = 2;
427                         }
428                         ;
429                     default:
430                         idx = 0;
431                         version = null;
432                         break;
433                 }
434             }
435             else
436             {
437                 byte value = Byte.parseByte(version.substring(0, 1));
438                 if (java14 > 0 && value >= 4)
439                 {
440                     java14 = 2;
441                 }
442                 break;
443             }
444         }
445         return java14 == 2;
446     }
447
448
449     public DecimalFormatSymbols JavaDoc getDecimalFormatSymbols()
450     {
451         return new DecimalFormatSymbols JavaDoc(getLocale());
452     }
453 }
454
Popular Tags