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