KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jdesktop > swing > data > Converters


1 /*
2  * $Id: Converters.java,v 1.1.1.1 2004/06/16 01:43:39 davidson1 Exp $
3  *
4  * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle,
5  * Santa Clara, California 95054, U.S.A. All rights reserved.
6  */

7
8 package org.jdesktop.swing.data;
9
10 import java.net.MalformedURLException JavaDoc;
11 import java.net.URL JavaDoc;
12
13 import java.text.ParseException JavaDoc;
14 import java.text.DateFormat JavaDoc;
15 import java.text.SimpleDateFormat JavaDoc;
16
17 import java.util.Date JavaDoc;
18 import java.util.Map JavaDoc;
19 import java.util.HashMap JavaDoc;
20 import java.util.Set JavaDoc;
21
22 import javax.swing.UIDefaults JavaDoc;
23
24 /**
25  * Class containing the static converter registry and a set of static Converter
26  * classes for the common Java data types:
27  * <ul>
28  * <li>java.lang.Boolean</li>
29  * <li>java.lang.String</li>
30  * <li>java.lang.Integer</li>
31  * <li>java.lang.Long</li>
32  * <li>java.lang.Short</li>
33  * <li>java.lang.Float</li>
34  * <li>java.lang.Double</li>
35  * <li>java.lang.Date</li>
36  * <li>org.jdesktop.swing.data.Link</li>
37  * </ul>
38  * Converter instances are retrieved from the registry using the class
39  * as the key. Example usage:
40  * <pre><code> Converter converter = Converters.get(Integer.class);
41  * try {
42  * Integer value = (Integer)converter.decode("99", null);
43  * }
44  * catch (ConversionException e) {
45  * // conversion error!
46  * }
47  * </code></pre>
48  * <p>
49  * Converters can also be added or replaced in the registry:
50  * <pre><code> Converters.put(Foo.class, new FooConverter());
51  * </code></pre>
52  * </p>
53  *
54  * @author Amy Fowler
55  * @version 1.0
56  */

57 public class Converters {
58     private static Map JavaDoc map;
59
60     static {
61         map = new HashMap JavaDoc();
62         map.put(Boolean JavaDoc.class, "org.jdesktop.swing.data.Converters$BooleanConverter");
63         map.put(Date JavaDoc.class, "org.jdesktop.swing.data.Converters$DateConverter");
64         map.put(Double JavaDoc.class, "org.jdesktop.swing.data.Converters$DoubleConverter");
65         map.put(Float JavaDoc.class, "org.jdesktop.swing.data.Converters$FloatConverter");
66         map.put(Integer JavaDoc.class, "org.jdesktop.swing.data.Converters$IntegerConverter");
67         map.put(Link.class, "org.jdesktop.swing.data.Converters$LinkConverter");
68         map.put(Long JavaDoc.class, "org.jdesktop.swing.data.Converters$LongConverter");
69         map.put(Short JavaDoc.class, "org.jdesktop.swing.data.Converters$ShortConverter");
70         map.put(String JavaDoc.class, "org.jdesktop.swing.data.Converters$StringConverter");
71     }
72
73     /**
74      * Retrieves the converter for the class.
75      *
76      * @param klass class used as key for converter lookup
77      * @return Converter instance registered for specified class, or null if
78      * no converter is currently registered for that class
79      */

80     public static Converter get(Class JavaDoc klass) {
81     Object JavaDoc obj = map.get(klass);
82     Converter converter = null;
83     if (obj != null) {
84         if (obj instanceof String JavaDoc) {
85         try {
86             Class JavaDoc cls = Class.forName((String JavaDoc)obj);
87             converter = (Converter)cls.newInstance();
88             map.put(klass, converter);
89         } catch (Exception JavaDoc ex) {
90             converter = null;
91         }
92         } else {
93         converter = (Converter)obj;
94         }
95     }
96         return converter;
97     }
98
99     /**
100      * Registers the specified converter for the specified class, overriding
101      * any prior converter mapping for that class if it existed.
102      * @param klass class used as key for converter lookup
103      * @param converter Converter instance to be registered for the class
104      */

105     public static void put(Class JavaDoc klass, Converter converter) {
106         map.put(klass, converter);
107     }
108
109     /**
110      * Return all the types which currently have supported type converters.
111      *
112      * @return an non-null array of supported types
113      */

114     public static Class JavaDoc[] getTypes() {
115     Set JavaDoc keys = map.keySet();
116     return (Class JavaDoc[])keys.toArray(new Class JavaDoc[0]);
117     }
118
119     protected Converters() {
120     } //prevent instantiation
121

122     /**
123      * Converter for java.lang.String which passes the value
124      * unchanged. The <code>format</code> parameter is ignored.
125      */

126     static class StringConverter implements Converter {
127
128         public String JavaDoc encode(Object JavaDoc value, Object JavaDoc format)
129             throws ConversionException{
130             if (value != null && value instanceof String JavaDoc) {
131                 return (String JavaDoc)value;
132             }
133             throw new ConversionException(value, String JavaDoc.class);
134         }
135
136         public Object JavaDoc decode(String JavaDoc value, Object JavaDoc format)
137             throws ConversionException {
138             try {
139                 return value.toString();
140             }
141             catch (Exception JavaDoc e) {
142                 throw new ConversionException(value, String JavaDoc.class, e);
143             }
144         }
145     }
146
147     /**
148      * Converter for java.lang.Boolean.
149      * Conversion from String to Boolean will return Boolean.TRUE if the
150      * string value is equal to &quot;true&quot; using a case-insensitive
151      * compare and will return Boolean.FALSE for all other string values.
152      * The <code>format</code> parameter is ignored.
153      */

154     static class BooleanConverter implements Converter {
155
156         public String JavaDoc encode(Object JavaDoc value, Object JavaDoc format)
157             throws ConversionException {
158             try {
159                 Boolean JavaDoc boolValue = (Boolean JavaDoc) value;
160                 return boolValue.toString();
161             }
162             catch (Exception JavaDoc e) {
163                 throw new ConversionException(value, Boolean JavaDoc.class, e);
164             }
165         }
166
167         public Object JavaDoc decode(String JavaDoc value, Object JavaDoc format)
168             throws ConversionException {
169             try {
170                 // this returns Boolean.FALSE for any string that is not
171
// equivelent to "true" using a case-insensitive compare
172
return Boolean.valueOf(value);
173             }
174             catch (Exception JavaDoc e) {
175                 throw new ConversionException(value, Boolean JavaDoc.class, e);
176             }
177         }
178     }
179
180     /**
181      * Converter for java.lang.Integer.
182      * The <code>format</code> parameter may either be an Integer object
183      * representing the radix, or null. If <code>format</code> is null,
184      * a default radix of 10 is used.
185      */

186     static class IntegerConverter implements Converter {
187
188         public String JavaDoc encode(Object JavaDoc value, Object JavaDoc format)
189             throws ConversionException {
190             try {
191                 int intValue = ((Integer JavaDoc)value).intValue();
192                 int radix = (format == null? 10 : ((Integer JavaDoc)format).intValue());
193                 return Integer.toString(intValue, radix);
194             }
195             catch (Exception JavaDoc e) {
196                 throw new ConversionException(value, Integer JavaDoc.class, e);
197             }
198          }
199
200          public Object JavaDoc decode(String JavaDoc value, Object JavaDoc format)
201              throws ConversionException {
202              try {
203                  int radix = (format == null? 10 : ((Integer JavaDoc)format).intValue());
204                  return Integer.valueOf(value, radix);
205              }
206              catch (Exception JavaDoc e) {
207                 throw new ConversionException(value, Integer JavaDoc.class, e);
208              }
209          }
210      }
211
212      /**
213       * Converter for java.lang.Long.
214       * The <code>format</code> parameter may either be an Integer object
215       * representing the radix or null. If <code>format</code> is null,
216       * a default radix of 10 is used.
217       */

218      static class LongConverter implements Converter {
219
220          public String JavaDoc encode(Object JavaDoc value, Object JavaDoc format)
221              throws ConversionException {
222              try {
223                  long longValue = ((Long JavaDoc)value).longValue();
224                  int radix = (format == null? 10 : ((Integer JavaDoc)format).intValue());
225                  return Long.toString(longValue, radix);
226              }
227              catch (Exception JavaDoc e) {
228                  throw new ConversionException(value, Long JavaDoc.class, e);
229              }
230           }
231
232           public Object JavaDoc decode(String JavaDoc value, Object JavaDoc format)
233               throws ConversionException {
234               try {
235                   int radix = (format == null? 10 : ((Integer JavaDoc)format).intValue());
236                   return Long.valueOf(value, radix);
237               }
238               catch (Exception JavaDoc e) {
239                  throw new ConversionException(value, Long JavaDoc.class, e);
240               }
241           }
242       }
243
244       /**
245        * Converter for java.lang.Short.
246        * The <code>format</code> parameter may either be an Integer object
247        * representing the radix or null. If <code>format</code> is null,
248        * a default radix of 10 is used.
249        */

250       static class ShortConverter implements Converter {
251
252           public String JavaDoc encode(Object JavaDoc value, Object JavaDoc format) throws
253               ConversionException {
254               try {
255                   // Short doesn't have toString(short value, int radix) method
256
int shortValue = ( (Short JavaDoc) value).intValue();
257                   int radix = (format == null ? 10 : ( (Integer JavaDoc) format).intValue());
258                   return Integer.toString(shortValue, radix);
259               }
260               catch (Exception JavaDoc e) {
261                   throw new ConversionException(value, Short JavaDoc.class, e);
262               }
263           }
264
265           public Object JavaDoc decode(String JavaDoc value, Object JavaDoc format) throws
266               ConversionException {
267               try {
268                   int radix = (format == null ? 10 : ( (Integer JavaDoc) format).intValue());
269                   return Short.valueOf(value, radix);
270               }
271               catch (Exception JavaDoc e) {
272                   throw new ConversionException(value, Short JavaDoc.class, e);
273               }
274           }
275       }
276
277      /**
278       * Converter for java.lang.Float.
279       * The <code>format</code> parameter is ignored.
280       */

281      static class FloatConverter implements Converter {
282
283          public String JavaDoc encode(Object JavaDoc value, Object JavaDoc format)
284              throws ConversionException {
285              try {
286                  Float JavaDoc floatValue = (Float JavaDoc) value;
287                  return floatValue.toString();
288              }
289              catch (Exception JavaDoc e) {
290                  throw new ConversionException(value, Float JavaDoc.class, e);
291              }
292          }
293
294          public Object JavaDoc decode(String JavaDoc value, Object JavaDoc format)
295              throws ConversionException {
296              try {
297                  return Float.valueOf(value);
298              }
299              catch (Exception JavaDoc e) {
300                 throw new ConversionException(value, Float JavaDoc.class, e);
301              }
302          }
303     }
304
305     /**
306       * Converter for java.lang.Double.
307       * The <code>format</code> parameter is ignored.
308       */

309      static class DoubleConverter implements Converter {
310
311          public String JavaDoc encode(Object JavaDoc value, Object JavaDoc format)
312              throws ConversionException {
313              try {
314                  Double JavaDoc doubleValue = (Double JavaDoc) value;
315                  return doubleValue.toString();
316              }
317              catch (Exception JavaDoc e) {
318                  throw new ConversionException(value, Double JavaDoc.class, e);
319              }
320          }
321
322          public Object JavaDoc decode(String JavaDoc value, Object JavaDoc format)
323              throws ConversionException {
324              try {
325                  return Double.valueOf(value);
326              }
327              catch (Exception JavaDoc e) {
328                 throw new ConversionException(value, Double JavaDoc.class, e);
329              }
330          }
331     }
332
333
334     /**
335      * Converter for java.util.Date.
336      * The <code>format</code> parameter must be either an instance of
337      * <code>DateFormat</code> or <code>null</code>. If <code>null</code> is
338      * specified, the converter will use the default <code>SimpleDateFormat</code>
339      * object, whose format defaults to &quot;EEE MMM dd hh:mm:ss z yyyy&quot;.
340      *
341      * @see java.text.DateFormat
342      * @see java.text.SimpleDateFormat
343      */

344     public static class DateConverter implements Converter {
345         private DateFormat JavaDoc defaultInputFormat;
346         private DateFormat JavaDoc defaultOutputFormat;
347
348         public DateConverter() {
349             defaultInputFormat = defaultOutputFormat =
350                 new SimpleDateFormat JavaDoc("EEE MMM dd HH:mm:ss z yyyy");
351         }
352
353         public DateConverter(DateFormat JavaDoc defaultInputFormat,
354                              DateFormat JavaDoc defaultOutputFormat) {
355             this.defaultInputFormat = defaultInputFormat;
356             this.defaultOutputFormat = defaultOutputFormat;
357         }
358
359         public String JavaDoc encode(Object JavaDoc value, Object JavaDoc format)
360             throws ConversionException {
361             try {
362                 DateFormat JavaDoc dateFormat = format == null ? defaultOutputFormat :
363                     (DateFormat JavaDoc) format;
364                 return dateFormat.format((Date JavaDoc)value);
365             }
366             catch (Exception JavaDoc e) {
367                 throw new ConversionException(value, Date JavaDoc.class, e);
368             }
369         }
370
371         public Object JavaDoc decode(String JavaDoc value, Object JavaDoc format)
372             throws ConversionException {
373             try {
374                 DateFormat JavaDoc dateFormat = format == null? defaultInputFormat :
375                                                  (DateFormat JavaDoc)format;
376                 return dateFormat.parse(value);
377             }
378             catch (Exception JavaDoc e) {
379                 throw new ConversionException(value, Date JavaDoc.class, e);
380             }
381         }
382     }
383
384     /**
385      * Converter for org.jdesktop.swing.Link.
386      * Currently the <code>format</code> parameter is ignored and the conversion
387      * uses the HTML href tag format to encode and decode the values:<br>
388      * <pre> &lt;a HREF=&quot;%HREF%&quot; target=&quot;%TARGET%&quot;&gt;%DISPLAYSTRING%&lt;/a&gt;
389      * </pre>
390      */

391     static class LinkConverter implements Converter {
392         /** @todo aim: quick hack, reimplement with sax parser instead! */
393
394         private static final String JavaDoc URL_BEGIN = "<a HREF=\"";
395         private static final String JavaDoc URL_MARKER = "%u";
396         private static final String JavaDoc URL_END = "\"";
397         private static final String JavaDoc TARGET_BEGIN = " target=\"";
398         private static final String JavaDoc TARGET_MARKER = "%t";
399         private static final String JavaDoc TARGET_END = "\"";
400         private static final String JavaDoc DISPLAY_BEGIN = ">";
401         private static final String JavaDoc DISPLAY_MARKER = "%d";
402         private static final String JavaDoc DISPLAY_END = "</a>";
403
404         private static final String JavaDoc TEMPLATE =
405             URL_BEGIN + URL_MARKER + URL_END +
406             TARGET_BEGIN + TARGET_MARKER + TARGET_END +
407             DISPLAY_BEGIN + DISPLAY_MARKER + DISPLAY_END;
408
409         private static final String JavaDoc TEMPLATE2 =
410             URL_BEGIN + URL_MARKER + URL_END +
411             DISPLAY_BEGIN + DISPLAY_MARKER + DISPLAY_END;
412
413         public String JavaDoc encode(Object JavaDoc value, Object JavaDoc format)
414             throws ConversionException {
415             try {
416                 Link link = (Link) value;
417                 String JavaDoc linkString;
418                 String JavaDoc target = link.getTarget();
419                 if (target != null) {
420                     linkString = TEMPLATE.replaceFirst(URL_MARKER,
421                         link.getURL().toExternalForm());
422                     linkString = linkString.replaceFirst(TARGET_MARKER,
423                         target);
424                 }
425                 else {
426                     linkString = TEMPLATE2.replaceFirst(URL_MARKER,
427                         link.getURL().toExternalForm());
428                 }
429                 linkString = linkString.replaceFirst(DISPLAY_MARKER,
430                                                      link.getText());
431
432                 return linkString;
433             }
434             catch (Exception JavaDoc e) {
435                 throw new ConversionException(value, Link.class, e);
436             }
437         }
438
439         public Object JavaDoc decode(String JavaDoc value, Object JavaDoc format)
440             throws ConversionException {
441             try {
442                 String JavaDoc url = value.substring(URL_BEGIN.length(),
443                                              value.indexOf(URL_END, URL_BEGIN.length() + 1));
444                 String JavaDoc target = null;
445                 int targetIndex = value.indexOf(TARGET_BEGIN);
446                 if (targetIndex != -1) {
447                     target = value.substring(targetIndex + TARGET_BEGIN.length(),
448                                              value.indexOf(TARGET_END,
449                         targetIndex + TARGET_BEGIN.length() + 1));
450                 }
451                 String JavaDoc display = value.substring(value.indexOf(DISPLAY_BEGIN) +
452                                                  DISPLAY_BEGIN.length(),
453                                                  value.indexOf(DISPLAY_END));
454
455
456                 return new Link(display, target, new URL JavaDoc(url));
457             }
458             catch (Exception JavaDoc e) {
459                 throw new ConversionException(value, Link.class, e);
460             }
461         }
462     }
463 }
464
Popular Tags