task4/solution13/src/org/apidesign/apifest08/currency/Convertor.java
changeset 61 58ec6da75f6f
parent 58 07c16ec15a25
child 63 20d332739f60
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/task4/solution13/src/org/apidesign/apifest08/currency/Convertor.java	Sat Oct 11 23:38:46 2008 +0200
     1.3 @@ -0,0 +1,218 @@
     1.4 +package org.apidesign.apifest08.currency;
     1.5 +
     1.6 +import java.math.BigDecimal;
     1.7 +import java.math.MathContext;
     1.8 +import java.math.RoundingMode;
     1.9 +
    1.10 +/** Convertor able to convert amount from one currency to other currency.
    1.11 + * <p>
    1.12 + * Conversion method are:
    1.13 + * <ul>
    1.14 + * <li>{@link #convert(ConvertorCurrency, ConvertorCurrency, BigDecimal)} - convert
    1.15 + * using exchange rate specified in exchange rate provide. This method is not try 
    1.16 + * use reverted excahnage rate. 
    1.17 + * <li>{@link #convertWithReversibleRates(ConvertorCurrency, ConvertorCurrency, BigDecimal)} - 
    1.18 + * convert using exchange rate specified in exchange rate provide. This method
    1.19 + * is not trying to use reverted exchange rate.
    1.20 + * </ul>
    1.21 + * 
    1.22 + * Exchange rate is provided by {@link ExchangeRateProvider}.
    1.23 + */
    1.24 +public class Convertor {
    1.25 +    private Convertor[] convertors;
    1.26 +
    1.27 +    /** Create new <code>Convertor</code> as merge of provided convertors. Merged convertor will use
    1.28 +     * provided convertors to convert between currencies.
    1.29 +     * <p>
    1.30 +     * Only one should be able to provide conversion between currencies. If more than one convertos
    1.31 +     * are able to convert currency, one of conversions will be used (it is not defined which).
    1.32 +     * 
    1.33 +     * @since version 2
    1.34 +     * @param convertors Convertor used to create merge-convertor.
    1.35 +     * @return Returns new convertor instance.
    1.36 +     */
    1.37 +    public static Convertor createConvertorAsMerge(Convertor[] convertors) {
    1.38 +        return new Convertor(convertors);
    1.39 +    }
    1.40 +    
    1.41 +    boolean remainderAllowed = true; //if false, remained is not allowed (should be true ideally, but can't handle it now)
    1.42 +    ExchangeRateProvider exchangeRateProvider; 
    1.43 +    
    1.44 +    /** Create simle convertor.
    1.45 +     */
    1.46 +    private Convertor() {
    1.47 +        this.convertors=new Convertor[0];
    1.48 +    }
    1.49 +    
    1.50 +    /** Create merge convertor.
    1.51 +     */            
    1.52 +    private Convertor(Convertor[] convertors) {
    1.53 +        this.convertors = convertors;       
    1.54 +    }
    1.55 +    
    1.56 +    /**
    1.57 +     * Create new <code>Convertor</code> using <code>ExchangeRateProvider</code>.
    1.58 +     * 
    1.59 +     * @param exchangeRateProvider {@link ExchangeRateProvider} used to get exchange rate.
    1.60 +     * 
    1.61 +     * @return Returns <code>Convertor</code> which can be used to convert money.
    1.62 +     * @since version1
    1.63 +     */
    1.64 +    public static Convertor createConvertor(ExchangeRateProvider exchangeRateProvider) {
    1.65 +        Convertor c = new Convertor();
    1.66 +
    1.67 +        c.exchangeRateProvider = exchangeRateProvider;
    1.68 +        return c;
    1.69 +    }
    1.70 +    
    1.71 +    /**
    1.72 +     * Convert <code>amount</code> from <code>fromCurrency</code> to <code>toCurrency</code> as specified
    1.73 +     * in <code>ExchangeRateProvider</code>.
    1.74 +     * 
    1.75 +     * @param amount Amount which should be converted. Can't be negative value (can be zero or positive).
    1.76 +     * @return Return <code>ConversionResult</code> which holds conversion result.
    1.77 +     * @since version1
    1.78 +     * @deprecated since version2. Use {@link #convert(ConvertorCurrency, ConvertorCurrency, BigDecimal) } - explicitly specify conversion currencies.
    1.79 +     */
    1.80 +    public ConversionResult convert(BigDecimal amount) {
    1.81 +        return convertValue(exchangeRateProvider.getFromCurrency(), exchangeRateProvider.getToCurrency(),amount, false,false);
    1.82 +    }
    1.83 +    
    1.84 +    /**
    1.85 +     * Convert <code>amount</code> from <code>toCurrency</code> to <code>fromCurrency</code> as specified
    1.86 +     * in <code>ExchangeRateProvider</code>. This is <em>reverted</em> order than suggested by  names of currency fields in <code>ExchangeRate</code>.
    1.87 +     * 
    1.88 +     * @param amount Amount which should be converted. Can't be negative value (can be zero or positive).
    1.89 +     * @return Return <code>ConversionResult</code> which holds conversion result.
    1.90 +     * @since version1
    1.91 +     * @deprecated since version2. Use {@link #convert(ConvertorCurrency, ConvertorCurrency, BigDecimal) } - explicitly specify conversion currencies.
    1.92 +     */
    1.93 +    public ConversionResult convertBack(BigDecimal amount) {
    1.94 +        return convertValue(exchangeRateProvider.getFromCurrency(), exchangeRateProvider.getToCurrency(),amount, true,false);
    1.95 +    }
    1.96 +
    1.97 +    private ConversionResult convertUsingSimpleConvertor(ConvertorCurrency fromCurrency, ConvertorCurrency toCurrency, boolean reversibleExRate, BigDecimal amount, boolean convertBack) throws ConversionNotSupportedException, RuntimeException {
    1.98 +        ConversionResult result = new ConversionResult();
    1.99 +
   1.100 +        //ExchangeRate rate = exchangeRateProvider.getExchangeRate();
   1.101 +        ExchangeRate rate;
   1.102 +        if (reversibleExRate) {
   1.103 +            rate = exchangeRateProvider.getReversibleExchangeRate(fromCurrency, toCurrency);
   1.104 +        } else {
   1.105 +            rate = exchangeRateProvider.getExchangeRate(fromCurrency, toCurrency);
   1.106 +        }
   1.107 +        if (rate == null) {
   1.108 +            return null;
   1.109 +        }
   1.110 +        
   1.111 +        int fromFranctionDigits = fromCurrency.getDefaultFractionDigits();
   1.112 +        int toFractionDigits = toCurrency.getDefaultFractionDigits();
   1.113 +
   1.114 +        if (toFractionDigits != 2) {
   1.115 +            throw new ConvertorException("Can't process currency with defaultFractionDigits!=2, " + exchangeRateProvider.getToCurrency() + " has " + toFractionDigits + " defaultFractionDigits");
   1.116 +        }
   1.117 +        if (fromFranctionDigits != 2) {
   1.118 +            throw new ConvertorException("Can't process currency with defaultFractionDigits!=2, " + exchangeRateProvider.getFromCurrency() + " has " + fromFranctionDigits + " defaultFractionDigits");
   1.119 +        }
   1.120 +
   1.121 +        if (amount.signum() == -1) {
   1.122 +            throw new RuntimeException("Can convert only non-negative value, current value is " + amount);
   1.123 +        }
   1.124 +
   1.125 +
   1.126 +        MathContext context = new MathContext(0, RoundingMode.DOWN);
   1.127 +
   1.128 +        BigDecimal from;
   1.129 +        BigDecimal to;
   1.130 +        if (convertBack) {
   1.131 +            //converting in reverted way
   1.132 +            to = rate.getFromValue();
   1.133 +            from = rate.getToValue();
   1.134 +        } else {
   1.135 +            //converting in normal way
   1.136 +            from = rate.getFromValue();
   1.137 +            to = rate.getToValue();
   1.138 +        }
   1.139 +
   1.140 +        BigDecimal amountCent = amount.movePointRight(toFractionDigits);
   1.141 +
   1.142 +        final BigDecimal multiplied = amountCent.multiply(to, context);
   1.143 +        BigDecimal[] division = multiplied.divideAndRemainder(from, context);
   1.144 +
   1.145 +        if (!remainderAllowed && !(BigDecimal.ZERO.equals(division[1]))) {
   1.146 +            throw new RuntimeException("Remained is not allowed - remaining amount is " + division[1] + " cents");
   1.147 +        } else {
   1.148 +            result.setRemainder(BigDecimal.ZERO);
   1.149 +        }
   1.150 +
   1.151 +        BigDecimal converted = division[0].movePointLeft(toFractionDigits);
   1.152 +        converted = converted.setScale(toFractionDigits); //XXX ugly
   1.153 +        result.setConverted(converted);
   1.154 +        //result.setRemainder(...);
   1.155 +        return result;
   1.156 +    }
   1.157 +    
   1.158 +
   1.159 +    private ConversionResult convertValue(ConvertorCurrency fromCurrency, ConvertorCurrency toCurrency,BigDecimal amount, boolean convertBack,boolean reversibleExRate) throws RuntimeException {
   1.160 +        //result.setRemainder(...);
   1.161 +        if (convertors.length==0) {
   1.162 +            return convertUsingSimpleConvertor(fromCurrency, toCurrency, reversibleExRate, amount, convertBack);
   1.163 +        } else {
   1.164 +            ConversionResult result = null;
   1.165 +            for (int i = 0;i<convertors.length;i++) {
   1.166 +                Convertor subConvertor = convertors[i];
   1.167 +                result = subConvertor.convertValue(fromCurrency, toCurrency, amount, convertBack, reversibleExRate);
   1.168 +                if (result!=null) {
   1.169 +                    break;
   1.170 +                }
   1.171 +            }
   1.172 +            return result;
   1.173 +        }
   1.174 +    }
   1.175 +    
   1.176 +    /**
   1.177 +     * Convert <code>value</code> from <code>fromCurrency</code> to <code>toCurrency</code>.
   1.178 +     * <p>
   1.179 +     * Exchange rate is provided by exchange rate provider which was specified when Convertor was created.
   1.180 +     * This method is using only exchange rate from->to and not trying to use reverted excange rate to->from.
   1.181 +     * 
   1.182 +     * @param fromCurrency Source currency to convert from.
   1.183 +     * @param toCurrency Target currency to convert to.
   1.184 +     * @param value Value in source currency which should be converted.
   1.185 +     * @return Return conversion result.
   1.186 +     * @since version2
   1.187 +     * @throws ConversionNotSupportedException If conversion from <code>fromCurrency</code> to <code>toCurrency</code> is not supported.
   1.188 +     */
   1.189 +    public ConversionResult convert(ConvertorCurrency fromCurrency, ConvertorCurrency toCurrency, BigDecimal value) {
   1.190 +        ConversionResult result = convertValue(fromCurrency, toCurrency, value, false,false);
   1.191 +        if (result==null) {
   1.192 +            //throw new ConversionNotSupportedException("Conversion from " + fromCurrency + " to " + toCurrency + " is not supported");
   1.193 +            throw new ConversionNotSupportedException(fromCurrency.getCurrencyCode(),toCurrency.getCurrencyCode(),false);
   1.194 +        }
   1.195 +        return result;
   1.196 +    }
   1.197 +    
   1.198 +    /**
   1.199 +     * Convert <code>value</code> from <code>fromCurrency</code> to <code>toCurrency</code>.
   1.200 +     * Exchange rate is provided by exchange rate provider which was specified when Convertor was created.
   1.201 +     * <p>
   1.202 +     *  This method is using only exchange rate from->to and if not found, it is trying to use reverted excange rate to->from.
   1.203 +     * 
   1.204 +     * @param fromCurrency Source currency to convert from.
   1.205 +     * @param toCurrency Target currency to convert to.
   1.206 +     * @param value Value in source currency which should be converted.
   1.207 +     * @return Return conversion result.
   1.208 +     * @since version2
   1.209 +     * @throws ConversionNotSupportedException If conversion from <code>fromCurrency</code> to <code>toCurrency</code> 
   1.210 +     *         is not supported and neither conversion from <code>toCurrency</code> to <code>fromCurrency</code> is not supported.
   1.211 +     */
   1.212 +    public ConversionResult convertWithReversibleRates(ConvertorCurrency fromCurrency, ConvertorCurrency toCurrency, BigDecimal value) {
   1.213 +        ConversionResult result = convertValue(fromCurrency, toCurrency, value, false,true);
   1.214 +        if (result==null) {
   1.215 +            //throw new ConversionNotSupportedException("Neither onversion nor reverted conversion from " + fromCurrency + " to " + toCurrency + "  is not supported,");
   1.216 +            throw new ConversionNotSupportedException(fromCurrency.getCurrencyCode(),toCurrency.getCurrencyCode(),true);
   1.217 +        }
   1.218 +        return result;
   1.219 +    }
   1.220 +    
   1.221 +}