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