1 package org.apidesign.apifest08.currency;
3 import java.io.Serializable;
4 import java.util.Arrays;
5 import java.util.Currency;
8 * Convertor that is composed from other convertors.
12 class CompositeConvertor implements ExtendedConvertor, Serializable {
14 private static final long serialVersionUID = -2702026568249130055L;
16 private final ExtendedConvertor[] convertors;
19 public CompositeConvertor(ExtendedConvertor... convertors) {
20 this.convertors = convertors.clone();
21 for (ExtendedConvertor convertor: this.convertors)
25 throw new NullPointerException("One of the convertors to be merged is null");
31 * Returns true if the composite contains convertor that supports given conversion.
33 public boolean isConversionSupported(Currency from, Currency to) {
34 return findConvertorFor(from, to)!=null;
39 * If the composite contains convertor that supports given conversion, delegates to its convert method.
40 * Throws {@link IllegalArgumentException} convertor supporting given conversion is not found.
42 public Money convert(Money amount, Currency destinationCurrency) throws IllegalArgumentException {
43 ExtendedConvertor convertor = findConvertorFor(amount.getCurrency(), destinationCurrency);
46 return convertor.convert(amount, destinationCurrency);
48 throw new IllegalArgumentException("Conversion not supported. Can not convert to "+destinationCurrency+".");
52 * Finds convertor for given currencies. If not found, returns null.
57 ExtendedConvertor findConvertorFor(Currency from, Currency to) {
58 //does linear search, in the future can cache the results.
59 for (ExtendedConvertor convertor:convertors)
61 if (convertor.isConversionSupported(from, to))
71 public String toString() {
72 return getClass().getName()+" converts "+Arrays.toString(convertors);