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