View Javadoc
1   package com.opencsv.bean;
2   
3   import com.opencsv.ICSVParser;
4   import com.opencsv.exceptions.CsvDataTypeMismatchException;
5   import org.apache.commons.lang3.StringUtils;
6   
7   import java.util.Currency;
8   import java.util.Locale;
9   import java.util.ResourceBundle;
10  
11  /**
12   * This class converts an input ISO 4217 currency code to a {@link java.util.Currency}
13   * instance.
14   *
15   * @author Andrew Munn
16   * @since 5.3
17   */
18  public class ConverterCurrency extends AbstractCsvConverter {
19  
20      /**
21       * Initializes the class.
22       * @param errorLocale     The locale to use for error messages
23       */
24      public ConverterCurrency(Locale errorLocale) {
25          super(Currency.class, null, null, errorLocale);
26      }
27  
28      /**
29       * @param value The ISO 4217 currency code string to be converted
30       * @return {@link java.util.Currency} instance
31       */
32      @Override
33      public Object convertToRead(String value) throws CsvDataTypeMismatchException {
34          Currency c = null;
35          if (StringUtils.isNotEmpty(value)) {
36              try {
37                  c = Currency.getInstance(value);
38              } catch (IllegalArgumentException e) {
39                  CsvDataTypeMismatchException csve = new CsvDataTypeMismatchException(value, type, String.format(
40                          ResourceBundle.getBundle(ICSVParser.DEFAULT_BUNDLE_NAME, this.errorLocale).getString("invalid.currency.value"),
41                          value, type.getName()));
42                  csve.initCause(e);
43                  throw csve;
44              }
45  
46          }
47          return c;
48      }
49  
50      /**
51       * Converts {@link java.util.Currency} instance to a string.
52       *
53       * @param value The {@link java.util.Currency} instance
54       * @return ISO 4217 currency code or {@code null} if value was {@code null}
55       * @throws CsvDataTypeMismatchException If the value is not a {@link java.util.Currency}
56       */
57      @Override
58      public String convertToWrite(Object value) throws CsvDataTypeMismatchException {
59          String result = null;
60          if (value != null) {
61              Currency c = (Currency) value;
62              result = c.getCurrencyCode();
63          }
64          return result;
65      }
66  }