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.ArrayList;
8 import java.util.Currency;
12 * The factory for {@link Convertor}.
16 public final class ConvertorFactory {
17 //do not expose constructor
18 private ConvertorFactory(){}
21 * @return a convertor instance.
23 * @throws CurrencyException in a convertor cannot be instantiated
25 public static Convertor newInstance() throws CurrencyException{
26 return new DefaultConvertor();
29 private static final class DefaultConvertor extends Convertor {
30 private List<Bid> bids;
32 private DefaultConvertor() {
33 bids = new ArrayList<Bid>();
34 Bid usdCzk = new Bid(Currencies.USD, Currencies.CZK, new BigDecimal("17"));
36 Bid skCzk = new Bid(Currencies.SKK, Currencies.CZK, new BigDecimal("0.8"));
41 public Amount convert(Amount from, Currency targetCurrency)
42 throws CurrencyException {
43 return convert(from.getValue(), from.getCurrency(), targetCurrency);
48 public Amount convert(BigDecimal amount, Currency from,
49 Currency targetCurrency) throws ConversionException,
50 UnsupportedConversionException {
51 notNull(from, "from");
52 notNull(targetCurrency, "targetCurrency");
54 int index = bids.indexOf(new Bid(from, targetCurrency));
56 throw new UnsupportedConversionException(from, targetCurrency);
58 Bid bid = bids.get(index);
59 BigDecimal bidValue = bid.getBidValue(from, targetCurrency);
60 BigDecimal result = bidValue.multiply(amount);
61 return new Amount(result, targetCurrency);