task4/solution13/src/org/apidesign/apifest08/currency/Convertor.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sat, 11 Oct 2008 23:38:46 +0200
changeset 61 58ec6da75f6f
parent 58 task3/solution13/src/org/apidesign/apifest08/currency/Convertor.java@07c16ec15a25
child 63 20d332739f60
permissions -rw-r--r--
Copying structure for task4
     1 package org.apidesign.apifest08.currency;
     2 
     3 import java.math.BigDecimal;
     4 import java.math.MathContext;
     5 import java.math.RoundingMode;
     6 
     7 /** Convertor able to convert amount from one currency to other currency.
     8  * <p>
     9  * Conversion method are:
    10  * <ul>
    11  * <li>{@link #convert(ConvertorCurrency, ConvertorCurrency, BigDecimal)} - convert
    12  * using exchange rate specified in exchange rate provide. This method is not try 
    13  * use reverted excahnage rate. 
    14  * <li>{@link #convertWithReversibleRates(ConvertorCurrency, ConvertorCurrency, BigDecimal)} - 
    15  * convert using exchange rate specified in exchange rate provide. This method
    16  * is not trying to use reverted exchange rate.
    17  * </ul>
    18  * 
    19  * Exchange rate is provided by {@link ExchangeRateProvider}.
    20  */
    21 public class Convertor {
    22     private Convertor[] convertors;
    23 
    24     /** Create new <code>Convertor</code> as merge of provided convertors. Merged convertor will use
    25      * provided convertors to convert between currencies.
    26      * <p>
    27      * Only one should be able to provide conversion between currencies. If more than one convertos
    28      * are able to convert currency, one of conversions will be used (it is not defined which).
    29      * 
    30      * @since version 2
    31      * @param convertors Convertor used to create merge-convertor.
    32      * @return Returns new convertor instance.
    33      */
    34     public static Convertor createConvertorAsMerge(Convertor[] convertors) {
    35         return new Convertor(convertors);
    36     }
    37     
    38     boolean remainderAllowed = true; //if false, remained is not allowed (should be true ideally, but can't handle it now)
    39     ExchangeRateProvider exchangeRateProvider; 
    40     
    41     /** Create simle convertor.
    42      */
    43     private Convertor() {
    44         this.convertors=new Convertor[0];
    45     }
    46     
    47     /** Create merge convertor.
    48      */            
    49     private Convertor(Convertor[] convertors) {
    50         this.convertors = convertors;       
    51     }
    52     
    53     /**
    54      * Create new <code>Convertor</code> using <code>ExchangeRateProvider</code>.
    55      * 
    56      * @param exchangeRateProvider {@link ExchangeRateProvider} used to get exchange rate.
    57      * 
    58      * @return Returns <code>Convertor</code> which can be used to convert money.
    59      * @since version1
    60      */
    61     public static Convertor createConvertor(ExchangeRateProvider exchangeRateProvider) {
    62         Convertor c = new Convertor();
    63 
    64         c.exchangeRateProvider = exchangeRateProvider;
    65         return c;
    66     }
    67     
    68     /**
    69      * Convert <code>amount</code> from <code>fromCurrency</code> to <code>toCurrency</code> as specified
    70      * in <code>ExchangeRateProvider</code>.
    71      * 
    72      * @param amount Amount which should be converted. Can't be negative value (can be zero or positive).
    73      * @return Return <code>ConversionResult</code> which holds conversion result.
    74      * @since version1
    75      * @deprecated since version2. Use {@link #convert(ConvertorCurrency, ConvertorCurrency, BigDecimal) } - explicitly specify conversion currencies.
    76      */
    77     public ConversionResult convert(BigDecimal amount) {
    78         return convertValue(exchangeRateProvider.getFromCurrency(), exchangeRateProvider.getToCurrency(),amount, false,false);
    79     }
    80     
    81     /**
    82      * Convert <code>amount</code> from <code>toCurrency</code> to <code>fromCurrency</code> as specified
    83      * in <code>ExchangeRateProvider</code>. This is <em>reverted</em> order than suggested by  names of currency fields in <code>ExchangeRate</code>.
    84      * 
    85      * @param amount Amount which should be converted. Can't be negative value (can be zero or positive).
    86      * @return Return <code>ConversionResult</code> which holds conversion result.
    87      * @since version1
    88      * @deprecated since version2. Use {@link #convert(ConvertorCurrency, ConvertorCurrency, BigDecimal) } - explicitly specify conversion currencies.
    89      */
    90     public ConversionResult convertBack(BigDecimal amount) {
    91         return convertValue(exchangeRateProvider.getFromCurrency(), exchangeRateProvider.getToCurrency(),amount, true,false);
    92     }
    93 
    94     private ConversionResult convertUsingSimpleConvertor(ConvertorCurrency fromCurrency, ConvertorCurrency toCurrency, boolean reversibleExRate, BigDecimal amount, boolean convertBack) throws ConversionNotSupportedException, RuntimeException {
    95         ConversionResult result = new ConversionResult();
    96 
    97         //ExchangeRate rate = exchangeRateProvider.getExchangeRate();
    98         ExchangeRate rate;
    99         if (reversibleExRate) {
   100             rate = exchangeRateProvider.getReversibleExchangeRate(fromCurrency, toCurrency);
   101         } else {
   102             rate = exchangeRateProvider.getExchangeRate(fromCurrency, toCurrency);
   103         }
   104         if (rate == null) {
   105             return null;
   106         }
   107         
   108         int fromFranctionDigits = fromCurrency.getDefaultFractionDigits();
   109         int toFractionDigits = toCurrency.getDefaultFractionDigits();
   110 
   111         if (toFractionDigits != 2) {
   112             throw new ConvertorException("Can't process currency with defaultFractionDigits!=2, " + exchangeRateProvider.getToCurrency() + " has " + toFractionDigits + " defaultFractionDigits");
   113         }
   114         if (fromFranctionDigits != 2) {
   115             throw new ConvertorException("Can't process currency with defaultFractionDigits!=2, " + exchangeRateProvider.getFromCurrency() + " has " + fromFranctionDigits + " defaultFractionDigits");
   116         }
   117 
   118         if (amount.signum() == -1) {
   119             throw new RuntimeException("Can convert only non-negative value, current value is " + amount);
   120         }
   121 
   122 
   123         MathContext context = new MathContext(0, RoundingMode.DOWN);
   124 
   125         BigDecimal from;
   126         BigDecimal to;
   127         if (convertBack) {
   128             //converting in reverted way
   129             to = rate.getFromValue();
   130             from = rate.getToValue();
   131         } else {
   132             //converting in normal way
   133             from = rate.getFromValue();
   134             to = rate.getToValue();
   135         }
   136 
   137         BigDecimal amountCent = amount.movePointRight(toFractionDigits);
   138 
   139         final BigDecimal multiplied = amountCent.multiply(to, context);
   140         BigDecimal[] division = multiplied.divideAndRemainder(from, context);
   141 
   142         if (!remainderAllowed && !(BigDecimal.ZERO.equals(division[1]))) {
   143             throw new RuntimeException("Remained is not allowed - remaining amount is " + division[1] + " cents");
   144         } else {
   145             result.setRemainder(BigDecimal.ZERO);
   146         }
   147 
   148         BigDecimal converted = division[0].movePointLeft(toFractionDigits);
   149         converted = converted.setScale(toFractionDigits); //XXX ugly
   150         result.setConverted(converted);
   151         //result.setRemainder(...);
   152         return result;
   153     }
   154     
   155 
   156     private ConversionResult convertValue(ConvertorCurrency fromCurrency, ConvertorCurrency toCurrency,BigDecimal amount, boolean convertBack,boolean reversibleExRate) throws RuntimeException {
   157         //result.setRemainder(...);
   158         if (convertors.length==0) {
   159             return convertUsingSimpleConvertor(fromCurrency, toCurrency, reversibleExRate, amount, convertBack);
   160         } else {
   161             ConversionResult result = null;
   162             for (int i = 0;i<convertors.length;i++) {
   163                 Convertor subConvertor = convertors[i];
   164                 result = subConvertor.convertValue(fromCurrency, toCurrency, amount, convertBack, reversibleExRate);
   165                 if (result!=null) {
   166                     break;
   167                 }
   168             }
   169             return result;
   170         }
   171     }
   172     
   173     /**
   174      * Convert <code>value</code> from <code>fromCurrency</code> to <code>toCurrency</code>.
   175      * <p>
   176      * Exchange rate is provided by exchange rate provider which was specified when Convertor was created.
   177      * This method is using only exchange rate from->to and not trying to use reverted excange rate to->from.
   178      * 
   179      * @param fromCurrency Source currency to convert from.
   180      * @param toCurrency Target currency to convert to.
   181      * @param value Value in source currency which should be converted.
   182      * @return Return conversion result.
   183      * @since version2
   184      * @throws ConversionNotSupportedException If conversion from <code>fromCurrency</code> to <code>toCurrency</code> is not supported.
   185      */
   186     public ConversionResult convert(ConvertorCurrency fromCurrency, ConvertorCurrency toCurrency, BigDecimal value) {
   187         ConversionResult result = convertValue(fromCurrency, toCurrency, value, false,false);
   188         if (result==null) {
   189             //throw new ConversionNotSupportedException("Conversion from " + fromCurrency + " to " + toCurrency + " is not supported");
   190             throw new ConversionNotSupportedException(fromCurrency.getCurrencyCode(),toCurrency.getCurrencyCode(),false);
   191         }
   192         return result;
   193     }
   194     
   195     /**
   196      * Convert <code>value</code> from <code>fromCurrency</code> to <code>toCurrency</code>.
   197      * Exchange rate is provided by exchange rate provider which was specified when Convertor was created.
   198      * <p>
   199      *  This method is using only exchange rate from->to and if not found, it is trying to use reverted excange rate to->from.
   200      * 
   201      * @param fromCurrency Source currency to convert from.
   202      * @param toCurrency Target currency to convert to.
   203      * @param value Value in source currency which should be converted.
   204      * @return Return conversion result.
   205      * @since version2
   206      * @throws ConversionNotSupportedException If conversion from <code>fromCurrency</code> to <code>toCurrency</code> 
   207      *         is not supported and neither conversion from <code>toCurrency</code> to <code>fromCurrency</code> is not supported.
   208      */
   209     public ConversionResult convertWithReversibleRates(ConvertorCurrency fromCurrency, ConvertorCurrency toCurrency, BigDecimal value) {
   210         ConversionResult result = convertValue(fromCurrency, toCurrency, value, false,true);
   211         if (result==null) {
   212             //throw new ConversionNotSupportedException("Neither onversion nor reverted conversion from " + fromCurrency + " to " + toCurrency + "  is not supported,");
   213             throw new ConversionNotSupportedException(fromCurrency.getCurrencyCode(),toCurrency.getCurrencyCode(),true);
   214         }
   215         return result;
   216     }
   217     
   218 }