diff -r a3144e7f9c90 -r 58ec6da75f6f task4/solution02/test/org/apidesign/apifest08/test/OnlineConvertor.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution02/test/org/apidesign/apifest08/test/OnlineConvertor.java Sat Oct 11 23:38:46 2008 +0200 @@ -0,0 +1,54 @@ +package org.apidesign.apifest08.test; + +import java.math.BigDecimal; +import java.util.Currency; + +import org.apidesign.apifest08.currency.ConvertorFactory; +import org.apidesign.apifest08.currency.ExtendedConvertor; +import org.apidesign.apifest08.currency.Money; +import org.apidesign.apifest08.currency.MoneyImpl; + +/** + * Third party implementation of the convertor. IT IS NOT THREAD SAFE. + * @author lukas + * + */ +class OnlineConvertor implements ExtendedConvertor { + + private static final BigDecimal LOWER_LIMIT = BigDecimal.valueOf(15); + private static final BigDecimal HIGHER_LIMIT = BigDecimal.valueOf(16); + + private static final Currency USD = Currency.getInstance("USD"); + private static final Currency CZK = Currency.getInstance("CZK"); + private static final MoneyImpl ONE_USD = new MoneyImpl(1,USD); + + private ExtendedConvertor wrappedConvertor = ConvertorFactory.createConvertor(ONE_USD, new MoneyImpl(16, CZK)); + + private BigDecimal increment = new BigDecimal("-0.01"); + + public boolean isConversionSupported(Currency from, Currency to) { + return wrappedConvertor.isConversionSupported(from, to); + } + + public Money convert(Money amount, Currency destinationCurrency) + throws IllegalArgumentException { + Money result = wrappedConvertor.convert(amount, destinationCurrency); + updateConvertor(); + return result; + } + + /** + * Prepares convertor for the next conversion. + */ + private void updateConvertor() { + BigDecimal currentRate = wrappedConvertor.convert(ONE_USD, CZK).getAmount(); + BigDecimal newRate = currentRate.add(increment); + + if (LOWER_LIMIT.compareTo(newRate)==0 || HIGHER_LIMIT.compareTo(newRate)==0) + { + increment = increment.negate(); + } + wrappedConvertor = ConvertorFactory.createConvertor(ONE_USD, new MoneyImpl(newRate, CZK)); + } + +}