japod@34: package org.apidesign.apifest08.currency; japod@34: japod@34: import java.io.Serializable; japod@34: import java.util.Arrays; japod@34: import java.util.Currency; japod@34: japod@34: /** japod@34: * Convertor that is composed from other convertors. japod@34: * @author lukas japod@34: * japod@34: */ japod@34: class CompositeConvertor implements ExtendedConvertor, Serializable { japod@34: japod@34: private static final long serialVersionUID = -2702026568249130055L; japod@34: japod@34: private final ExtendedConvertor[] convertors; japod@34: japod@34: japod@34: public CompositeConvertor(ExtendedConvertor... convertors) { japod@34: this.convertors = convertors.clone(); japod@34: for (ExtendedConvertor convertor: this.convertors) japod@34: { japod@34: if (convertor==null) japod@34: { japod@34: throw new NullPointerException("One of the convertors to be merged is null"); japod@34: } japod@34: } japod@34: } japod@34: japod@34: /** japod@34: * Returns true if the composite contains convertor that supports given conversion. japod@34: */ japod@34: public boolean isConversionSupported(Currency from, Currency to) { japod@34: return findConvertorFor(from, to)!=null; japod@34: } japod@34: japod@34: japod@34: /** japod@34: * If the composite contains convertor that supports given conversion, delegates to its convert method. japod@34: * Throws {@link IllegalArgumentException} convertor supporting given conversion is not found. japod@34: */ japod@34: public Money convert(Money amount, Currency destinationCurrency) throws IllegalArgumentException { japod@34: ExtendedConvertor convertor = findConvertorFor(amount.getCurrency(), destinationCurrency); japod@34: if (convertor!=null) japod@34: { japod@34: return convertor.convert(amount, destinationCurrency); japod@34: } japod@34: throw new IllegalArgumentException("Conversion not supported. Can not convert to "+destinationCurrency+"."); japod@34: } japod@34: japod@34: /** japod@34: * Finds convertor for given currencies. If not found, returns null. japod@34: * @param from japod@34: * @param to japod@34: * @return japod@34: */ japod@34: ExtendedConvertor findConvertorFor(Currency from, Currency to) { japod@34: //does linear search, in the future can cache the results. japod@34: for (ExtendedConvertor convertor:convertors) japod@34: { japod@34: if (convertor.isConversionSupported(from, to)) japod@34: { japod@34: return convertor; japod@34: } japod@34: } japod@34: return null; japod@34: } japod@34: japod@34: japod@34: @Override japod@34: public String toString() { japod@34: return getClass().getName()+" converts "+Arrays.toString(convertors); japod@34: } japod@34: japod@34: }