task2/solution06/src/org/apidesign/apifest08/currency/Convertor.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Wed, 01 Oct 2008 10:43:05 +0200
changeset 29 f6073056b9fe
parent 21 task1/solution06/src/org/apidesign/apifest08/currency/Convertor.java@61e4c4c120fd
child 38 5838e0aaa81f
permissions -rw-r--r--
Getting ready for task2: copying all solutions to new locations
     1 package org.apidesign.apifest08.currency;
     2 
     3 import static org.apidesign.apifest08.currency.Assert.notNull;
     4 
     5 import java.math.BigDecimal;
     6 import java.math.RoundingMode;
     7 import java.util.Currency;
     8 
     9 public final class Convertor {
    10 	
    11 	private final Currency first;
    12 	private final Currency second;
    13 	private final BigDecimal rateValue; // a rate between the first currency and the second currency
    14 	public static final BigDecimal one = new BigDecimal(1);	
    15 	
    16 	public Convertor(BigDecimal rateValue, Currency currencyFirst, Currency currencySecond) {
    17 		notNull(currencyFirst, "currencyFirst");
    18 		notNull(currencySecond, "currencySecond");		
    19 		notNull(rateValue, "rateValue");
    20 		
    21 		this.rateValue = rateValue;
    22 		this.first = currencyFirst;
    23 		this.second = currencySecond;
    24 	}
    25     	
    26 	/**
    27 	 * Converts an amount value between the two currencies of this converter.
    28 	 *  
    29 	 * @param amount an amount
    30 	 * @param fromCurrency an amount currency
    31 	 * @param toCurrency to a target currency
    32 	 * @return a converted amount value
    33 	 * 
    34 	 * @throws ConversionException if the conversion fails
    35 	 * @throws UnsupportedConversionException if the conversion between a given currencies is not supported.
    36 	 */
    37 	public Amount convert(BigDecimal amount, Currency fromCurrency, Currency toCurrency) throws ConversionException {
    38 		notNull(amount, "amount");
    39 		notNull(fromCurrency, "fromCurrency");
    40 		notNull(toCurrency, "toCurrency");
    41 		
    42 		if((fromCurrency != first && fromCurrency != second) || (toCurrency != first && toCurrency != second)) {
    43 			throw new UnsupportedConversionException(fromCurrency, toCurrency);
    44 		}		
    45 
    46 		BigDecimal rateValue = getRateValue(fromCurrency, toCurrency);
    47 		BigDecimal result = rateValue.multiply(amount);			
    48 		return new Amount(result, toCurrency);	
    49 	}
    50 	
    51 	private BigDecimal getRateValue(Currency fromCurrency, Currency toCurrency) {		
    52 		
    53 		BigDecimal retVal;
    54 		
    55 		if(first == fromCurrency) {
    56 			retVal = rateValue;
    57 		} else {	
    58 			//reverse rate	
    59 			retVal = one.divide(rateValue, 10 ,RoundingMode.HALF_UP);
    60 		}
    61 		
    62 		return retVal;
    63 	}
    64 }