task4/solution02/test/org/apidesign/apifest08/test/OnlineConvertor.java
changeset 61 58ec6da75f6f
parent 56 a3144e7f9c90
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/task4/solution02/test/org/apidesign/apifest08/test/OnlineConvertor.java	Sat Oct 11 23:38:46 2008 +0200
     1.3 @@ -0,0 +1,54 @@
     1.4 +package org.apidesign.apifest08.test;
     1.5 +
     1.6 +import java.math.BigDecimal;
     1.7 +import java.util.Currency;
     1.8 +
     1.9 +import org.apidesign.apifest08.currency.ConvertorFactory;
    1.10 +import org.apidesign.apifest08.currency.ExtendedConvertor;
    1.11 +import org.apidesign.apifest08.currency.Money;
    1.12 +import org.apidesign.apifest08.currency.MoneyImpl;
    1.13 +
    1.14 +/**
    1.15 + * Third party implementation of the convertor. IT IS NOT THREAD SAFE.
    1.16 + * @author lukas
    1.17 + *
    1.18 + */
    1.19 +class OnlineConvertor implements ExtendedConvertor {
    1.20 +	
    1.21 +	private static final BigDecimal LOWER_LIMIT = BigDecimal.valueOf(15);
    1.22 +	private static final BigDecimal HIGHER_LIMIT = BigDecimal.valueOf(16);
    1.23 +	
    1.24 +	private static final Currency USD = Currency.getInstance("USD");
    1.25 +	private static final Currency CZK = Currency.getInstance("CZK");
    1.26 +	private static final MoneyImpl ONE_USD = new MoneyImpl(1,USD);
    1.27 +	
    1.28 +	private ExtendedConvertor wrappedConvertor = ConvertorFactory.createConvertor(ONE_USD, new MoneyImpl(16, CZK));
    1.29 +	
    1.30 +	private BigDecimal increment = new BigDecimal("-0.01");
    1.31 +	
    1.32 +	public boolean isConversionSupported(Currency from, Currency to) {
    1.33 +		return wrappedConvertor.isConversionSupported(from, to);
    1.34 +	}
    1.35 +
    1.36 +	public Money convert(Money amount, Currency destinationCurrency)
    1.37 +			throws IllegalArgumentException {
    1.38 +		Money result = wrappedConvertor.convert(amount, destinationCurrency);
    1.39 +		updateConvertor();
    1.40 +		return result;
    1.41 +	}
    1.42 +
    1.43 +	/**
    1.44 +	 * Prepares convertor for the next conversion.
    1.45 +	 */
    1.46 +	private void updateConvertor() {
    1.47 +		BigDecimal currentRate = wrappedConvertor.convert(ONE_USD, CZK).getAmount();
    1.48 +		BigDecimal newRate = currentRate.add(increment);
    1.49 +		
    1.50 +		if (LOWER_LIMIT.compareTo(newRate)==0 || HIGHER_LIMIT.compareTo(newRate)==0)
    1.51 +		{
    1.52 +			increment = increment.negate();
    1.53 +		}
    1.54 +		wrappedConvertor = ConvertorFactory.createConvertor(ONE_USD, new MoneyImpl(newRate, CZK));
    1.55 +	}
    1.56 +
    1.57 +}