1 package org.apidesign.apifest08.currency;
3 import java.util.Currency;
4 import java.util.HashMap;
8 * A {@link Convertor} that works from a pre-set conversion table.
9 * First use {@link #putIntoTable(org.apidesign.apifest08.currency.ConversionRate)} to set the conversion table.
10 * Then invoke the {@link #convert(org.apidesign.apifest08.currency.Convertor.ConversionRequest)} method as many times as you wish.
13 public class TableConvertor implements Convertor {
15 private final Map<Currency, Map<Currency, ConversionRate>> conversionTable = new HashMap<Currency, Map<Currency, ConversionRate>>();
17 public TableConvertor() {
21 * Puts a rate into the table.
24 public void putIntoTable( final ConversionRate rate ) {
25 final Currency srcCurrency = rate.getSrcUnitAmount().getCurrency();
26 final Currency tgtCurrency = rate.getTgtUnitAmount().getCurrency();
27 synchronized ( conversionTable ) {
28 Map<Currency, ConversionRate> targetTable = conversionTable.get( srcCurrency );
29 if ( targetTable == null ) {
30 targetTable = new HashMap<Currency, ConversionRate>();
31 conversionTable.put( srcCurrency, targetTable );
33 targetTable.put( tgtCurrency, rate );
38 * Carries out the conversion.
39 * If the table does not contain a conversion from the source currency to the target one,
40 * a {@link ConversionResult} is returned that has null netAmount.
41 * This implementation works with any {@link ConversionRequest}, it won't throw {@link IllegalRequestSubtypeException}.
42 * @param req the conversion request
43 * @return the conversion result
45 public ConversionResult convert( final ConversionRequest req ) {
46 final Currency srcCurrency = req.getSrcAmount().getCurrency();
47 final Currency tgtCurrency = req.getTgtCurrency();
48 final ConversionRate rate = findConversionRate( srcCurrency, tgtCurrency );
50 final MonetaryAmount tgtAmount = rate.convert( req.getSrcAmount() );
51 return new ConversionResult( tgtAmount );
53 return new ConversionResult( null ); // did not find the pair of currencies in the table
58 * Looks up the conversion between the given currencies in the table.
59 * @param srcCurrency the source currency
60 * @param tgtCurrency the target currency
61 * @return the conversion rate; null means no conversion between the currencies was found in the table
63 protected ConversionRate findConversionRate( final Currency srcCurrency, final Currency tgtCurrency ) {
64 synchronized ( conversionTable ) {
65 final Map<Currency, ConversionRate> targetTable = conversionTable.get(srcCurrency);
66 final ConversionRate rate = (targetTable != null) ? targetTable.get(tgtCurrency) : null;