task4/solution02/test/org/apidesign/apifest08/test/OnlineConvertor.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sat, 11 Oct 2008 23:38:46 +0200
changeset 61 58ec6da75f6f
parent 56 task3/solution02/test/org/apidesign/apifest08/test/OnlineConvertor.java@a3144e7f9c90
permissions -rw-r--r--
Copying structure for task4
japod@56
     1
package org.apidesign.apifest08.test;
japod@56
     2
japod@56
     3
import java.math.BigDecimal;
japod@56
     4
import java.util.Currency;
japod@56
     5
japod@56
     6
import org.apidesign.apifest08.currency.ConvertorFactory;
japod@56
     7
import org.apidesign.apifest08.currency.ExtendedConvertor;
japod@56
     8
import org.apidesign.apifest08.currency.Money;
japod@56
     9
import org.apidesign.apifest08.currency.MoneyImpl;
japod@56
    10
japod@56
    11
/**
japod@56
    12
 * Third party implementation of the convertor. IT IS NOT THREAD SAFE.
japod@56
    13
 * @author lukas
japod@56
    14
 *
japod@56
    15
 */
japod@56
    16
class OnlineConvertor implements ExtendedConvertor {
japod@56
    17
	
japod@56
    18
	private static final BigDecimal LOWER_LIMIT = BigDecimal.valueOf(15);
japod@56
    19
	private static final BigDecimal HIGHER_LIMIT = BigDecimal.valueOf(16);
japod@56
    20
	
japod@56
    21
	private static final Currency USD = Currency.getInstance("USD");
japod@56
    22
	private static final Currency CZK = Currency.getInstance("CZK");
japod@56
    23
	private static final MoneyImpl ONE_USD = new MoneyImpl(1,USD);
japod@56
    24
	
japod@56
    25
	private ExtendedConvertor wrappedConvertor = ConvertorFactory.createConvertor(ONE_USD, new MoneyImpl(16, CZK));
japod@56
    26
	
japod@56
    27
	private BigDecimal increment = new BigDecimal("-0.01");
japod@56
    28
	
japod@56
    29
	public boolean isConversionSupported(Currency from, Currency to) {
japod@56
    30
		return wrappedConvertor.isConversionSupported(from, to);
japod@56
    31
	}
japod@56
    32
japod@56
    33
	public Money convert(Money amount, Currency destinationCurrency)
japod@56
    34
			throws IllegalArgumentException {
japod@56
    35
		Money result = wrappedConvertor.convert(amount, destinationCurrency);
japod@56
    36
		updateConvertor();
japod@56
    37
		return result;
japod@56
    38
	}
japod@56
    39
japod@56
    40
	/**
japod@56
    41
	 * Prepares convertor for the next conversion.
japod@56
    42
	 */
japod@56
    43
	private void updateConvertor() {
japod@56
    44
		BigDecimal currentRate = wrappedConvertor.convert(ONE_USD, CZK).getAmount();
japod@56
    45
		BigDecimal newRate = currentRate.add(increment);
japod@56
    46
		
japod@56
    47
		if (LOWER_LIMIT.compareTo(newRate)==0 || HIGHER_LIMIT.compareTo(newRate)==0)
japod@56
    48
		{
japod@56
    49
			increment = increment.negate();
japod@56
    50
		}
japod@56
    51
		wrappedConvertor = ConvertorFactory.createConvertor(ONE_USD, new MoneyImpl(newRate, CZK));
japod@56
    52
	}
japod@56
    53
japod@56
    54
}