1 package org.apidesign.apifest08.currency;
3 import static org.apidesign.apifest08.currency.Assert.notNull;
5 import java.math.BigDecimal;
6 import java.math.RoundingMode;
7 import java.util.Currency;
9 public final class Convertor {
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);
16 public Convertor(BigDecimal rateValue, Currency currencyFirst, Currency currencySecond) {
17 notNull(currencyFirst, "currencyFirst");
18 notNull(currencySecond, "currencySecond");
19 notNull(rateValue, "rateValue");
21 this.rateValue = rateValue;
22 this.first = currencyFirst;
23 this.second = currencySecond;
27 * Converts an amount value between the two currencies of this converter.
29 * @param amount an amount
30 * @param fromCurrency an amount currency
31 * @param toCurrency to a target currency
32 * @return a converted amount value
34 * @throws ConversionException if the conversion fails
35 * @throws UnsupportedConversionException if the conversion between a given currencies is not supported.
37 public Amount convert(BigDecimal amount, Currency fromCurrency, Currency toCurrency) throws ConversionException {
38 notNull(amount, "amount");
39 notNull(fromCurrency, "fromCurrency");
40 notNull(toCurrency, "toCurrency");
42 if((fromCurrency != first && fromCurrency != second) || (toCurrency != first && toCurrency != second)) {
43 throw new UnsupportedConversionException(fromCurrency, toCurrency);
46 BigDecimal rateValue = getRateValue(fromCurrency, toCurrency);
47 BigDecimal result = rateValue.multiply(amount);
48 return new Amount(result, toCurrency);
51 private BigDecimal getRateValue(Currency fromCurrency, Currency toCurrency) {
55 if(first == fromCurrency) {
59 retVal = one.divide(rateValue, 10 ,RoundingMode.HALF_UP);