View Javadoc

1   package com.panogenesis.util;
2   
3   import java.text.DecimalFormat;
4   import java.text.ParseException;
5   
6   import org.apache.commons.beanutils.ConversionException;
7   import org.apache.commons.beanutils.Converter;
8   import org.apache.commons.lang.StringUtils;
9   import org.apache.commons.logging.Log;
10  import org.apache.commons.logging.LogFactory;
11  
12  /***
13   * This class is converts a Double to a double-digit String
14   * (and vise-versa) by BeanUtils when copying properties.
15   * Registered for use in BaseAction.
16   *
17   * <p>
18   * <a href="CurrencyConverter.java.html"><i>View Source</i></a>
19   * </p>
20   *
21   * @author <a href="mailto:matt@raibledesigns.com">Matt Raible</a>
22   */
23  public class CurrencyConverter implements Converter {
24      protected final Log log = LogFactory.getLog(CurrencyConverter.class);
25      protected final DecimalFormat formatter = new DecimalFormat("###,###.00");
26  
27      /***
28       * Convert a String to a Double and a Double to a String
29       *
30       * @param type the class type to output
31       * @param value the object to convert
32       * @return object the converted object (Double or String)
33       */
34      public final Object convert(final Class type, final Object value) {
35          // for a null value, return null
36          if (value == null) {
37              return null;
38          } else {
39              if (value instanceof String) {
40                  if (log.isDebugEnabled()) {
41                      log.debug("value (" + value + ") instance of String");
42                  }
43  
44                  try {
45                      if (StringUtils.isBlank(String.valueOf(value))) {
46                          return null;
47                      }
48  
49                      if (log.isDebugEnabled()) {
50                          log.debug("converting '" + value + "' to a decimal");
51                      }
52  
53                      //formatter.setDecimalSeparatorAlwaysShown(true);
54                      Number num = formatter.parse(String.valueOf(value));
55  
56                      return new Double(num.doubleValue());
57                  } catch (ParseException pe) {
58                      pe.printStackTrace();
59                  }
60              } else if (value instanceof Double) {
61                  if (log.isDebugEnabled()) {
62                      log.debug("value (" + value + ") instance of Double");
63                      log.debug("returning double: " + formatter.format(value));
64                  }
65  
66                  return formatter.format(value);
67              }
68          }
69  
70          throw new ConversionException("Could not convert " + value + " to " +
71                                        type.getName() + "!");
72      }
73  }