# HG changeset patch # User Jaroslav Tulach # Date 1224308854 -7200 # Node ID 067f86d76ac7c9b8e5518ad726a19f1a34b4f37a # Parent 0c910349ba679aa31e32470be68ab6f9b71b3176# Parent c6b50876b5cfbfc60afd8b2cc0f94c8494a621ac Merging task4 solutions diff -r 0c910349ba67 -r 067f86d76ac7 currency/test/org/apidesign/apifest08/test/Task4Test.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/currency/test/org/apidesign/apifest08/test/Task4Test.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,132 @@ +package org.apidesign.apifest08.test; + +import java.util.Date; +import junit.framework.TestCase; +import org.apidesign.apifest08.currency.Convertor; + +/** The exchange rates are not always the same. They are changing. However + * as in order to predict the future, one needs to understand own past. That is + * why it is important to know the exchange rate as it was at any time during + * the past. + *

+ * Today's quest is to enhance the convertor API to deal with dates. + * One shall be able to convert a currency at any date. Each currencies rate shall + * be associated with a range between two Date objects. In order + * to keep compatibility with old API that knew nothing about dates, the + * rates associated then are applicable "for eternity". Any use of existing + * convert methods that do not accept a Date argument, uses the current + * System.currentTimeMillis() as default date. + */ +public class Task4Test extends TestCase { + public Task4Test(String testName) { + super(testName); + } + + @Override + protected void setUp() throws Exception { + } + + @Override + protected void tearDown() throws Exception { + } + + // Backward compatibly enhance your existing API to support following + // usecases: + // + + /** Takes a convertor with any rates associated and creates new convertor + * that returns the same values as the old one for time between from to till. + * Otherwise it returns no results. This is just a helper method that + * shall call some real one in the API. + * + * @param old existing convertor + * @param from initial date (inclusive) + * @param till final date (exclusive) + * @return new convertor + */ + public static Convertor limitTo(Convertor old, Date from, Date till) { + return null; + } + + + public void testCompositionOfLimitedConvertors() throws Exception { + if (Boolean.getBoolean("ignore.failing")) { + // implement me! then delete this if statement + return; + } + + Date d1 = null; // 2008-10-01 0:00 GMT + Date d2 = null; // 2008-10-02 0:00 GMT + Date d3 = null; // 2008-10-03 0:00 GMT + + Convertor c = Task2Test.merge( + limitTo(Task1Test.createCZKtoUSD(), d1, d2), + limitTo(Task1Test.createSKKtoCZK(), d2, d3) + ); + + // convert $5 to CZK using c: + // cannot convert as no rate is applicable to current date + + // convert $8 to CZK using c: + // cannot convert as no rate is applicable to current date + + // convert 1003CZK to USD using c: + // cannot convert as no rate is applicable to current date + + // convert 16CZK using c: + // cannot convert as no rate is applicable to current date + + // convert 500SKK to CZK using c: + // cannot convert as no rate is applicable to current date + + // convert $5 to CZK using c at 2008-10-01 6:00 GMT: + // assertEquals("Result is 85 CZK"); + + // convert $8 to CZK using c at 2008-10-01 6:00 GMT: + // assertEquals("Result is 136 CZK"); + + // convert 1003CZK to USD using c at 2008-10-01 6:00 GMT: + // assertEquals("Result is 59 USD"); + + // convert 16CZK using c at 2008-10-02 9:00 GMT: + // assertEquals("Result is 20 SKK"); + + // convert 500SKK to CZK using c at 2008-10-02 9:00 GMT: + // assertEquals("Result is 400 CZK"); + + // convert 500SKK to CZK using c at 2008-10-01 6:00 GMT: + // cannot convert as no rate is applicable to current date + } + + /** Create convertor that understands two currencies, CZK and + * SKK. Make 100 SKK == 90 CZK. + * + * @return prepared convertor ready for converting SKK to CZK and CZK to SKK + */ + public static Convertor createSKKtoCZK2() { + return null; + } + + public void testDateConvetorWithTwoDifferentRates() throws Exception { + if (Boolean.getBoolean("ignore.failing")) { + // implement me! then delete this if statement + return; + } + + Date d1 = null; // 2008-10-01 0:00 GMT + Date d2 = null; // 2008-10-02 0:00 GMT + Date d3 = null; // 2008-10-03 0:00 GMT + + Convertor c = Task2Test.merge( + limitTo(createSKKtoCZK2(), d1, d2), + limitTo(Task1Test.createSKKtoCZK(), d2, d3) + ); + + // convert 500SKK to CZK using c at 2008-10-02 9:00 GMT: + // assertEquals("Result is 400 CZK"); + + // convert 500SKK to CZK using c at 2008-10-01 6:00 GMT: + // assertEquals("Result is 450 CZK"); + } + +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution04/build.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution04/build.xml Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,69 @@ + + + + + + Builds, tests, and runs the project. + + + diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution04/nbproject/build-impl.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution04/nbproject/build-impl.xml Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,642 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set src.dir + Must set test.src.dir + Must set build.dir + Must set dist.dir + Must set build.classes.dir + Must set dist.javadoc.dir + Must set build.test.classes.dir + Must set build.test.results.dir + Must set build.classes.excludes + Must set dist.jar + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + + + + + + java -cp "${run.classpath.with.dist.jar}" ${main.class} + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + java -jar "${dist.jar.resolved}" + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set run.class + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set debug.class + + + + + Must set fix.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + Some tests failed; see details above. + + + + + + + + + Must select some files in the IDE or set test.includes + + + + Some tests failed; see details above. + + + + + Must select one file in the IDE or set test.class + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + + + + + + + + + + + diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution04/nbproject/genfiles.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution04/nbproject/genfiles.properties Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,8 @@ +build.xml.data.CRC32=2ab820eb +build.xml.script.CRC32=58a52595 +build.xml.stylesheet.CRC32=be360661 +# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. +# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. +nbproject/build-impl.xml.data.CRC32=2fbfa6ce +nbproject/build-impl.xml.script.CRC32=c521eea7 +nbproject/build-impl.xml.stylesheet.CRC32=e55b27f5 diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution04/nbproject/project.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution04/nbproject/project.properties Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,68 @@ +application.title=currency +application.vendor=apidesign.org +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.tab-size=8 +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.text-limit-width=80 +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.usedProfile=default +build.classes.dir=${build.dir}/classes +build.classes.excludes=**/*.java,**/*.form +# This directory is removed when the project is cleaned: +build.dir=build +build.generated.dir=${build.dir}/generated +# Only compile against the classpath explicitly listed here: +build.sysclasspath=ignore +build.test.classes.dir=${build.dir}/test/classes +build.test.results.dir=${build.dir}/test/results +debug.classpath=\ + ${run.classpath} +debug.test.classpath=\ + ${run.test.classpath} +# This directory is removed when the project is cleaned: +dist.dir=dist +dist.jar=${dist.dir}/currency.jar +dist.javadoc.dir=${dist.dir}/javadoc +excludes= +file.reference.junit-4.4.jar=../../libs/junit-4.4.jar +file.reference.src-apifest08=.. +includes=** +jar.compress=false +javac.classpath= +# Space-separated list of extra javac options +javac.compilerargs= +javac.deprecation=false +javac.source=1.5 +javac.target=1.5 +javac.test.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir}:\ + ${file.reference.junit-4.4.jar} +javadoc.additionalparam= +javadoc.author=false +javadoc.encoding= +javadoc.noindex=false +javadoc.nonavbar=false +javadoc.notree=false +javadoc.private=false +javadoc.splitindex=true +javadoc.use=true +javadoc.version=false +javadoc.windowtitle= +jnlp.codebase.type=local +jnlp.codebase.url=file:/home/jarda/src/apifest08/currency/dist +jnlp.descriptor=application +jnlp.enabled=false +jnlp.offline-allowed=false +jnlp.signed=false +meta.inf.dir=${src.dir}/META-INF +platform.active=default_platform +run.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +# Space-separated list of JVM arguments used when running the project +# (you may also define separate properties like run-sys-prop.name=value instead of -Dname=value +# or test-sys-prop.name=value to set system properties for unit tests): +run.jvmargs= +run.test.classpath=\ + ${javac.test.classpath}:\ + ${build.test.classes.dir} +src.dir=src +test.src.dir=test diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution04/nbproject/project.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution04/nbproject/project.xml Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,16 @@ + + + org.netbeans.modules.java.j2seproject + + + Currency Convertor Solution 04 + 1.6.5 + + + + + + + + + diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution04/src/org/apidesign/apifest08/currency/CompositeConvertorImpl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution04/src/org/apidesign/apifest08/currency/CompositeConvertorImpl.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,352 @@ +package org.apidesign.apifest08.currency; + + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.Collections; +import java.util.Currency; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + + +/** + * A composite convertor allows conversions between many currencies by forwarding conversion requests to stored convertors. + * A composite convertor will build all possible conversions that are allowed by the underlying set of convertors. + * + * @author D'Arcy Smith + * @verson 1.2 + */ +final class CompositeConvertorImpl + implements Convertor +{ + /** + * The convertors that are supported. + */ + private final Convertor[] convertors; + + /** + * Keeps track of what convertors to use to convert between currencies. + */ + private final Map> possibleConversions; + + { + possibleConversions = new HashMap>(); + } + + /** + * Construct a ComositeConvertorImpl with the specified convertors. + * This will result in all possible conversions between the supplied currencies being made. + * + * @param cs the convertors to use. + * @throws IllegalArgumentException if any of the items in cs are null. + */ + CompositeConvertorImpl(Convertor ... cs) + { + int newConvertors; + + convertors = cs; + + // track all of the known conversion + for(final Convertor convertor : convertors) + { + final Set currencies; + Map possible; + + if(convertor == null) + { + throw new IllegalArgumentException("cs cannot contain null"); + } + + currencies = convertor.getCurrencies(); + + for(final Currency currency : currencies) + { + possible = possibleConversions.get(currency); + + if(possible == null) + { + possible = new HashMap(); + possibleConversions.put(currency, possible); + } + + for(final Currency c : currencies) + { + possible.put(c, convertor); + } + } + } + + // make up conversions that can be derived... eg: + // we have: + // USD <-> CAD + // CAD <-> CZK + // SSK <-> GBP + // we can derive: + // USD <-> CZK + // we cannot derive: + // USD <-> GBP + // CAD <-> GBP + // CZK <-> GBP + // + // NOTE: no attempt is made to deal with dates for DatedConvertors... nothing we can do about it. + do + { + newConvertors = 0; + + // todo... need to loop this until all the ones that can be handled are done. + for(final Currency from : getCurrencies()) + { + for(final Currency to : getCurrencies()) + { + if(!(canConvert(from, to))) + { + final Set fromCurrencies; + final Set toCurrencies; + final Set common; + + fromCurrencies = possibleConversions.get(from).keySet(); + toCurrencies = possibleConversions.get(to).keySet(); + common = new HashSet(); + + for(final Currency currency : fromCurrencies) + { + if(toCurrencies.contains(currency)) + { + common.add(currency); + } + } + + for(final Currency currency : common) + { + final Convertor convertor; + + convertor = createConvertor(from, to, currency); + possibleConversions.get(from).put(to, convertor); + possibleConversions.get(to).put(from, convertor); + newConvertors++; + } + } + } + } + } + while(newConvertors > 0); + } + + /** + * Check to see if converting between the two currencies is possible. + * + * @param from the currency to convert from. + * @param to the currency to convert to. + * @return true if the conversion is possible. + * @throws IllegalArgumentException if either from or to are null. + */ + public boolean canConvert(final Currency from, final Currency to) + { + final Map possible; + + if(from == null) + { + throw new IllegalArgumentException("from cannot be null"); + } + + if(to == null) + { + throw new IllegalArgumentException("to cannot be null"); + } + + possible = possibleConversions.get(from); + + if(possible.containsKey(to)) + { + return (true); + } + + return (false); + } + + /** + * Get the currencies that the convertor supports. Just because a currency is + * supported does not mean that canConvert will return true. + * + * @return the supported currencies. + */ + public Set getCurrencies() + { + final Set currencies; + + currencies = possibleConversions.keySet(); + + return (Collections.unmodifiableSet(currencies)); + } + + /** + * Get the conversion rate between two currencies. + * + * @param from the currency to convert from. + * @param to the currency to convert to. + * @return the conversion rate between the two currencies. + * @throws IllegalArgumentException if either from or to is null. + * @throws InvalidConversionException if canConvert would return false. + */ + public BigDecimal getConversionRate(final Currency from, final Currency to) + throws InvalidConversionException + { + final Map possible; + Convertor convertor; + + if(from == null) + { + throw new IllegalArgumentException("from cannot be null"); + } + + if(to == null) + { + throw new IllegalArgumentException("to cannot be null"); + } + + if(!(canConvert(from, to))) + { + throw new InvalidConversionException("cannot convert", to); + } + + possible = possibleConversions.get(from); + convertor = possible.get(to); + + if(convertor == null) + { + throw new Error(); + } + + return (convertor.getConversionRate(from, to)); + } + + private Convertor getConvertor(final Currency from, final Currency to) + throws InvalidConversionException + { + final Map possible; + Convertor convertor; + + if(from == null) + { + throw new IllegalArgumentException("from cannot be null"); + } + + if(to == null) + { + throw new IllegalArgumentException("to cannot be null"); + } + + if(!(canConvert(from, to))) + { + throw new InvalidConversionException("cannot convert", to); + } + + possible = possibleConversions.get(from); + convertor = possible.get(to); + + if(convertor == null) + { + throw new Error(); + } + + return (convertor); + } + + /** + * Convert an amount from one currency to another. + * + * @param from the currency to convert from. + * @param to the currency to convert to. + * @param amount the amount to convert. + * @return the converted amount. + * @throws IllegalArgumentException if any of the arguments are null. + * @throws InvalidConversionException if either from or to are not valid for the convertor. + */ + public BigDecimal convert(final Currency from, + final Currency to, + final BigDecimal amount) + throws InvalidConversionException + { + final BigDecimal result; + final Convertor convertor; + + if(amount == null) + { + throw new IllegalArgumentException("amount cannot be null"); + } + + if(from == null) + { + throw new IllegalArgumentException("from cannot be null"); + } + + if(to == null) + { + throw new IllegalArgumentException("to cannot be null"); + } + + // fixed a bug from Task2 that showed up in Task3... before we did the conversion here, + // but that meant that the underlying covnerter convert method never got called... which + // meant that in Task3 the exchange rate never changed. + convertor = getConvertor(from, to); + result = convertor.convert(from, to, amount); + + return (result.setScale(2, RoundingMode.HALF_DOWN)); + } + + /** + * Create a convertor between two currencies using another currency that is able to convert between both. + * + * @param from the currency to convert from. + * @param to the currency to convert to. + * @param intermediary the currency to use as a go-between. + * @return a Convertor that is able to convert between from an to. + * @throws IllegalArgumentException if any of the arguments are null. + */ + private Convertor createConvertor(final Currency from, + final Currency to, + final Currency intermediary) + { + final Convertor fromIntermediary; + final Convertor toIntermediary; + + if(from == null) + { + throw new IllegalArgumentException("from cannot be null"); + } + + if(to == null) + { + throw new IllegalArgumentException("to cannot be null"); + } + + if(intermediary == null) + { + throw new IllegalArgumentException("intermediary cannot be null"); + } + + fromIntermediary = possibleConversions.get(from).get(intermediary); + toIntermediary = possibleConversions.get(to).get(intermediary); + + try + { + final BigDecimal fromRate; + final BigDecimal toRate; + final BigDecimal rate; + final Convertor convertor; + + fromRate = fromIntermediary.getConversionRate(from, intermediary); + toRate = toIntermediary.getConversionRate(intermediary, to); + rate = fromRate.multiply(toRate); + convertor = ConvertorFactory.getConvertor(from, BigDecimal.ONE, to, rate); + + return (convertor); + } + catch (InvalidConversionException ex) + { + throw new Error(); + } + } +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution04/src/org/apidesign/apifest08/currency/ConverterImpl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution04/src/org/apidesign/apifest08/currency/ConverterImpl.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,148 @@ +package org.apidesign.apifest08.currency; + + +import java.math.BigDecimal; +import java.util.Currency; +import java.util.Set; + + +/** + * Convert between two currencies. + * + * @author D'Arcy Smith + * @version 1.1 + */ +class ConvertorImpl + implements ExchangeRateConvertor +{ + /** + */ + private final ExchangeRate rate; + + /** + * Constructs a convertor with the specified currencies. + * + * @param a the currency to convert from. + * @param aRate the exchage rage between from and to. + * @param b the currency to convert to. + * @param bRate the exchage rage between to and from. + * @throws IllegalArgumentException if either any of the arguments are null or if either rate <= 0. + */ + public ConvertorImpl(final ExchangeRate r) + { + if(r == null) + { + throw new IllegalArgumentException("r cannot be null"); + } + + rate = r; + } + + /** + * Convert an amount from one currency to another. + * + * @param from the currency to convert from. + * @param to the currency to convert to. + * @param amount the amount to convert. + * @return the converted amount. + * @throws IllegalArgumentException if any of the arguments are null. + * @throws InvalidConversionException if either from or to are not equal to the currencies passed to the constructor. + */ + public BigDecimal convert(final Currency from, + final Currency to, + final BigDecimal amount) + throws InvalidConversionException + { + return (rate.convert(from, to, amount)); + } + + /** + * Check to see if converting between the two currencies is possible. + * + * @param from the currency to convert from. + * @param to the currency to convert to. + * @return true if the conversion is possible. + * @throws IllegalArgumentException if either from or to are null. + */ + public boolean canConvert(final Currency from, final Currency to) + { + return (rate.canConvert(from, to)); + } + + /** + * Get the currencies that the convertor supports. + * + * @return the supported currencies. + */ + public Set getCurrencies() + { + return (rate.getCurrencies()); + } + + /** + * Get the conversion rate between two currencies. + * + * @param from the currency to convert from. + * @param to the currency to convert to. + * @return the conversion rate between the two currencies. + * @throws InvalidConversionException if canConvert would return false. + * @throws IllegalArgumentException if either from or to are null. + */ + public BigDecimal getConversionRate(final Currency from, + final Currency to) + throws InvalidConversionException + { + return (rate.getConversionRate(from, to)); + } + + /** + * Check to see if two ConvertorImpls are equal. + * + * @param obj the object to check + * @return if the ConvertorImpls are not the same (cuyrrencies and rates). + */ + @Override + public boolean equals(Object obj) + { + if (obj == null) + { + return false; + } + + if (getClass() != obj.getClass()) + { + return false; + } + + final ConvertorImpl other = (ConvertorImpl) obj; + + return (rate.equals(other.rate)); + } + + /** + * Get the hashCode of the Convertor. + * + * @return the hashCode of the convertor. + */ + @Override + public int hashCode() + { + return (rate.hashCode()); + } + + /** + * Get the currencyCode of both currencies. + * + * @return the currency codes of both currencies. + */ + @Override + public String toString() + { + return (rate.getCurrencyA().getCurrencyCode() + " to " + rate.getCurrencyB().getCurrencyCode()); + } + + public ExchangeRate getExchangeRate() + { + return (rate); + } +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution04/src/org/apidesign/apifest08/currency/Convertor.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution04/src/org/apidesign/apifest08/currency/Convertor.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,59 @@ +package org.apidesign.apifest08.currency; + + +import java.math.BigDecimal; +import java.util.Currency; +import java.util.Set; + + +/** + * Convert between two currencies. + * + * @author D'Arcy Smith + * @version 1.0 + */ +public interface Convertor +{ + /** + * Convert an amount from one currency to another. + * + * @param from the currency to convert from. + * @param to the currency to convert to. + * @param amount the amount to convert. + * @return the converted amount. + * @throws IllegalArgumentException if any of the arguments are null. + * @throws InvalidConversionException if either from or to are not valid for the convertor. + */ + BigDecimal convert(Currency from, + Currency to, + BigDecimal amount) + throws InvalidConversionException; + + /** + * Check to see if converting between the two currencies is possible. + * + * @param from the currency to convert from. + * @param to the currency to convert to. + * @return true if the conversion is possible. + */ + boolean canConvert(Currency from, Currency to); + + /** + * Get the currencies that the convertor supports. Just because a currency is + * supported does not mean that canConvert will return true. + * + * @return the supported currencies. + */ + Set getCurrencies(); + + /** + * Get the conversion rate between two currencies. + * + * @param from the currency to convert from. + * @param to the currency to convert to. + * @return the conversion rate between the two currencies. + * @throws InvalidConversionException if canConvert would return false. + */ + BigDecimal getConversionRate(final Currency from, final Currency to) + throws InvalidConversionException; +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution04/src/org/apidesign/apifest08/currency/ConvertorFactory.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution04/src/org/apidesign/apifest08/currency/ConvertorFactory.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,193 @@ +package org.apidesign.apifest08.currency; + +import java.math.BigDecimal; +import java.util.Currency; +import java.util.Date; + + +/** + * Create convertors using a flyweight to reduce the number of repetative creations of the same convertor. + * + * @author D'Arcy Smith + * @version 1.2 + */ +public final class ConvertorFactory +{ + /** + * Prevent accidental construction. + */ + private ConvertorFactory() + { + } + + /** + * Get the convertor for the specified currencies. The currency name format + * must be acceptable to java.util.Currency.getInstance(String) + * + * @param a the currency to convert from. + * @param aRate the exchange rate for a to b. + * @param b the currency to convert to. + * @param bRate the echante rate for b to a. + * @return the convertor for the specified currencies. + * @throws IllegalArgumentException if any of the arguments are null. + */ + public static Convertor getConvertor(final String a, + final BigDecimal aRate, + final String b, + final BigDecimal bRate) + { + final Currency currencyA; + final Currency currencyB; + final Convertor convertor; + + currencyA = Currency.getInstance(a); + currencyB = Currency.getInstance(b); + convertor = getConvertor(currencyA, aRate, currencyB, bRate); + + return (convertor); + } + + /** + * Get the convertor for the specified currencies. + * + * @param a the currency to convert from. + * @param aRate the exchange rate for a to b. + * @param b the currency to convert to. + * @param bRate the echante rate for b to a. + * @return the convertor for the specified currencies. + * @throws IllegalArgumentException if either any of the arguments are null or if either rate <= 0. + */ + public static Convertor getConvertor(final Currency a, + final BigDecimal aRate, + final Currency b, + final BigDecimal bRate) + { + Convertor convertor; + final ExchangeRate rate; + + if(a == null) + { + throw new IllegalArgumentException("a cannot be null"); + } + + if(b == null) + { + throw new IllegalArgumentException("b cannot be null"); + } + + if(aRate == null) + { + throw new IllegalArgumentException("aRate cannot be null"); + } + + if(bRate == null) + { + throw new IllegalArgumentException("bRate cannot be null"); + } + + rate = ExchangeRate.getExchangeRate(a, b, aRate, bRate); + convertor = getConvertor(rate); + + return (convertor); + } + + public static Convertor getConvertor(final ExchangeRate rate) + { + final ConvertorImpl convertor; + + if(rate == null) + { + throw new IllegalArgumentException("rate cannot be null"); + } + + convertor = new ConvertorImpl(rate); + + return (convertor); + } + + public static DatedConvertor getConvertor(final Date from, + final Date till, + final Convertor convertor) + { + final DateRange range; + final ExchangeRate rate; + final DatedConvertor datedConvertor; + + if(from == null) + { + throw new IllegalArgumentException("from cannot be null"); + } + + if(till == null) + { + throw new IllegalArgumentException("till cannot be null"); + } + + if(convertor == null) + { + throw new IllegalArgumentException("convertor cannot be null"); + } + + if(from.after(till)) + { + throw new IllegalArgumentException(from + " cannot be after " + till); + } + + if(convertor instanceof ExchangeRateConvertor) + { + rate = ((ExchangeRateConvertor)convertor).getExchangeRate(); + } + else + { + throw new Error(); + } + + range = new DateRange(from, till); + datedConvertor = new DatedConvertorImpl(range, rate); + + return (datedConvertor); + } + + /** + * + * @param cs + * @return + */ + public static Convertor mergeConvertors(final Convertor ... cs) + { + Convertor convertor; + int dated; + int nonDated; + + dated = 0; + nonDated = 0; + + for(final Convertor c : cs) + { + if(c instanceof DatedConvertor) + { + dated++; + } + else + { + nonDated++; + } + } + + if(dated != 0 && nonDated != 0) + { + throw new IllegalArgumentException("cannot mix DatedConvertors and non-DatedConvertors"); + } + + if(dated != 0) + { + convertor = new DatedCompositeConvertorImpl(cs); + } + else + { + convertor = new CompositeConvertorImpl(cs); + } + + return (convertor); + } +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution04/src/org/apidesign/apifest08/currency/DateRange.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution04/src/org/apidesign/apifest08/currency/DateRange.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,91 @@ +package org.apidesign.apifest08.currency; + + +import java.util.Date; + + +public final class DateRange +{ + private final Date from; + private final Date till; + + DateRange(final Date f, + final Date t) + { + if(f == null && t != null) + { + throw new IllegalArgumentException("f was null but t was not"); + } + + if(f != null && t == null) + { + throw new IllegalArgumentException("f was null but t was not"); + } + + from = f; + till = t; + } + + public Date getFrom() + { + return (from); + } + + public Date getTill() + { + return (from); + } + + public boolean isInRange(final Date date) + { + final boolean retVal; + + if(date.equals(from) || date.equals(till)) + { + retVal = true; + } + else if(date.after(from) && date.before(till)) + { + retVal = true; + } + else + { + retVal = false; + } + + return (retVal); + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final DateRange other = (DateRange) obj; + if (this.from != other.from && (this.from == null || !this.from.equals(other.from))) { + return false; + } + if (this.till != other.till && (this.till == null || !this.till.equals(other.till))) { + return false; + } + return true; + } + + @Override + public int hashCode() { + int hash = 7; + hash = 89 * hash + (this.from != null ? this.from.hashCode() : 0); + hash = 89 * hash + (this.till != null ? this.till.hashCode() : 0); + return hash; + } + + @Override + public String toString() + { + return (from + " until " + till); + } + +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution04/src/org/apidesign/apifest08/currency/DatedCompositeConvertorImpl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution04/src/org/apidesign/apifest08/currency/DatedCompositeConvertorImpl.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,319 @@ +package org.apidesign.apifest08.currency; + +import java.math.BigDecimal; +import java.util.Currency; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + + +final class DatedCompositeConvertorImpl + implements TimedConvertor +{ + /** + * The convertors that are supported. + */ + private final DatedConvertor[] convertors; + + /** + * Keeps track of what convertors to use to convert between currencies. + */ + private final Map>> datedConversions; + + { + datedConversions = new HashMap>>(); + } + + /** + * Construct a ComositeConvertorImpl with the specified convertors. + * This will result in all possible conversions between the supplied currencies being made. + * + * @param cs the convertors to use. + * @throws IllegalArgumentException if any of the items in cs are null. + */ + DatedCompositeConvertorImpl(Convertor ... cs) + { + int i; + + convertors = new DatedConvertor[cs.length]; + i = 0; + + for(final Convertor c : cs) + { + if(!(c instanceof DatedConvertor)) + { + throw new IllegalArgumentException("cs must only contain DatedConvertors"); + } + + convertors[i] = (DatedConvertor)c; + i++; + } + + // track all of the known conversion + for(final DatedConvertor convertor : convertors) + { + final Set currencies; + Map possible; + DateRange range; + + if(convertor == null) + { + throw new IllegalArgumentException("cs cannot contain null"); + } + + currencies = convertor.getCurrencies(); + range = convertor.getDateRange(); + + for(final Currency currency : currencies) + { + Map> possibleConversions; + + possibleConversions = datedConversions.get(range); + + if(possibleConversions == null) + { + possibleConversions = new HashMap>(); + datedConversions.put(range, possibleConversions); + } + + possible = possibleConversions.get(currency); + + if(possible == null) + { + possible = new HashMap(); + possibleConversions.put(currency, possible); + } + + for(final Currency c : currencies) + { + possible.put(c, convertor); + } + } + } + + + /* + // make up conversions that can be derived... eg: + // we have: + // USD <-> CAD + // CAD <-> CZK + // SSK <-> GBP + // we can derive: + // USD <-> CZK + // we cannot derive: + // USD <-> GBP + // CAD <-> GBP + // CZK <-> GBP + // + // NOTE: no attempt is made to deal with dates for DatedConvertors... nothing we can do about it. + do + { + newConvertors = 0; + + // todo... need to loop this until all the ones that can be handled are done. + for(final Currency from : getCurrencies()) + { + for(final Currency to : getCurrencies()) + { + if(!(canConvert(from, to))) + { + final Set fromCurrencies; + final Set toCurrencies; + final Set common; + Map> possibleConversions; + + possibleConversions.get(range); + fromCurrencies = possibleConversions.get(from).keySet(); + toCurrencies = possibleConversions.get(to).keySet(); + common = new HashSet(); + + for(final Currency currency : fromCurrencies) + { + if(toCurrencies.contains(currency)) + { + common.add(currency); + } + } + + for(final Currency currency : common) + { + final Convertor convertor; + + convertor = createConvertor(from, to, currency); + possibleConversions.get(from).put(to, convertor); + possibleConversions.get(to).put(from, convertor); + newConvertors++; + } + } + } + } + } + while(newConvertors > 0); + */ + } + + /** + * Check to see if converting between the two currencies is possible. + * + * @param from the currency to convert from. + * @param to the currency to convert to. + * @return true if the conversion is possible. + * @throws IllegalArgumentException if either from or to are null. + */ + public boolean canConvert(final Currency from, final Currency to) + { + throw new UnsupportedOperationException(); + } + + /** + * Get the currencies that the convertor supports. Just because a currency is + * supported does not mean that canConvert will return true. + * + * @return the supported currencies. + */ + public Set getCurrencies() + { + throw new UnsupportedOperationException(); + } + + /** + * Get the conversion rate between two currencies. + * + * @param from the currency to convert from. + * @param to the currency to convert to. + * @return the conversion rate between the two currencies. + * @throws IllegalArgumentException if either from or to is null. + * @throws InvalidConversionException if canConvert would return false. + */ + public BigDecimal getConversionRate(final Currency from, final Currency to) + throws InvalidConversionException + { + throw new UnsupportedOperationException(); + } + + private Convertor getConvertor(final Currency from, final Currency to, final Date date) + { + Map> possibleConversions; + final Map possible; + Convertor convertor; + + if(from == null) + { + throw new IllegalArgumentException("from cannot be null"); + } + + if(to == null) + { + throw new IllegalArgumentException("to cannot be null"); + } + + possibleConversions = null; + + for(final DateRange range : datedConversions.keySet()) + { + if(range.isInRange(date)) + { + possibleConversions = datedConversions.get(range); + break; + } + } + + if(possibleConversions == null) + { + return (null); + } + + possible = possibleConversions.get(from); + + + if(possible == null) + { + return (null); + } + + + convertor = possible.get(to); + + + if(convertor == null) + { + return (null); + } + + return (convertor); + } + + /** + * Convert an amount from one currency to another. + * + * @param from the currency to convert from. + * @param to the currency to convert to. + * @param amount the amount to convert. + * @return the converted amount. + * @throws IllegalArgumentException if any of the arguments are null. + * @throws InvalidConversionException if either from or to are not valid for the convertor. + */ + public BigDecimal convert(final Currency from, + final Currency to, + final BigDecimal amount) + throws InvalidConversionException + { + throw new InvalidConversionException("No date for the conversion", from); + } + + public BigDecimal convert(final Currency from, + final Currency to, + final BigDecimal amount, + final Date date) + throws InvalidConversionException + { + final Convertor convertor; + final BigDecimal total; + + convertor = getConvertor(from, to, date); + + if(convertor == null) + { + throw new InvalidConversionException("cannot convert", from); + } + + if(canConvert(from, to, date)) + { + final TimedConvertor timeConvertor; + + timeConvertor = (TimedConvertor)convertor; + total = timeConvertor.convert(from, to, amount, date); + } + else + { + throw new InvalidConversionException("cannot convert", from); + } + + return (total); + } + + public boolean canConvert(final Currency from, + final Currency to, + final Date date) + { + Convertor convertor; + final boolean retVal; + + convertor = getConvertor(from, to, date); + + if(convertor != null) + { + final TimedConvertor timeConvertor; + + timeConvertor = (TimedConvertor)convertor; + retVal = timeConvertor.canConvert(from, to, date); + } + else + { + retVal = false; + } + + return (retVal); + } +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution04/src/org/apidesign/apifest08/currency/DatedConvertor.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution04/src/org/apidesign/apifest08/currency/DatedConvertor.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,9 @@ +package org.apidesign.apifest08.currency; + + +public interface DatedConvertor + extends ExchangeRateConvertor, + TimedConvertor +{ + DateRange getDateRange(); +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution04/src/org/apidesign/apifest08/currency/DatedConvertorImpl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution04/src/org/apidesign/apifest08/currency/DatedConvertorImpl.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,82 @@ +package org.apidesign.apifest08.currency; + +import java.math.BigDecimal; +import java.util.Currency; +import java.util.Date; + + +final class DatedConvertorImpl + extends ConvertorImpl + implements DatedConvertor +{ + private final DateRange range; + + DatedConvertorImpl(final DateRange rng, + final ExchangeRate r) + { + super(r); + + if(rng == null) + { + throw new IllegalArgumentException("rng cannot be null"); + } + + range = rng; + } + + public DateRange getDateRange() + { + return (range); + } + + @Override + public BigDecimal convert(final Currency from, + final Currency to, + final BigDecimal amount) + throws InvalidConversionException + { + final BigDecimal total; + + total = convert(from, to, amount, new Date(System.currentTimeMillis())); + + return (total); + } + + public BigDecimal convert(final Currency from, + final Currency to, + final BigDecimal amount, + final Date date) + throws InvalidConversionException + { + final BigDecimal total; + + if(range.isInRange(date)) + { + total = super.convert(from, to, amount); + } + else + { + throw new InvalidConversionException("cannot convert for date", from); + } + + return (total); + } + + public boolean canConvert(final Currency from, + final Currency to, + final Date date) + { + final boolean retVal; + + if(canConvert(from, to)) + { + retVal = range.isInRange(date); + } + else + { + retVal = false; + } + + return (retVal); + } +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution04/src/org/apidesign/apifest08/currency/ExchangeRate.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution04/src/org/apidesign/apifest08/currency/ExchangeRate.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,326 @@ +package org.apidesign.apifest08.currency; + + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.Collections; +import java.util.Currency; +import java.util.HashSet; +import java.util.Set; + + +/** + * The exchange rate between two currencies. + * + * @author D'Arcy Smith + * @version 1.1 + */ +public final class ExchangeRate +{ + /** + * + */ + private final Currency currencyA; + + /** + * + */ + private final Currency currencyB; + + /** + * + */ + private final BigDecimal rateAtoB; + + /** + * + */ + private final BigDecimal rateBtoA; + + /** + * Construct an ExchangeRate with the specified values. + * + * @param a the first currency + * @param b the second currency + * @param ra the rate to convert a to b + * @param rb the rate to covertt b to a + * @throws IllegalArgumentException if any parameter is null. + */ + public ExchangeRate(final Currency a, + final Currency b, + final BigDecimal ra, + final BigDecimal rb) + { + if(a == null) + { + throw new IllegalArgumentException("a cannot be null"); + } + + if(b == null) + { + throw new IllegalArgumentException("b cannot be null"); + } + + if(ra == null) + { + throw new IllegalArgumentException("ra cannot be null"); + } + + if(rb == null) + { + throw new IllegalArgumentException("rb cannot be null"); + } + + if(ra.compareTo(BigDecimal.ZERO) <= 0) + { + throw new IllegalArgumentException("ra cannot be <= 0, was: " + ra); + } + + if(rb.compareTo(BigDecimal.ZERO) <= 0) + { + throw new IllegalArgumentException("rb cannot be <= 0, was: " + ra); + } + + currencyA = a; + currencyB = b; + rateAtoB = ra; + rateBtoA = rb; + } + + /** + * Get the first currency. + * + * @return the first currency. + */ + public Currency getCurrencyA() + { + return currencyA; + } + + /** + * Get the second currency. + * + * @return the second currency. + */ + public Currency getCurrencyB() + { + return currencyB; + } + + /** + * Get the conversion rate from currencyA to currencyB. + * + * @return the conversion rate from currencyA to currencyB. + */ + public BigDecimal getRateAtoB() + { + return rateAtoB; + } + + /** + * Get the conversion rate from currencyB to currencyA. + * + * @return the conversion rate from currencyB to currencyA. + */ + public BigDecimal getRateBtoA() + { + return rateBtoA; + } + + public static ExchangeRate getExchangeRate(final Currency a, + final Currency b, + final BigDecimal va, + final BigDecimal vb) + { + final BigDecimal rateAtoB; + final BigDecimal rateBtoA; + final ExchangeRate rate; + + if(a == null) + { + throw new IllegalArgumentException("a cannot be null"); + } + + if(b == null) + { + throw new IllegalArgumentException("b cannot be null"); + } + + if(a.equals(b)) + { + rateAtoB = BigDecimal.ONE; + rateBtoA = BigDecimal.ONE; + } + else + { + rateAtoB = vb.divide(va, 20, RoundingMode.HALF_DOWN); + rateBtoA = va.divide(vb, 20, RoundingMode.HALF_DOWN); + } + + rate = new ExchangeRate(a, + b, + rateAtoB.setScale(20, RoundingMode.HALF_EVEN), + rateBtoA.setScale(20, RoundingMode.HALF_EVEN)); + + return (rate); + } + + public BigDecimal convert(final Currency from, + final Currency to, + final BigDecimal amount) + throws InvalidConversionException + { + final BigDecimal result; + + if(amount == null) + { + throw new IllegalArgumentException("amount cannot be null"); + } + + if(from == null) + { + throw new IllegalArgumentException("from cannot be null"); + } + + if(to == null) + { + throw new IllegalArgumentException("to cannot be null"); + } + + if(!(from.equals(currencyA)) && (!(from.equals(currencyB)))) + { + throw new InvalidConversionException("cannot convert from: " + from.getCurrencyCode(), from, currencyA, currencyB); + } + + if(!(to.equals(currencyA)) && (!(to.equals(currencyB)))) + { + throw new InvalidConversionException("cannot convert to: " + to.getCurrencyCode(), to, currencyA, currencyB); + } + + result = amount.multiply(getConversionRate(from, to)); + + return (result.setScale(2, RoundingMode.HALF_DOWN)); + } + + /** + * Check to see if converting between the two currencies is possible. + * + * @param from the currency to convert from. + * @param to the currency to convert to. + * @return true if the conversion is possible. + * @throws IllegalArgumentException if either from or to are null. + */ + public boolean canConvert(final Currency from, final Currency to) + { + if(from == null) + { + throw new IllegalArgumentException("from cannot be null"); + } + + if(to == null) + { + throw new IllegalArgumentException("to cannot be null"); + } + + return ((from.equals(currencyA) || from.equals(currencyB)) && + (to.equals(currencyA) || to.equals(currencyB))); + } + /** + * Get the currencies that the convertor supports. + * + * @return the supported currencies. + */ + public Set getCurrencies() + { + final Set currencies; + + currencies = new HashSet(); + currencies.add(currencyA); + currencies.add(currencyB); + + return (Collections.unmodifiableSet(currencies)); + } + + /** + * Get the conversion rate between two currencies. + * + * @param from the currency to convert from. + * @param to the currency to convert to. + * @return the conversion rate between the two currencies. + * @throws InvalidConversionException if canConvert would return false. + * @throws IllegalArgumentException if either from or to are null. + */ + public BigDecimal getConversionRate(final Currency from, + final Currency to) + throws InvalidConversionException + { + final BigDecimal rate; + + if(from == null) + { + throw new IllegalArgumentException("from cannot be null"); + } + + if(to == null) + { + throw new IllegalArgumentException("to cannot be null"); + } + + if(from.equals(to)) + { + rate = BigDecimal.ONE; + } + else + { + if(from.equals(currencyA)) + { + rate = rateAtoB; + } + else + { + rate = rateBtoA; + } + } + + return (rate); + } + + public String toString() + { + return (rateAtoB + " : " + rateBtoA); + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final ExchangeRate other = (ExchangeRate) obj; + if (this.currencyA != other.currencyA && (this.currencyA == null || !this.currencyA.equals(other.currencyA))) { + return false; + } + if (this.currencyB != other.currencyB && (this.currencyB == null || !this.currencyB.equals(other.currencyB))) { + return false; + } + if (this.rateAtoB != other.rateAtoB && (this.rateAtoB == null || !this.rateAtoB.equals(other.rateAtoB))) { + return false; + } + if (this.rateBtoA != other.rateBtoA && (this.rateBtoA == null || !this.rateBtoA.equals(other.rateBtoA))) { + return false; + } + return true; + } + + @Override + public int hashCode() { + int hash = 7; + hash = 97 * hash + (this.currencyA != null ? this.currencyA.hashCode() : 0); + hash = 97 * hash + (this.currencyB != null ? this.currencyB.hashCode() : 0); + hash = 97 * hash + (this.rateAtoB != null ? this.rateAtoB.hashCode() : 0); + hash = 97 * hash + (this.rateBtoA != null ? this.rateBtoA.hashCode() : 0); + return hash; + } +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution04/src/org/apidesign/apifest08/currency/ExchangeRateConvertor.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution04/src/org/apidesign/apifest08/currency/ExchangeRateConvertor.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,8 @@ +package org.apidesign.apifest08.currency; + + +public interface ExchangeRateConvertor + extends Convertor +{ + ExchangeRate getExchangeRate(); +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution04/src/org/apidesign/apifest08/currency/ExchangeRateFinder.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution04/src/org/apidesign/apifest08/currency/ExchangeRateFinder.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,22 @@ +package org.apidesign.apifest08.currency; + +import java.util.Currency; + + +/** + * Used to look up the exchange rate between two currencies. + * + * @author D'Arcy Smith + * @version 1.0 + */ +public interface ExchangeRateFinder +{ + /** + * Find the exchange rate between two currencies. + * + * @param a the currency to convert from. + * @param b the currency to convert to. + * @return the exchange rate for conversions between the two currencies. + */ + ExchangeRate findRate(Currency a, Currency b); +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution04/src/org/apidesign/apifest08/currency/InvalidConversionException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution04/src/org/apidesign/apifest08/currency/InvalidConversionException.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,95 @@ +package org.apidesign.apifest08.currency; + + +import java.util.Currency; + + +/** + * Thrown when a currency is invalid for a given Convertor. + * + * @author D'Arcy Smith + * @version 1.0 + */ +public class InvalidConversionException + extends Exception +{ + /** + * The currency that was tried. + */ + private final Currency badCurrency; + + /** + * A currency that is valid for the Convertor. + */ + private final Currency currencyA; + + /** + * A currency that is valid for the Convertor. + */ + private final Currency currencyB; + + + /** + * Construct a new InvalidConversionException with the specified message. + * + * @param msg the message for getMessage. + * @param bad the currency that is not valid. + */ + public InvalidConversionException(final String msg, + final Currency bad) + { + this(msg, bad, null, null); + } + + /** + * Construct a new InvalidConversionException with the specified message. + * + * @param msg the message for getMessage. + * @param bad the currency that is not valid. + * @param a a valid currency. + * @param b a valid currency. + */ + public InvalidConversionException(final String msg, + final Currency bad, + final Currency a, + final Currency b) + { + super(msg); + + badCurrency = bad; + currencyA = a; + currencyB = b; + } + + /** + * Get the currency that is not valid. + * + * @return the badCurrency + */ + public Currency getBadCurrency() + { + return (badCurrency); + } + + /** + * Get a currency that is valid. + * + * @return the currencyA passed to the constructor. + */ + public Currency getCurrencyA() + { + return (currencyA); + } + + /** + * Get a currency that is valid. + * + * @return the currencyB passed to the constructor. + */ + public Currency getCurrencyB() + { + return (currencyB); + } + + +} \ No newline at end of file diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution04/src/org/apidesign/apifest08/currency/OnlineConvertor.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution04/src/org/apidesign/apifest08/currency/OnlineConvertor.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,175 @@ +package org.apidesign.apifest08.currency; + + +import java.math.BigDecimal; +import java.util.Currency; +import java.util.Set; + + +/** + * A Convertor that looks up the exchange rate with each call to "convert". + * + * @author D'Arcy Smith + * @version 1.0 + */ +public class OnlineConvertor + implements Convertor +{ + /** + * The currency to convert from. + */ + private final Currency currencyA; + + /** + * The currency to convert to. + */ + private final Currency currencyB; + + /** + * Used to find the current exchange rate. + */ + private final ExchangeRateFinder finder; + + /** + * The convertor to perform the conversion. + */ + private Convertor realConvertor; + + /** + * Constructs an OnlinConvertor with the specified currencies. + * + * @param a the currency to convert from. + * @param b the currency to convert to. + * @param f the finder used to obtanin the current exchange rate. + * @throws IllegalArgumentException if either a or b are null. + */ + public OnlineConvertor(final Currency a, + final Currency b, + final ExchangeRateFinder f) + { + if(a == null) + { + throw new IllegalArgumentException("a cannot be null"); + } + + if(b == null) + { + throw new IllegalArgumentException("b cannot be null"); + } + + if(f == null) + { + throw new IllegalArgumentException("f cannot be null"); + } + + currencyA = a; + currencyB = b; + finder = f; + realConvertor = lookupRate(); + } + + /** + * Convert an amount from one currency to another. Before the conversion takes place + * the current exchange rate is looked up. + * + * @param from the currency to convert from. + * @param to the currency to convert to. + * @param amount the amount to convert. + * @return the converted amount. + * @throws IllegalArgumentException if any of the arguments are null. + * @throws InvalidConversionException if either from or to are not equal to the currencies passed to the constructor. + */ + public BigDecimal convert(final Currency from, + final Currency to, + final BigDecimal amount) + throws InvalidConversionException + { + final BigDecimal value; + + synchronized(this) + { + realConvertor = lookupRate(); + value = realConvertor.convert(from, to, amount); + } + + return (value); + } + + /** + * Lookup the current exchange rate. + * + * @return + */ + private final Convertor lookupRate() + { + final Convertor convertor; + final ExchangeRate rate; + + rate = finder.findRate(currencyA, currencyB); + convertor = ConvertorFactory.getConvertor(rate.getCurrencyA(), rate.getRateAtoB(), rate.getCurrencyB(), rate.getRateBtoA()); + + return (convertor); + } + + /** + * Check to see if converting between the two currencies is possible. + * + * @param from the currency to convert from. + * @param to the currency to convert to. + * @return true if the conversion is possible. + * @throws IllegalArgumentException if either from or to are null. + */ + public boolean canConvert(final Currency from, + final Currency to) + { + if(from == null) + { + throw new IllegalArgumentException("from cannot be null"); + } + + if(to == null) + { + throw new IllegalArgumentException("to cannot be null"); + } + + return (realConvertor.canConvert(from, to)); + } + + /** + * Get the currencies that the convertor supports. + * + * @return the supported currencies. + */ + public Set getCurrencies() + { + return (realConvertor.getCurrencies()); + } + + /** + * Get the conversion rate between two currencies. This does not lookup the current + * conversion rate (it probably should, but given the way the contest works that might + * not be a good idea - if it were the real world way it might be a good idea). + * + * @param from the currency to convert from. + * @param to the currency to convert to. + * @return the conversion rate between the two currencies. + * @throws InvalidConversionException if canConvert would return false. + * @throws IllegalArgumentException if either from or to are null. + */ + public BigDecimal getConversionRate(final Currency from, + final Currency to) + throws InvalidConversionException + { + if(from == null) + { + throw new IllegalArgumentException("from cannot be null"); + } + + if(to == null) + { + throw new IllegalArgumentException("to cannot be null"); + } + + return (realConvertor.getConversionRate(from, to)); + } +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution04/src/org/apidesign/apifest08/currency/TimedConvertor.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution04/src/org/apidesign/apifest08/currency/TimedConvertor.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,17 @@ +package org.apidesign.apifest08.currency; + +import java.math.BigDecimal; +import java.util.Currency; +import java.util.Date; + + +public interface TimedConvertor + extends Convertor +{ + BigDecimal convert(Currency from, + Currency to, + BigDecimal amount, + Date date) + throws InvalidConversionException; + boolean canConvert(Currency from, Currency to, Date date); +} \ No newline at end of file diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution04/test/org/apidesign/apifest08/test/Task1Test.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution04/test/org/apidesign/apifest08/test/Task1Test.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,223 @@ +package org.apidesign.apifest08.test; + + +import java.math.BigDecimal; +import java.util.Currency; +import java.util.Set; +import junit.framework.TestCase; +import org.apidesign.apifest08.currency.Convertor; +import org.apidesign.apifest08.currency.ConvertorFactory; +import org.apidesign.apifest08.currency.InvalidConversionException; + + +/** Finish the Convertor API, and then write bodies of methods inside + * of this class to match the given tasks. To fullfil your task, use the + * API define in the org.apidesign.apifest08.currency package. + * Do not you reflection, or other hacks as your code + * shall run without any runtime permissions. + */ +public class Task1Test extends TestCase { + + public final static Currency CZK; + public final static Currency SKK; + public final static Currency USD; + + static + { + CZK = Currency.getInstance("CZK"); + SKK = Currency.getInstance("SKK"); + USD = Currency.getInstance("USD"); + } + + public Task1Test(String testName) { + super(testName); + } + + @Override + protected void setUp() throws Exception { + } + + @Override + protected void tearDown() throws Exception { + } + + /** Create convertor that understands two currencies, CZK and + * USD. Make 1 USD == 17 CZK. + * + * Creation of the convertor shall not require subclassing of any class + * or interface on the client side. + * + * @return prepared convertor ready for converting USD to CZK and CZK to USD + */ + public static Convertor createCZKtoUSD() + { + return (ConvertorFactory.getConvertor("CZK", BigDecimal.valueOf(17.0), + "USD", BigDecimal.valueOf(1))); + } + + /** Create convertor that understands two currencies, CZK and + * SKK. Make 100 SKK == 80 CZK. + * + * Creation of the convertor shall not require subclassing of any class + * or interface on the client side. + * + * @return prepared convertor ready for converting SKK to CZK and CZK to SKK + */ + public static Convertor createSKKtoCZK() + { + return (ConvertorFactory.getConvertor(Currency.getInstance("SKK"), BigDecimal.valueOf(100), + Currency.getInstance("CZK"), BigDecimal.valueOf(80))); + } + + /** Use the convertor from createCZKtoUSD method and do few conversions + * with it. + */ + public void testCurrencyCZKUSD() throws Exception { + Convertor c = createCZKtoUSD(); + BigDecimal result; + + // convert $5 to CZK using c: + // assertEquals("Result is 85 CZK"); + result = c.convert(USD, CZK, BigDecimal.valueOf(5)); + assertEquals(new BigDecimal("85.00"), result); + + // convert $8 to CZK + // assertEquals("Result is 136 CZK"); + result = c.convert(USD, CZK, BigDecimal.valueOf(8)); + assertEquals(new BigDecimal("136.00"), result); + + // convert 1003CZK to USD + // assertEquals("Result is 59 USD"); + result = c.convert(CZK, USD, BigDecimal.valueOf(1003)); + assertEquals(new BigDecimal("59.00"), result); + } + + /** Use the convertor from createSKKtoCZK method and do few conversions + * with it. + */ + public void testCurrencySKKCZK() throws Exception { + Convertor c = createSKKtoCZK(); + BigDecimal result; + + // convert 16CZK using c: + // assertEquals("Result is 20 SKK"); + result = c.convert(CZK, SKK, BigDecimal.valueOf(16)); + assertEquals(new BigDecimal("20.00"), result); + + // convert 500SKK to CZK + // assertEquals("Result is 400 CZK"); + result = c.convert(SKK, CZK, BigDecimal.valueOf(500)); + assertEquals(new BigDecimal("400.00"), result); + } + + /** + * Verify that the CZK to USD convertor knows nothing about SKK. + */ + public void testCannotConvertToSKKwithCZKUSDConvertor() + throws Exception + { + Convertor c = createCZKtoUSD(); + + try + { + // convert $5 to SKK, the API shall say this is not possible + c.convert(USD, SKK, BigDecimal.valueOf(5)); + fail("cannot use the CZKtoUSD converter to convert to SKK"); + } + catch(InvalidConversionException ex) + { + assertEquals("cannot convert to: SKK", ex.getMessage()); + assertEquals(SKK, ex.getBadCurrency()); + assertEquals(CZK, ex.getCurrencyA()); + assertEquals(USD, ex.getCurrencyB()); + } + + try + { + // convert 500 SKK to CZK, the API shall say this is not possible + c.convert(SKK, CZK, BigDecimal.valueOf(5)); + fail("cannot use the CZKtoUSD converter to convert from SKK"); + } + catch(InvalidConversionException ex) + { + assertEquals("cannot convert from: SKK", ex.getMessage()); + assertEquals(SKK, ex.getBadCurrency()); + assertEquals(CZK, ex.getCurrencyA()); + assertEquals(USD, ex.getCurrencyB()); + } + } + + /** + * Verify that the CZK to SKK convertor knows nothing about USD. + */ + public void testCannotConvertToUSDwithSKKCZKConvertor() + throws Exception + { + Convertor c = createSKKtoCZK(); + + try + { + // convert $5 to SKK, the API shall say this is not possible + c.convert(USD, SKK, BigDecimal.valueOf(5)); + fail("cannot use the CZKtoUSD converter to convert to SKK"); + } + catch(InvalidConversionException ex) + { + assertEquals("cannot convert from: USD", ex.getMessage()); + assertEquals(USD, ex.getBadCurrency()); + assertEquals(SKK, ex.getCurrencyA()); + assertEquals(CZK, ex.getCurrencyB()); + } + + try + { + // convert 500 CZK to USD, the API shall say this is not possible + c.convert(CZK, USD, BigDecimal.valueOf(500)); + fail("cannot use the CZKtoUSD converter to convert from SKK"); + } + catch(InvalidConversionException ex) + { + assertEquals("cannot convert to: USD", ex.getMessage()); + assertEquals(USD, ex.getBadCurrency()); + assertEquals(SKK, ex.getCurrencyA()); + assertEquals(CZK, ex.getCurrencyB()); + } + } + + public void testGetCurrencies() + { + Convertor c; + Set currencies; + + c = createSKKtoCZK(); + currencies = c.getCurrencies(); + assertEquals(2, currencies.size()); + assertTrue(currencies.contains(Currency.getInstance("SKK"))); + assertTrue(currencies.contains(Currency.getInstance("CZK"))); + + c = createCZKtoUSD(); + currencies = c.getCurrencies(); + assertEquals(2, currencies.size()); + assertTrue(currencies.contains(Currency.getInstance("USD"))); + assertTrue(currencies.contains(Currency.getInstance("CZK"))); + } + + public void testGetConverstionRate() + throws InvalidConversionException + { + Convertor c; + + c = createSKKtoCZK(); + assertEquals(1.0, c.getConversionRate(Currency.getInstance("CZK"), Currency.getInstance("CZK")).doubleValue()); + assertEquals(1.0, c.getConversionRate(Currency.getInstance("SKK"), Currency.getInstance("SKK")).doubleValue()); + assertEquals(0.80, c.getConversionRate(Currency.getInstance("SKK"), Currency.getInstance("CZK")).doubleValue()); + assertEquals(1.25, c.getConversionRate(Currency.getInstance("CZK"), Currency.getInstance("SKK")).doubleValue()); + + c = createCZKtoUSD(); + assertEquals(1.0, c.getConversionRate(Currency.getInstance("CZK"), Currency.getInstance("CZK")).doubleValue()); + assertEquals(1.0, c.getConversionRate(Currency.getInstance("USD"), Currency.getInstance("USD")).doubleValue()); + assertEquals(1.0/17.0, c.getConversionRate(Currency.getInstance("CZK"), Currency.getInstance("USD")).doubleValue(), 0.00000000000000001); + assertEquals(17.0, c.getConversionRate(Currency.getInstance("USD"), Currency.getInstance("CZK")).doubleValue(), 0.00000000000000001); + } +} + diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution04/test/org/apidesign/apifest08/test/Task2Test.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution04/test/org/apidesign/apifest08/test/Task2Test.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,179 @@ +package org.apidesign.apifest08.test; + +import java.math.BigDecimal; +import java.util.Currency; +import java.util.Set; +import junit.framework.TestCase; +import org.apidesign.apifest08.currency.Convertor; +import org.apidesign.apifest08.currency.ConvertorFactory; +import org.apidesign.apifest08.currency.InvalidConversionException; + + +/** There are many currencies around the world and many banks manipulate + * with more than one or two at the same time. As banks are usually the + * best paying clients, which is true even in case of your Convertor API, + * it is reasonable to listen to their requests. + *

+ * The quest for today is to enhance your existing convertor API to hold + * information about many currencies and allow conversions between any of them. + * Also, as conversion rates for diferent currencies usually arise from various + * bank departments, there is another important need. There is a need to + * compose two convertors into one by merging all the information about + * currencies they know about. + */ +public class Task2Test extends TestCase +{ + private final static Currency CZK; + private final static Currency SKK; + private final static Currency USD; + + static + { + CZK = Currency.getInstance("CZK"); + SKK = Currency.getInstance("SKK"); + USD = Currency.getInstance("USD"); + } + + public Task2Test(String testName) + { + super(testName); + } + + @Override + protected void setUp() + throws Exception + { + } + + @Override + protected void tearDown() + throws Exception + { + } + + // As in Task1Test, keep in mind, that there are three parts + // of the whole system: + // 1. there is someone who knows the current exchange rate + // 2. there is someone who wants to do the conversion + // 3. there is the API between 1. and 2. which allows them to communicate + // + // Please backward compatibly enhance your existing API to support following + // usecases: + // + + /** Create convertor that understands two currencies, CZK and + * SKK. Make 100 SKK == 75 CZK. This is method for the group of users that + * knows the exchange rate, and needs to use the API to create objects + * with the exchange rate. Anyone shall be ready to call this method without + * any other method being called previously. The API itself shall know + * nothing about any rates, before this method is called. + */ + public static Convertor createTripleConvertor() { + // Rates: 1USD = 15CZK + // Rates: 1USD = 20SKK + // Rates: 75CZK = 100SKK + Convertor c = ConvertorFactory.mergeConvertors( + ConvertorFactory.getConvertor(USD, BigDecimal.ONE, CZK, BigDecimal.valueOf(15.00)), + ConvertorFactory.getConvertor(USD, BigDecimal.ONE, SKK, BigDecimal.valueOf(20.00)) + ); + + return c; + } + + /** Define convertor that understands three currencies. Use it. + */ + public void testConvertorForUSDandCZKandSKK() throws Exception { + Convertor c = createTripleConvertor(); + + // convert $5 to CZK using c: + // assertEquals("Result is 75 CZK"); + assertEquals(new BigDecimal("75.00"), c.convert(USD, CZK, BigDecimal.valueOf(5.00))); + + // convert $5 to SKK using c: + // assertEquals("Result is 100 SKK"); + assertEquals(new BigDecimal("100.00"), c.convert(USD, SKK, BigDecimal.valueOf(5.00))); + + // convert 200SKK to CZK using c: + // assertEquals("Result is 150 CZK"); + assertEquals(new BigDecimal("150.00"), c.convert(SKK, CZK, BigDecimal.valueOf(200.00))); + + // convert 200SKK to USK using c: + // assertEquals("Result is 10 USD"); + assertEquals(new BigDecimal("10.00"), c.convert(SKK, USD, BigDecimal.valueOf(200.00))); + } + + /** Merge all currency rates of convertor 1 with convertor 2. + * Implement this using your API, preferably this method just delegates + * into some API method which does the actual work, without requiring + * API clients to code anything complex. + */ + public static Convertor merge(Convertor one, Convertor two) { + return ConvertorFactory.mergeConvertors(one, two); + } + + /** Join the convertors from previous task, Task1Test and show that it + * can be used to do reasonable conversions. + */ + public void testConvertorComposition() throws Exception { + Convertor c = merge( + Task1Test.createCZKtoUSD(), + Task1Test.createSKKtoCZK() + ); + + // convert $5 to CZK using c: + // assertEquals("Result is 85 CZK"); + assertEquals(new BigDecimal("85.00"), c.convert(USD, CZK, BigDecimal.valueOf(5.00))); + + // convert $8 to CZK using c: + // assertEquals("Result is 136 CZK"); + assertEquals(new BigDecimal("136.00"), c.convert(USD, CZK, BigDecimal.valueOf(8.00))); + + // convert 1003CZK to USD using c: + // assertEquals("Result is 59 USD"); + assertEquals(new BigDecimal("59.00"), c.convert(CZK, USD, BigDecimal.valueOf(1003.00))); + + // convert 16CZK using c: + // assertEquals("Result is 20 SKK"); + assertEquals(new BigDecimal("20.00"), c.convert(CZK, SKK, BigDecimal.valueOf(16.00))); + + // convert 500SKK to CZK using c: + // assertEquals("Result is 400 CZK"); + assertEquals(new BigDecimal("400.00"), c.convert(SKK, CZK, BigDecimal.valueOf(500.00))); + } + + public void testGetCurrencies() + { + Convertor c = merge( + Task1Test.createCZKtoUSD(), + Task1Test.createSKKtoCZK() + ); + Set currencies; + + currencies = c.getCurrencies(); + assertEquals(3, currencies.size()); + assertTrue(currencies.contains(Currency.getInstance("SKK"))); + assertTrue(currencies.contains(Currency.getInstance("CZK"))); + assertTrue(currencies.contains(Currency.getInstance("USD"))); + } + + public void testGetConverstionRate() + throws InvalidConversionException + { + Convertor c = merge( + Task1Test.createCZKtoUSD(), + Task1Test.createSKKtoCZK() + ); + + assertEquals(1.0, c.getConversionRate(USD, USD).doubleValue(), 0.0000000000000001); + assertEquals(17.0, c.getConversionRate(USD, CZK).doubleValue(), 0.0000000000000001); + assertEquals(21.25, c.getConversionRate(USD, SKK).doubleValue(), 0.0000000000000001); + + assertEquals(1.0 / 17.0, c.getConversionRate(CZK, USD).doubleValue(), 0.0000000000000001); + assertEquals(1.0, c.getConversionRate(CZK, CZK).doubleValue(), 0.0000000000000001); + assertEquals(1.25, c.getConversionRate(CZK, SKK).doubleValue(), 0.0000000000000001); + + assertEquals(0.04705882352941176, c.getConversionRate(SKK, USD).doubleValue(), 0.0000000000000001); + assertEquals(0.8, c.getConversionRate(SKK, CZK).doubleValue(), 0.0000000000000001); + assertEquals(1.0, c.getConversionRate(SKK, SKK).doubleValue(), 0.0000000000000001); + } +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution04/test/org/apidesign/apifest08/test/Task3Test.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution04/test/org/apidesign/apifest08/test/Task3Test.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,145 @@ +package org.apidesign.apifest08.test; + +import java.math.BigDecimal; +import java.util.Currency; +import junit.framework.TestCase; +import org.apidesign.apifest08.currency.Convertor; +import org.apidesign.apifest08.currency.InvalidConversionException; +import org.apidesign.apifest08.currency.OnlineConvertor; + +/** The exchange rates are not always the same. They are changing. Day by day, + * hour by hour, minute by minute. For every bank it is important to always + * have the actual exchange rate available in the system. That is why let's + * create a pluggable convertor that will always have up to date value of its + * exchange rate. + *

+ * The quest for today is to allow 3rd party developer to write a convertor + * that adjusts its exchange rate everytime it is queried. This convertor is + * written by independent vendor, the vendor knows only your Convertor API, + * he does not know how the whole system looks and how the convertor is supposed + * to be used. + */ +public class Task3Test + extends TestCase +{ + private final static Currency CZK; + private final static Currency SKK; + private final static Currency USD; + + static + { + CZK = Currency.getInstance("CZK"); + SKK = Currency.getInstance("SKK"); + USD = Currency.getInstance("USD"); + } + + public Task3Test(String testName) + { + super(testName); + } + + @Override + protected void setUp() throws Exception + { + } + + @Override + protected void tearDown() throws Exception + { + } + + // Backward compatibly enhance your existing API to support following + // usecases: + // + + + /** Without knowing anything about the surrounding system, write an + * implementation of convertor that will return different rates everytime + * it is queried. Convert USD to CZK and vice versa. Start with the rate of + * 1USD = 16CZK and adjust it in favor of CZK by 0.01 CZK with every query. + * As soon as you reach 1USD = 15CZK adjust it by 0.01 CZK in favor of USD + * until you reach 1USD = 16CZK + * + * @return new instance of "online" USD and CZK convertor starting with rate 1USD = 16CZK + * @throws InvalidConversionException + */ + public static Convertor createOnlineCZKUSDConvertor() + throws InvalidConversionException + { + final Convertor convertor; + + convertor = new OnlineConvertor(USD, + CZK, + new TestExchangeRateFinder(new BigDecimal("15.00"), + new BigDecimal("16.00"), + new BigDecimal("16.00"), + new BigDecimal("0.01"), + new BigDecimal("-0.01"))); + + // initial rate: 1USD = 16CZK + // 2nd query 1USD = 15.99CZK + // 3rd query 1USD = 15.98CZK + // until 1USD = 15.00CZK + // then 1USD = 15.01CZK + // then 1USD = 15.02CZK + // and so on and on up to 1USD = 16CZK + // and then another round to 15, etc. + return convertor; + } + + public void testFewQueriesForOnlineConvertor() + throws InvalidConversionException + { + Convertor c = createOnlineCZKUSDConvertor(); + doFewQueriesForOnlineConvertor(c); + } + + static void doFewQueriesForOnlineConvertor(Convertor c) + throws InvalidConversionException + { + BigDecimal amount; + + // convert $5 to CZK using c: + //assertEquals("Result is 80 CZK"); + amount = c.convert(USD, CZK, new BigDecimal("5.00")); + assertEquals(new BigDecimal("80.00"), amount); + + // convert $8 to CZK using c: + //assertEquals("Result is 127.92 CZK"); + amount = c.convert(USD, CZK, new BigDecimal("8.00")); + assertEquals(new BigDecimal("127.92"), amount); + + // convert $1 to CZK using c: + //assertEquals("Result is 15.98 CZK"); + amount = c.convert(USD, CZK, new BigDecimal("1.00")); + assertEquals(new BigDecimal("15.98"), amount); + + // convert 15.97CZK to USD using c: + //assertEquals("Result is 1$"); + amount = c.convert(CZK, USD, new BigDecimal("15.97")); + assertEquals(new BigDecimal("1.00"), amount); + } + + /** Join the convertors and show they behave sane. + */ + public void testOnlineConvertorComposition() throws Exception { + BigDecimal amount; + + Convertor c = Task2Test.merge( + createOnlineCZKUSDConvertor(), + Task1Test.createSKKtoCZK() + ); + + // convert 16CZK to SKK using c: + // assertEquals("Result is 20 SKK"); + amount = c.convert(CZK, SKK, new BigDecimal("16.00")); + assertEquals(new BigDecimal("20.00"), amount); + + // convert 500SKK to CZK using c: + // assertEquals("Result is 400 CZK"); + amount = c.convert(SKK, CZK, new BigDecimal("500.00")); + assertEquals(new BigDecimal("400.00"), amount); + + doFewQueriesForOnlineConvertor(c); + } +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution04/test/org/apidesign/apifest08/test/Task4Test.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution04/test/org/apidesign/apifest08/test/Task4Test.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,237 @@ +package org.apidesign.apifest08.test; + +import java.math.BigDecimal; +import java.util.Calendar; +import java.util.Date; +import java.util.TimeZone; +import junit.framework.TestCase; +import org.apidesign.apifest08.currency.Convertor; +import org.apidesign.apifest08.currency.ConvertorFactory; +import org.apidesign.apifest08.currency.ExchangeRate; +import org.apidesign.apifest08.currency.InvalidConversionException; +import org.apidesign.apifest08.currency.TimedConvertor; + +/** The exchange rates are not always the same. They are changing. However + * as in order to predict the future, one needs to understand own past. That is + * why it is important to know the exchange rate as it was at any time during + * the past. + *

+ * Today's quest is to enhance the convertor API to deal with dates. + * One shall be able to convert a currency at any date. Each currencies rate shall + * be associated with a range between two Date objects. In order + * to keep compatibility with old API that knew nothing about dates, the + * rates associated then are applicable "for eternity". Any use of existing + * convert methods that do not accept a Date argument, uses the current + * System.currentTimeMillis() as default date. + */ +public class Task4Test extends TestCase { + public Task4Test(String testName) { + super(testName); + } + + private Calendar gmtCalendar; + + @Override + protected void setUp() throws Exception { + gmtCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT")); + } + + @Override + protected void tearDown() throws Exception { + } + + // Backward compatibly enhance your existing API to support following + // usecases: + // + + /** Takes a convertor with any rates associated and creates new convertor + * that returns the same values as the old one for time between from to till. + * Otherwise it returns no results. This is just a helper method that + * shall call some real one in the API. + * + * @param old existing convertor + * @param from initial date (inclusive) + * @param till final date (exclusive) + * @return new convertor + */ + public static Convertor limitTo(Convertor old, Date from, Date till) { + final Convertor convertor; + + convertor = ConvertorFactory.getConvertor(from, till, old); + + return convertor; + } + + + public void testCompositionOfLimitedConvertors() throws Exception { + + gmtCalendar.set(2008, Calendar.OCTOBER, 1, 0, 0, 0); + Date d1 = gmtCalendar.getTime(); // 2008-10-01 0:00 GMT + gmtCalendar.set(2008, Calendar.OCTOBER, 2, 0, 0, 0); + Date d2 = gmtCalendar.getTime(); // 2008-10-02 0:00 GMT + gmtCalendar.set(2008, Calendar.OCTOBER, 3, 0, 0, 0); + Date d3 = gmtCalendar.getTime(); // 2008-10-03 0:00 GMT + + Convertor c = Task2Test.merge( + limitTo(Task1Test.createCZKtoUSD(), d1, d2), + limitTo(Task1Test.createSKKtoCZK(), d2, d3) + ); + + Date date; + BigDecimal amount; + + // convert $5 to CZK using c: + // cannot convert as no rate is applicable to current date + try + { + c.convert(Task1Test.USD, Task1Test.CZK, new BigDecimal("5.00")); + fail("test A"); + } + catch(final InvalidConversionException ex) + { + } + + // convert $8 to CZK using c: + // cannot convert as no rate is applicable to current date + try + { + c.convert(Task1Test.USD, Task1Test.CZK, new BigDecimal("8.00")); + fail("test B"); + } + catch(final InvalidConversionException ex) + { + } + + // convert 1003CZK to USD using c: + // cannot convert as no rate is applicable to current date + try + { + c.convert(Task1Test.CZK, Task1Test.USD, new BigDecimal("1003.00")); + fail("test C"); + } + catch(final InvalidConversionException ex) + { + } + + // convert 16CZK using c: + // cannot convert as no rate is applicable to current date + try + { + c.convert(Task1Test.CZK, Task1Test.USD, new BigDecimal("16.00")); + fail("test D"); + } + catch(final InvalidConversionException ex) + { + } + + // convert 500SKK to CZK using c: + // cannot convert as no rate is applicable to current date + try + { + c.convert(Task1Test.SKK, Task1Test.CZK, new BigDecimal("500.00")); + fail("test C"); + } + catch(final InvalidConversionException ex) + { + } + + // convert $5 to CZK using c at 2008-10-01 6:00 GMT: + // assertEquals("Result is 85 CZK"); + gmtCalendar.set(2008, Calendar.OCTOBER, 1, 6, 0, 0); + date = gmtCalendar.getTime(); + amount = ((TimedConvertor)c).convert(Task1Test.USD, Task1Test.CZK, new BigDecimal("5.00"), date); + assertEquals(new BigDecimal("85.00"), amount); + + // convert $8 to CZK using c at 2008-10-01 6:00 GMT: + // assertEquals("Result is 136 CZK"); + gmtCalendar.set(2008, Calendar.OCTOBER, 1, 6, 0, 0); + date = gmtCalendar.getTime(); + amount = ((TimedConvertor)c).convert(Task1Test.USD, Task1Test.CZK, new BigDecimal("8.00"), date); + assertEquals(new BigDecimal("136.00"), amount); + + // convert 1003CZK to USD using c at 2008-10-01 6:00 GMT: + // assertEquals("Result is 59 USD"); + gmtCalendar.set(2008, Calendar.OCTOBER, 1, 6, 0, 0); + date = gmtCalendar.getTime(); + amount = ((TimedConvertor)c).convert(Task1Test.CZK, Task1Test.USD, new BigDecimal("1003.00"), date); + assertEquals(new BigDecimal("59.00"), amount); + + // convert 16CZK using c at 2008-10-02 9:00 GMT: + // assertEquals("Result is 20 SKK"); + gmtCalendar.set(2008, Calendar.OCTOBER, 2, 9, 0, 0); + date = gmtCalendar.getTime(); + amount = ((TimedConvertor)c).convert(Task1Test.CZK, Task1Test.SKK, new BigDecimal("16.00"), date); + assertEquals(new BigDecimal("20.00"), amount); + + // convert 500SKK to CZK using c at 2008-10-02 9:00 GMT: + // assertEquals("Result is 400 CZK"); + gmtCalendar.set(2008, Calendar.OCTOBER, 2, 9, 0, 0); + date = gmtCalendar.getTime(); + amount = ((TimedConvertor)c).convert(Task1Test.SKK, Task1Test.CZK, new BigDecimal("500.00"), date); + assertEquals(new BigDecimal("400.00"), amount); + + // convert 500SKK to CZK using c at 2008-10-01 6:00 GMT: + // cannot convert as no rate is applicable to current date + try + { + gmtCalendar.set(2008, Calendar.OCTOBER, 1, 6, 0, 0); + date = gmtCalendar.getTime(); + ((TimedConvertor)c).convert(Task1Test.SKK, Task1Test.CZK, new BigDecimal("500.00"), date); + fail("test D"); + } + catch(final InvalidConversionException ex) + { + } + } + + /** Create convertor that understands two currencies, CZK and + * SKK. Make 100 SKK == 90 CZK. + * + * @return prepared convertor ready for converting SKK to CZK and CZK to SKK + */ + public static Convertor createSKKtoCZK2() + { + final ExchangeRate rate; + final Convertor convertor; + + rate = ExchangeRate.getExchangeRate(Task1Test.SKK, + Task1Test.CZK, + new BigDecimal("100.00"), + new BigDecimal("90.00")); + convertor = ConvertorFactory.getConvertor(rate); + + return (convertor); + } + + public void testDateConvetorWithTwoDifferentRates() throws Exception { + gmtCalendar.set(2008, Calendar.OCTOBER, 1, 0, 0, 0); + Date d1 = gmtCalendar.getTime(); // 2008-10-01 0:00 GMT + gmtCalendar.set(2008, Calendar.OCTOBER, 2, 0, 0, 0); + Date d2 = gmtCalendar.getTime(); // 2008-10-02 0:00 GMT + gmtCalendar.set(2008, Calendar.OCTOBER, 3, 0, 0, 0); + Date d3 = gmtCalendar.getTime(); // 2008-10-03 0:00 GMT + + Convertor c = Task2Test.merge( + limitTo(createSKKtoCZK2(), d1, d2), + limitTo(Task1Test.createSKKtoCZK(), d2, d3) + ); + + Date date; + BigDecimal amount; + + // convert 500SKK to CZK using c at 2008-10-02 9:00 GMT: + // assertEquals("Result is 400 CZK"); + gmtCalendar.set(2008, Calendar.OCTOBER, 2, 6, 0, 0); + date = gmtCalendar.getTime(); + amount = ((TimedConvertor)c).convert(Task1Test.SKK, Task1Test.CZK, new BigDecimal("500.00"), date); + assertEquals(new BigDecimal("400.00"), amount); + + // convert 500SKK to CZK using c at 2008-10-01 6:00 GMT: + // assertEquals("Result is 450 CZK"); + gmtCalendar.set(2008, Calendar.OCTOBER, 1, 6, 0, 0); + date = gmtCalendar.getTime(); + amount = ((TimedConvertor)c).convert(Task1Test.SKK, Task1Test.CZK, new BigDecimal("500.00"), date); + assertEquals(new BigDecimal("450.00"), amount); + } + +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution04/test/org/apidesign/apifest08/test/TestExchangeRateFinder.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution04/test/org/apidesign/apifest08/test/TestExchangeRateFinder.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,61 @@ +package org.apidesign.apifest08.test; + + +import java.math.BigDecimal; +import java.util.Currency; +import org.apidesign.apifest08.currency.ExchangeRate; +import org.apidesign.apifest08.currency.ExchangeRateFinder; + + +class TestExchangeRateFinder + implements ExchangeRateFinder +{ + private final BigDecimal min; + private final BigDecimal max; + private final BigDecimal stepUp; + private final BigDecimal stepDown; + private BigDecimal step; + private BigDecimal rate; + private boolean firstCall; + + TestExchangeRateFinder(final BigDecimal mn, + final BigDecimal mx, + final BigDecimal start, + final BigDecimal up, + final BigDecimal down) + { + min = mn; + max = mx; + rate = start; + stepUp = up; + stepDown = down; + firstCall = true; + } + + public ExchangeRate findRate(Currency a, Currency b) + { + final ExchangeRate value; + + if(rate.equals(max)) + { + step = stepDown; + } + else if(rate.equals(min)) + { + step = stepUp; + } + + value = new ExchangeRate(a, b, BigDecimal.ONE, rate); + + if(firstCall) + { + firstCall = false; + } + else + { + rate = rate.add(step); + } + + return (value); + } +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution06/build.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution06/build.xml Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,69 @@ + + + + + + Builds, tests, and runs the project. + + + diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution06/nbproject/build-impl.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution06/nbproject/build-impl.xml Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,642 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set src.dir + Must set test.src.dir + Must set build.dir + Must set dist.dir + Must set build.classes.dir + Must set dist.javadoc.dir + Must set build.test.classes.dir + Must set build.test.results.dir + Must set build.classes.excludes + Must set dist.jar + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + + + + + + java -cp "${run.classpath.with.dist.jar}" ${main.class} + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + java -jar "${dist.jar.resolved}" + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set run.class + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set debug.class + + + + + Must set fix.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + Some tests failed; see details above. + + + + + + + + + Must select some files in the IDE or set test.includes + + + + Some tests failed; see details above. + + + + + Must select one file in the IDE or set test.class + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + + + + + + + + + + + diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution06/nbproject/genfiles.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution06/nbproject/genfiles.properties Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,8 @@ +build.xml.data.CRC32=2ab820eb +build.xml.script.CRC32=58a52595 +build.xml.stylesheet.CRC32=be360661 +# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. +# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. +nbproject/build-impl.xml.data.CRC32=ff801896 +nbproject/build-impl.xml.script.CRC32=a0996c47 +nbproject/build-impl.xml.stylesheet.CRC32=e55b27f5 diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution06/nbproject/project.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution06/nbproject/project.properties Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,68 @@ +application.title=currency +application.vendor=apidesign.org +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.tab-size=8 +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.text-limit-width=80 +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.usedProfile=default +build.classes.dir=${build.dir}/classes +build.classes.excludes=**/*.java,**/*.form +# This directory is removed when the project is cleaned: +build.dir=build +build.generated.dir=${build.dir}/generated +# Only compile against the classpath explicitly listed here: +build.sysclasspath=ignore +build.test.classes.dir=${build.dir}/test/classes +build.test.results.dir=${build.dir}/test/results +debug.classpath=\ + ${run.classpath} +debug.test.classpath=\ + ${run.test.classpath} +# This directory is removed when the project is cleaned: +dist.dir=dist +dist.jar=${dist.dir}/currency.jar +dist.javadoc.dir=${dist.dir}/javadoc +excludes= +file.reference.junit-4.4.jar=../../libs/junit-4.4.jar +file.reference.src-apifest08=.. +includes=** +jar.compress=false +javac.classpath= +# Space-separated list of extra javac options +javac.compilerargs= +javac.deprecation=false +javac.source=1.5 +javac.target=1.5 +javac.test.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir}:\ + ${file.reference.junit-4.4.jar} +javadoc.additionalparam= +javadoc.author=false +javadoc.encoding= +javadoc.noindex=false +javadoc.nonavbar=false +javadoc.notree=false +javadoc.private=false +javadoc.splitindex=true +javadoc.use=true +javadoc.version=false +javadoc.windowtitle= +jnlp.codebase.type=local +jnlp.codebase.url=file:/home/jarda/src/apifest08/currency/dist +jnlp.descriptor=application +jnlp.enabled=false +jnlp.offline-allowed=false +jnlp.signed=false +meta.inf.dir=${src.dir}/META-INF +platform.active=default_platform +run.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +# Space-separated list of JVM arguments used when running the project +# (you may also define separate properties like run-sys-prop.name=value instead of -Dname=value +# or test-sys-prop.name=value to set system properties for unit tests): +run.jvmargs= +run.test.classpath=\ + ${javac.test.classpath}:\ + ${build.test.classes.dir} +src.dir=src +test.src.dir=test diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution06/nbproject/project.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution06/nbproject/project.xml Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,16 @@ + + + org.netbeans.modules.java.j2seproject + + + Currency Convertor Solution 06 + 1.6.5 + + + + + + + + + diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution06/src/org/apidesign/apifest08/currency/Amount.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution06/src/org/apidesign/apifest08/currency/Amount.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,81 @@ +package org.apidesign.apifest08.currency; + +import static org.apidesign.apifest08.currency.Assert.notNull; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.Currency; + +/** + * An amount representation. Amount is represented as composition of a value and + * a currency. + */ +public final class Amount { + + private final BigDecimal value; + private final Currency currency; + private final int scale; + private final RoundingMode roundingMode; + + public static final RoundingMode DEFAULT_ROUNDING = RoundingMode.HALF_EVEN; + + public Amount(final BigDecimal value, final Currency currency) { + notNull(value, "value"); + notNull(currency, "currency"); + this.value = value; + this.currency = currency; + this.scale = currency.getDefaultFractionDigits(); + this.roundingMode = DEFAULT_ROUNDING; + } + + public Amount(final BigDecimal value, final Currency currency, final RoundingMode roundingMode) { + notNull(value, "value"); + notNull(currency, "currency"); + notNull(roundingMode, "roundingMode"); + + this.value = value; + this.currency = currency; + this.scale = currency.getDefaultFractionDigits(); + this.roundingMode = roundingMode; + } + + public Amount(final long value, final Currency currency) { + this(BigDecimal.valueOf(value), currency); + } + + public Amount(final String value, final Currency currency) { + this(new BigDecimal(value), currency); + } + + /** + * @return the value with scale of the associated currency and rounded by + * the rounding mode. + */ + public BigDecimal getValue() { + return value.setScale(scale, roundingMode); + } + + /** + * @return the raw (no explicit scale, no explicit rounding) value + */ + public BigDecimal getRawValue() { + return value; + } + + public Currency getCurrency() { + return currency; + } + + public int getScale() { + return scale; + } + + public RoundingMode getRoundingMode() { + return roundingMode; + } + + @Override + public String toString() { + return value + ",- " + currency.toString(); + } +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution06/src/org/apidesign/apifest08/currency/Assert.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution06/src/org/apidesign/apifest08/currency/Assert.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,11 @@ +package org.apidesign.apifest08.currency; + +public final class Assert { + static void notNull(Object value, String argumentName) { + if(value == null) { + throw new IllegalArgumentException("The argument '" + argumentName + "' connot not be null"); + } + } +} + + diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution06/src/org/apidesign/apifest08/currency/ConversionException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution06/src/org/apidesign/apifest08/currency/ConversionException.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,26 @@ +package org.apidesign.apifest08.currency; + +/** + * Indicates that a desired conversion cannot be performed. + */ +public class ConversionException extends CurrencyException { + + private static final long serialVersionUID = 1L; + + public ConversionException() { + super(); + } + + public ConversionException(String message, Throwable cause) { + super(message, cause); + } + + public ConversionException(String message) { + super(message); + } + + public ConversionException(Throwable cause) { + super(cause); + } + +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution06/src/org/apidesign/apifest08/currency/Convertor.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution06/src/org/apidesign/apifest08/currency/Convertor.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,253 @@ +package org.apidesign.apifest08.currency; + +import static org.apidesign.apifest08.currency.Assert.notNull; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Currency; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.List; +import java.util.TimeZone; + +/** + * Currency covertor. + */ +public final class Convertor { + + private List convertorDelegates = new ArrayList(); + + + /** + * Create new instance of the converter for the given currencies and its rate. + * + * @param rateValue the rate between the first and the second currency + * @param currencyFirst the first currency + * @param currencySecond the second currency + */ + public Convertor(BigDecimal rateValue, Currency currencyFirst, Currency currencySecond) { + notNull(currencyFirst, "currencyFirst"); + notNull(currencySecond, "currencySecond"); + notNull(rateValue, "rateValue"); + convertorDelegates.add(new ConvertorDelegate(new StaticRateProvider(rateValue), currencyFirst, currencySecond, null, null)); + } + + /** + * Create new instance of the converter for the given currencies and its rate. + * A rate value is provided by {@link RateProvider}. + * + * @param rateProvider the rate provider + * @param currencyFirst the first currency + * @param currencySecond the second currency + */ + public Convertor(RateProvider rateProvider, Currency currencyFirst, Currency currencySecond) { + notNull(currencyFirst, "currencyFirst"); + notNull(currencySecond, "currencySecond"); + notNull(rateProvider, "rateProvider"); + convertorDelegates.add(new ConvertorDelegate(rateProvider, currencyFirst, currencySecond, null, null)); + } + + /** + * Create new instance of the convertor. The associated rate(s) is timely limited + * by a given 'from' and 'till'. + * @param convertor + * @param from + * @param till + */ + public Convertor(Convertor convertor, Date from, Date till) { + notNull(convertor, "convertor"); + notNull(from, "from"); + notNull(till, "till"); + for(ConvertorDelegate delegate: convertor.convertorDelegates) { + convertorDelegates.add(new ConvertorDelegate(delegate.rateProvider, delegate.first, delegate.second, from, till)); + } + } + + /** + * Create new instance of the convertor from the given convertors. + * @param convertors the convertors + */ + public Convertor(Convertor... convertors) { + notNull(convertors, "convertors"); + if(convertors.length == 0) { + throw new IllegalArgumentException("There must be at least one converter."); + } + + for(Convertor convertor: convertors) { + if(convertor != null) { + for(ConvertorDelegate delegate: convertor.convertorDelegates) { + convertorDelegates.add(new ConvertorDelegate(delegate.rateProvider, delegate.first, delegate.second, delegate.from, delegate.till)); + } + } + } + } + + /** + * Converts an amount value between the two currencies of this converter. The rate is taken + * for current time. + * + * @param amount an amount + * @param fromCurrency an amount currency + * @param toCurrency to a target currency + * @return a converted amount value + * + * @throws ConversionException if the conversion fails + * @throws UnsupportedConversionException if the conversion between a given currencies is not supported. + */ + public Amount convert(BigDecimal amount, Currency fromCurrency, Currency toCurrency) throws ConversionException { + return convert(amount, fromCurrency, toCurrency, new Date(System.currentTimeMillis())); + } + + /** + * Converts an amount value between the two currencies of this converter and its + * associated rate for a given time. + * + * @param amount an amount + * @param fromCurrency an amount currency + * @param toCurrency to a target currency + * @param time time + * @return a converted amount value + * + * @throws ConversionException if the conversion fails + * @throws UnsupportedConversionException if the conversion between a given currencies and time is not supported. + */ + public Amount convert(BigDecimal amount, Currency fromCurrency, Currency toCurrency, Date time) throws ConversionException { + notNull(amount, "amount"); + notNull(fromCurrency, "fromCurrency"); + notNull(toCurrency, "toCurrency"); + notNull(time, "time"); + + ConvertorDelegate appropriateDelegate = null; + //try find an appropriate delegate for conversion + for(ConvertorDelegate delegate : convertorDelegates) { + if(delegate.isConversionSupported(fromCurrency, toCurrency) && delegate.isConversionSupported(time)) { + appropriateDelegate = delegate; + } + } + if(appropriateDelegate == null) { + throw new UnsupportedConversionException(fromCurrency, toCurrency, time); + } + + return appropriateDelegate.convert(amount, fromCurrency, toCurrency); + } + + /** + * Internal delegate implements a logic for conversion between two currencies + * and vice versa. There could be time limitation for the associated rate. + * + * @see #isConversionSupported(Currency, Currency) + */ + private static class ConvertorDelegate { + + private final Currency first; + private final Currency second; + private final RateProvider rateProvider; + private final Date from; + private final Date till; + public static final BigDecimal one = new BigDecimal(1); + + + private ConvertorDelegate(RateProvider rateProvider, Currency currencyFirst, Currency currencySecond, Date from, Date till) { + this.rateProvider = rateProvider; + this.first = currencyFirst; + this.second = currencySecond; + this.from = from; + this.till = till; + } + + private Amount convert(BigDecimal amount, Currency fromCurrency, Currency toCurrency) throws ConversionException { + BigDecimal rateValue = getRateValue(fromCurrency, toCurrency); + BigDecimal result = rateValue.multiply(amount); + return new Amount(result, toCurrency); + } + + private BigDecimal getRateValue(Currency fromCurrency, Currency toCurrency) { + + BigDecimal retVal; + + if(first == fromCurrency) { + BigDecimal rateValue = rateProvider.getRate(); + if(rateValue == null) { + throw new NullPointerException("Rate cannot be null!"); + } + retVal = rateValue; + } else { + BigDecimal rateValue = rateProvider.getRate(); + if(rateValue == null) { + throw new NullPointerException("Rate cannot be null!"); + } + //reverse rate + retVal = one.divide(rateValue, 10 ,RoundingMode.HALF_UP); + } + + return retVal; + } + + /** + * @return true if the delegate is able to convert from the given currency + * to the given currency and vice versa otherwise false. + */ + private boolean isConversionSupported(Currency fromCurrency, Currency toCurrency) { + return ((fromCurrency == first || fromCurrency == second) && (toCurrency == first || toCurrency == second)); + } + + /** + * @return true if the delegate is able to convert in a given + * time. + */ + private boolean isConversionSupported(Date time) { + boolean retVal; + if(this.from != null && this.till != null) { + retVal = getDateInGMT(from).getTime() <= getDateInGMT(time).getTime() && getDateInGMT(till).getTime() >= getDateInGMT(time).getTime(); + } else { + retVal = true; //delegate is applicable "for eternity" + } + return retVal; + } + + private Date getDateInGMT(Date currentDate) { + TimeZone tz = TimeZone.getTimeZone("GMT"); + + Calendar mbCal = new GregorianCalendar(tz); + mbCal.setTimeInMillis(currentDate.getTime()); + + Calendar cal = Calendar.getInstance(); + cal.set(Calendar.YEAR, mbCal.get(Calendar.YEAR)); + cal.set(Calendar.MONTH, mbCal.get(Calendar.MONTH)); + cal.set(Calendar.DAY_OF_MONTH, mbCal.get(Calendar.DAY_OF_MONTH)); + cal.set(Calendar.HOUR_OF_DAY, mbCal.get(Calendar.HOUR_OF_DAY)); + cal.set(Calendar.MINUTE, mbCal.get(Calendar.MINUTE)); + cal.set(Calendar.SECOND, mbCal.get(Calendar.SECOND)); + cal.set(Calendar.MILLISECOND, mbCal.get(Calendar.MILLISECOND)); + + return cal.getTime(); + } + } + + /** + * A rate provider. This class represents a way how could be "static" convertor + * extended in order converts according to current rate. + */ + public static abstract class RateProvider { + + /** + * @return a rate between the from currency and the to currency associated with + * a given convertor. + */ + public abstract BigDecimal getRate(); + } + + private static class StaticRateProvider extends RateProvider{ + private final BigDecimal rateValue; + + private StaticRateProvider(BigDecimal rateValue){ + this.rateValue = rateValue; + } + + public BigDecimal getRate() { + return this.rateValue; + } + } +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution06/src/org/apidesign/apifest08/currency/CurrencyException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution06/src/org/apidesign/apifest08/currency/CurrencyException.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,25 @@ +package org.apidesign.apifest08.currency; + +/** + * Top level runtime exception for 'currency' API. + */ +public class CurrencyException extends RuntimeException{ + + private static final long serialVersionUID = 1L; + + public CurrencyException() { + super(); + } + + public CurrencyException(String message, Throwable cause) { + super(message, cause); + } + + public CurrencyException(String message) { + super(message); + } + + public CurrencyException(Throwable cause) { + super(cause); + } +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution06/src/org/apidesign/apifest08/currency/UnsupportedConversionException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution06/src/org/apidesign/apifest08/currency/UnsupportedConversionException.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,34 @@ +package org.apidesign.apifest08.currency; + +import java.util.Currency; +import java.util.Date; + +public final class UnsupportedConversionException extends ConversionException{ + + private static final long serialVersionUID = 1L; + + private Currency from; + private Currency to; + + public UnsupportedConversionException(Currency from, Currency to) { + super("Conversion from the currency " + from + " to the currency " + to + " or vice versa in not supported."); + this.from = from; + this.to = to; + } + + public UnsupportedConversionException(Currency from, Currency to, Date time) { + super("Conversion from the currency " + from + " to the currency " + to + " or vice versa in not supported for time " + time ); + this.from = from; + this.to = to; + } + + public Currency getFrom() { + return from; + } + + public Currency getTo() { + return to; + } + + +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution06/test/org/apidesign/apifest08/test/Currencies.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution06/test/org/apidesign/apifest08/test/Currencies.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,9 @@ +package org.apidesign.apifest08.test; + +import java.util.Currency; + +public class Currencies { + public static final Currency CZK = Currency.getInstance("CZK"); + public static final Currency SKK = Currency.getInstance("SKK"); + public static final Currency USD = Currency.getInstance("USD"); +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution06/test/org/apidesign/apifest08/test/Task1Test.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution06/test/org/apidesign/apifest08/test/Task1Test.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,136 @@ +package org.apidesign.apifest08.test; + +import static org.apidesign.apifest08.test.Currencies.CZK; +import static org.apidesign.apifest08.test.Currencies.SKK; +import static org.apidesign.apifest08.test.Currencies.USD; + +import java.math.BigDecimal; + +import junit.framework.TestCase; + +import org.apidesign.apifest08.currency.Amount; +import org.apidesign.apifest08.currency.ConversionException; +import org.apidesign.apifest08.currency.Convertor; +import org.apidesign.apifest08.currency.UnsupportedConversionException; + +/** Finish the Convertor API, and then write bodies of methods inside + * of this class to match the given tasks. To fullfil your task, use the + * API define in the org.apidesign.apifest08.currency package. + * Do not you reflection, or other hacks as your code + * shall run without any runtime permissions. + */ +public class Task1Test extends TestCase { + public Task1Test(String testName) { + super(testName); + } + + @Override + protected void setUp() throws Exception { + } + + @Override + protected void tearDown() throws Exception { + } + + /** Create convertor that understands two currencies, CZK and + * USD. Make 1 USD == 17 CZK. + * + * Creation of the convertor shall not require subclassing of any class + * or interface on the client side. + * + * @return prepared convertor ready for converting USD to CZK and CZK to USD + */ + public static Convertor createCZKtoUSD() { + return new Convertor(new BigDecimal(17), USD, CZK); + } + + /** Create convertor that understands two currencies, CZK and + * SKK. Make 100 SKK == 80 CZK. + * + * Creation of the convertor shall not require subclassing of any class + * or interface on the client side. + * + * @return prepared convertor ready for converting SKK to CZK and CZK to SKK + */ + public static Convertor createSKKtoCZK() { + return new Convertor(new BigDecimal("0.8"), SKK, CZK); + } + + /** Use the convertor from createCZKtoUSD method and do few conversions + * with it. + */ + public void testCurrencyCZKUSD() throws Exception { + Convertor c = createCZKtoUSD(); + // convert $5 to CZK using c: + Amount result = c.convert(new BigDecimal(5), USD, CZK); + assertEquals("Result is 85 CZK", 85, result.getValue().intValue()); + + // convert $8 to CZK + result = c.convert(new BigDecimal(8), USD, CZK); + assertEquals("Result is 136 CZK", 136, result.getValue().intValue()); + + // convert 1003CZK to USD + result = c.convert(new BigDecimal(1003), CZK, USD); + assertEquals("Result is 59 USD", 59, result.getValue().intValue()); + } + + /** Use the convertor from createSKKtoCZK method and do few conversions + * with it. + */ + public void testCurrencySKKCZK() throws Exception { + Convertor c = createSKKtoCZK(); + // convert 16CZK using c: + Amount result = c.convert(new BigDecimal(16), CZK, SKK); + assertEquals("Result is 20 SKK", 20, result.getValue().intValue()); + + // convert 500SKK to CZK + result = c.convert(new BigDecimal(500), SKK, CZK); + assertEquals("Result is 400 CZK", 400, result.getValue().intValue()); + } + + + /** + * Verify that the CZK to USD convertor knows nothing about SKK. + */ + public void testCannotConvertToSKKwithCZKUSDConvertor() throws Exception { + Convertor c = createCZKtoUSD(); + // convert $5 to SKK, the API shall say this is not possible + try { + c.convert(new BigDecimal(5), USD, SKK); + fail("convert $5 to SKK, the API shall say this is not possible"); + } catch (ConversionException e) { + //expected + } + + // convert 500 SKK to CZK, the API shall say this is not possible + + try { + c.convert(new BigDecimal("500"), SKK, CZK); + fail("convert 500 SKK to CZK, the API shall say this is not possible"); + } catch (ConversionException e) { + //expected + } + } + + /** + * Verify that the CZK to SKK convertor knows nothing about USD. + */ + public void testCannotConvertToSKKwithCZKSKKConvertor() throws Exception { + Convertor c = createSKKtoCZK(); + // convert $5 to SKK, the API shall say this is not possible + try { + c.convert(new BigDecimal(5), USD, SKK); + fail("convert $5 to SKK, the API shall say this is not possible"); + } catch(ConversionException e) { + //expected + } + + try { + c.convert(new BigDecimal(500), CZK, USD); + fail("convert 500 CZK to USD, the API shall say this is not possible"); + } catch(ConversionException e) { + //expected + } + } +} + diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution06/test/org/apidesign/apifest08/test/Task2Test.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution06/test/org/apidesign/apifest08/test/Task2Test.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,117 @@ +package org.apidesign.apifest08.test; + +import static org.apidesign.apifest08.test.Currencies.CZK; +import static org.apidesign.apifest08.test.Currencies.USD; +import static org.apidesign.apifest08.test.Currencies.SKK; + +import java.math.BigDecimal; + +import junit.framework.TestCase; +import org.apidesign.apifest08.currency.Convertor; +import org.apidesign.apifest08.test.Task1Test; + +/** There are many currencies around the world and many banks manipulate + * with more than one or two at the same time. As banks are usually the + * best paying clients, which is true even in case of your Convertor API, + * it is reasonable to listen to their requests. + *

+ * The quest for today is to enhance your existing convertor API to hold + * information about many currencies and allow conversions between any of them. + * Also, as conversion rates for diferent currencies usually arise from various + * bank departments, there is another important need. There is a need to + * compose two convertors into one by merging all the information about + * currencies they know about. + */ +public class Task2Test extends TestCase { + public Task2Test(String testName) { + super(testName); + } + + @Override + protected void setUp() throws Exception { + } + + @Override + protected void tearDown() throws Exception { + } + + // As in Task1Test, keep in mind, that there are three parts + // of the whole system: + // 1. there is someone who knows the current exchange rate + // 2. there is someone who wants to do the conversion + // 3. there is the API between 1. and 2. which allows them to communicate + // + // Please backward compatibly enhance your existing API to support following + // usecases: + // + + /** Create convertor that understands two currencies, CZK and + * SKK. Make 100 SKK == 75 CZK. This is method for the group of users that + * knows the exchange rate, and needs to use the API to create objects + * with the exchange rate. Anyone shall be ready to call this method without + * any other method being called previously. The API itself shall know + * nothing about any rates, before this method is called. + */ + public static Convertor createTripleConvertor() { + // Rates: 1USD = 15CZK + // Rates: 1USD = 20SKK + // Rates: 75CZK = 100SKK + Convertor usdCzk = new Convertor(new BigDecimal(15), USD, CZK); + Convertor usdSkk = new Convertor(new BigDecimal(20), USD, SKK); + Convertor skkCzk = new Convertor(new BigDecimal("0.75"), SKK, CZK); + return new Convertor(new Convertor[]{usdCzk, usdSkk, skkCzk}); + } + + /** Define convertor that understands three currencies. Use it. + */ + public void testConvertorForUSDandCZKandSKK() throws Exception { + Convertor c = createTripleConvertor(); + + // convert $5 to CZK using c: + assertEquals("Result is 75 CZK", 75 ,c.convert(new BigDecimal(5), USD, CZK).getValue().intValue()); + + // convert $5 to SKK using c: + assertEquals("Result is 100 SKK", 100, c.convert(new BigDecimal(5), USD, SKK).getValue().intValue()); + + // convert 200SKK to CZK using c: + assertEquals("Result is 150 CZK", 150, c.convert(new BigDecimal(200), SKK, CZK).getValue().intValue()); + + // convert 200SKK to USK using c: + assertEquals("Result is 10 USD", 10, c.convert(new BigDecimal(200), SKK, USD).getValue().intValue()); + } + + /** Merge all currency rates of convertor 1 with convertor 2. + * Implement this using your API, preferably this method just delegates + * into some API method which does the actual work, without requiring + * API clients to code anything complex. + */ + public static Convertor merge(Convertor one, Convertor two) { + return new Convertor(new Convertor[]{one, two}); + } + + /** Join the convertors from previous task, Task1Test and show that it + * can be used to do reasonable conversions. + */ + public void testConvertorComposition() throws Exception { + Convertor c = merge( + Task1Test.createCZKtoUSD(), + Task1Test.createSKKtoCZK() + ); + + // convert $5 to CZK using c: + assertEquals("Result is 85 CZK", 85, c.convert(new BigDecimal(5), USD, CZK).getValue().intValue()); + + // convert $8 to CZK using c: + assertEquals("Result is 136 CZK", 136, c.convert(new BigDecimal(8), USD, CZK).getValue().intValue()); + + // convert 1003CZK to USD using c: + assertEquals("Result is 59 USD", 59, c.convert(new BigDecimal(1003), CZK, USD).getValue().intValue()); + + // convert 16CZK using c: + assertEquals("Result is 20 SKK", 20, c.convert(new BigDecimal(16), CZK, SKK).getValue().intValue()); + + // convert 500SKK to CZK using c: + assertEquals("Result is 400 CZK", 400, c.convert(new BigDecimal(500), SKK, CZK).getValue().intValue()); + + } +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution06/test/org/apidesign/apifest08/test/Task3Test.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution06/test/org/apidesign/apifest08/test/Task3Test.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,111 @@ +package org.apidesign.apifest08.test; + +import java.math.BigDecimal; +import java.math.RoundingMode; + +import junit.framework.TestCase; +import org.apidesign.apifest08.currency.Convertor; +import static org.apidesign.apifest08.test.Currencies.*; + +/** The exchange rates are not always the same. They are changing. Day by day, + * hour by hour, minute by minute. For every bank it is important to always + * have the actual exchange rate available in the system. That is why let's + * create a pluggable convertor that will always have up to date value of its + * exchange rate. + *

+ * The quest for today is to allow 3rd party developer to write a convertor + * that adjusts its exchange rate everytime it is queried. This convertor is + * written by independent vendor, the vendor knows only your Convertor API, + * he does not know how the whole system looks and how the convertor is supposed + * to be used. + */ +public class Task3Test extends TestCase { + public Task3Test(String testName) { + super(testName); + } + + @Override + protected void setUp() throws Exception { + } + + @Override + protected void tearDown() throws Exception { + } + + // Backward compatibly enhance your existing API to support following + // usecases: + // + + + /** Without knowing anything about the surrounding system, write an + * implementation of convertor that will return different rates everytime + * it is queried. Convert USD to CZK and vice versa. Start with the rate of + * 1USD = 16CZK and adjust it in favor of CZK by 0.01 CZK with every query. + * As soon as you reach 1USD = 15CZK adjust it by 0.01 CZK in favor of USD + * until you reach 1USD = 16CZK + * + * @return new instance of "online" USD and CZK convertor starting with rate 1USD = 16CZK + */ + public static Convertor createOnlineCZKUSDConvertor() { + Convertor.RateProvider rateProvider = new Convertor.RateProvider() { + private BigDecimal seed = new BigDecimal("16.01").setScale(2); + + @Override + public BigDecimal getRate() { + if(seed.equals(new BigDecimal("15").setScale(2))) { + seed = seed.add(new BigDecimal("0.01")).setScale(2); + } else { + seed = seed.subtract(new BigDecimal("0.01")).setScale(2); + } + return seed; + } + + }; + + // initial rate: 1USD = 16CZK + // 2nd query 1USD = 15.99CZK + // 3rd query 1USD = 15.98CZK + // until 1USD = 15.00CZK + // then 1USD = 15.01CZK + // then 1USD = 15.02CZK + // and so on and on up to 1USD = 16CZK + // and then another round to 15, etc. + return new Convertor(rateProvider, USD, CZK); + } + + public void testFewQueriesForOnlineConvertor() { + Convertor c = createOnlineCZKUSDConvertor(); + doFewQueriesForOnlineConvertor(c); + } + + static void doFewQueriesForOnlineConvertor(Convertor c) { + // convert $5 to CZK using c: + assertEquals("Result is 80 CZK",80 ,c.convert(new BigDecimal(5), USD, CZK).getValue().intValue()); + + // convert $8 to CZK using c: + assertEquals("Result is 127.92 CZK", 127.92d , c.convert(new BigDecimal(8), USD, CZK).getValue().doubleValue()); + + // convert $1 to CZK using c: + assertEquals("Result is 15.98 CZK", 15.98d, c.convert(new BigDecimal(1), USD, CZK).getValue().doubleValue()); + + // convert 15.97CZK to USD using c: + assertEquals("Result is 1$", 1, c.convert(new BigDecimal("15.97").setScale(2), CZK, USD).getValue().intValue()); + } + + /** Join the convertors and show they behave sane. + */ + public void testOnlineConvertorComposition() throws Exception { + Convertor c = Task2Test.merge( + createOnlineCZKUSDConvertor(), + Task1Test.createSKKtoCZK() + ); + + // convert 16CZK to SKK using c: + assertEquals("Result is 20 SKK", 20, c.convert(new BigDecimal(16), CZK, SKK).getValue().intValue()); + + // convert 500SKK to CZK using c: + assertEquals("Result is 400 CZK", 400, c.convert(new BigDecimal(500), SKK, CZK).getValue().intValue()); + + doFewQueriesForOnlineConvertor(c); + } +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution06/test/org/apidesign/apifest08/test/Task4Test.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution06/test/org/apidesign/apifest08/test/Task4Test.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,161 @@ +package org.apidesign.apifest08.test; + +import java.math.BigDecimal; +import java.text.SimpleDateFormat; +import java.util.Date; +import junit.framework.TestCase; +import org.apidesign.apifest08.currency.Convertor; +import org.apidesign.apifest08.currency.UnsupportedConversionException; + +import static org.apidesign.apifest08.test.Currencies.*; + +/** The exchange rates are not always the same. They are changing. However + * as in order to predict the future, one needs to understand own past. That is + * why it is important to know the exchange rate as it was at any time during + * the past. + *

+ * Today's quest is to enhance the convertor API to deal with dates. + * One shall be able to convert a currency at any date. Each currencies rate shall + * be associated with a range between two Date objects. In order + * to keep compatibility with old API that knew nothing about dates, the + * rates associated then are applicable "for eternity". Any use of existing + * convert methods that do not accept a Date argument, uses the current + * System.currentTimeMillis() as default date. + */ +public class Task4Test extends TestCase { + public Task4Test(String testName) { + super(testName); + } + + @Override + protected void setUp() throws Exception { + } + + @Override + protected void tearDown() throws Exception { + } + + // Backward compatibly enhance your existing API to support following + // usecases: + // + + /** Takes a convertor with any rates associated and creates new convertor + * that returns the same values as the old one for time between from to till. + * Otherwise it returns no results. This is just a helper method that + * shall call some real one in the API. + * + * @param old existing convertor + * @param from initial date (inclusive) + * @param till final date (exclusive) + * @return new convertor + */ + public static Convertor limitTo(Convertor old, Date from, Date till) { + return new Convertor(old, from, till); + } + + + public void testCompositionOfLimitedConvertors() throws Exception { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm zzzz"); + + Date d1 = df.parse("2008-10-01 0:00 GMT"); + Date d2 = df.parse("2008-10-02 0:00 GMT"); + Date d3 = df.parse("2008-10-03 0:00 GMT"); + + Convertor c = Task2Test.merge( + limitTo(Task1Test.createCZKtoUSD(), d1, d2), + limitTo(Task1Test.createSKKtoCZK(), d2, d3) + ); + + // convert $5 to CZK using c: + try { + c.convert(new BigDecimal(5), USD , CZK); + fail("cannot convert as no rate is applicable to current date"); + } catch(UnsupportedConversionException e) { + //expected + } + + // convert $8 to CZK using c: + try { + c.convert(new BigDecimal(8), USD , CZK); + fail("cannot convert as no rate is applicable to current date"); + } catch(UnsupportedConversionException e) { + //expected + } + + // convert 1003CZK to USD using c: + try { + c.convert(new BigDecimal(1003), CZK, USD); + fail("cannot convert as no rate is applicable to current date"); + } catch(UnsupportedConversionException e) { + //expected + } + + // convert 16CZK using c: + try { + c.convert(new BigDecimal(16), CZK, USD); + fail("cannot convert as no rate is applicable to current date"); + } catch(UnsupportedConversionException e) { + //expected + } + + // convert 500SKK to CZK using c: + try { + c.convert(new BigDecimal(500), SKK, CZK); + fail("cannot convert as no rate is applicable to current date"); + } catch(UnsupportedConversionException e) { + //expected + } + + // convert $5 to CZK using c at 2008-10-01 6:00 GMT: + assertEquals("Result is 85 CZK", 85, c.convert(new BigDecimal(5), USD, CZK, df.parse("2008-10-01 6:00 GMT")).getValue().intValue()); + + // convert $8 to CZK using c at 2008-10-01 6:00 GMT: + assertEquals("Result is 136 CZK", 136, c.convert(new BigDecimal(8), USD, CZK, df.parse("2008-10-01 6:00 GMT")).getValue().intValue()); + + // convert 1003CZK to USD using c at 2008-10-01 6:00 GMT: + assertEquals("Result is 59 USD", 59, c.convert(new BigDecimal(1003), CZK, USD, df.parse("2008-10-01 6:00 GMT")).getValue().intValue()); + + // convert 16CZK using c at 2008-10-02 9:00 GMT: + assertEquals("Result is 20 SKK", 20, c.convert(new BigDecimal(16), CZK, SKK, df.parse("2008-10-02 9:00 GMT")).getValue().intValue()); + + // convert 500SKK to CZK using c at 2008-10-02 9:00 GMT: + assertEquals("Result is 400 CZK", 400, c.convert(new BigDecimal(500), SKK, CZK, df.parse("2008-10-02 9:00 GMT")).getValue().intValue()); + + // convert 500SKK to CZK using c at 2008-10-01 6:00 GMT: + try { + c.convert(new BigDecimal(500), SKK, CZK, df.parse("2008-10-01 6:00 GMT")); + fail("cannot convert as no rate is applicable to current date"); + } catch(UnsupportedConversionException e) { + //expected + } + } + + /** Create convertor that understands two currencies, CZK and + * SKK. Make 100 SKK == 90 CZK. + * + * @return prepared convertor ready for converting SKK to CZK and CZK to SKK + */ + public static Convertor createSKKtoCZK2() { + return new Convertor(new BigDecimal("0.9"), SKK, CZK); + } + + public void testDateConvetorWithTwoDifferentRates() throws Exception { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm zzzz"); + + Date d1 = df.parse("2008-10-01 0:00 GMT"); + Date d2 = df.parse("2008-10-02 0:00 GMT"); + Date d3 = df.parse("2008-10-03 0:00 GMT"); + + Convertor c = Task2Test.merge( + limitTo(createSKKtoCZK2(), d1, d2), + limitTo(Task1Test.createSKKtoCZK(), d2, d3) + ); + + // convert 500SKK to CZK using c at 2008-10-02 9:00 GMT: + assertEquals("Result is 400 CZK", 400, c.convert(new BigDecimal(500), SKK, CZK, df.parse("2008-10-02 9:00 GMT")).getValue().intValue()); + + // convert 500SKK to CZK using c at 2008-10-01 6:00 GMT: + assertEquals("Result is 450 CZK", 450, c.convert(new BigDecimal(500), SKK, CZK, df.parse("2008-10-01 6:00 GMT")).getValue().intValue()); + } + +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution07/build.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution07/build.xml Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,69 @@ + + + + + + Builds, tests, and runs the project. + + + diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution07/nbproject/build-impl.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution07/nbproject/build-impl.xml Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,642 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set src.dir + Must set test.src.dir + Must set build.dir + Must set dist.dir + Must set build.classes.dir + Must set dist.javadoc.dir + Must set build.test.classes.dir + Must set build.test.results.dir + Must set build.classes.excludes + Must set dist.jar + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + + + + + + java -cp "${run.classpath.with.dist.jar}" ${main.class} + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + java -jar "${dist.jar.resolved}" + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set run.class + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set debug.class + + + + + Must set fix.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + Some tests failed; see details above. + + + + + + + + + Must select some files in the IDE or set test.includes + + + + Some tests failed; see details above. + + + + + Must select one file in the IDE or set test.class + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + + + + + + + + + + + diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution07/nbproject/genfiles.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution07/nbproject/genfiles.properties Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,8 @@ +build.xml.data.CRC32=2ab820eb +build.xml.script.CRC32=58a52595 +build.xml.stylesheet.CRC32=be360661 +# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. +# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. +nbproject/build-impl.xml.data.CRC32=979fc7ba +nbproject/build-impl.xml.script.CRC32=92452d37 +nbproject/build-impl.xml.stylesheet.CRC32=e55b27f5 diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution07/nbproject/project.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution07/nbproject/project.properties Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,68 @@ +application.title=currency +application.vendor=apidesign.org +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.tab-size=8 +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.text-limit-width=80 +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.usedProfile=default +build.classes.dir=${build.dir}/classes +build.classes.excludes=**/*.java,**/*.form +# This directory is removed when the project is cleaned: +build.dir=build +build.generated.dir=${build.dir}/generated +# Only compile against the classpath explicitly listed here: +build.sysclasspath=ignore +build.test.classes.dir=${build.dir}/test/classes +build.test.results.dir=${build.dir}/test/results +debug.classpath=\ + ${run.classpath} +debug.test.classpath=\ + ${run.test.classpath} +# This directory is removed when the project is cleaned: +dist.dir=dist +dist.jar=${dist.dir}/currency.jar +dist.javadoc.dir=${dist.dir}/javadoc +excludes= +file.reference.junit-4.4.jar=../../libs/junit-4.4.jar +file.reference.src-apifest08=.. +includes=** +jar.compress=false +javac.classpath= +# Space-separated list of extra javac options +javac.compilerargs= +javac.deprecation=false +javac.source=1.5 +javac.target=1.5 +javac.test.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir}:\ + ${file.reference.junit-4.4.jar} +javadoc.additionalparam= +javadoc.author=false +javadoc.encoding= +javadoc.noindex=false +javadoc.nonavbar=false +javadoc.notree=false +javadoc.private=false +javadoc.splitindex=true +javadoc.use=true +javadoc.version=false +javadoc.windowtitle= +jnlp.codebase.type=local +jnlp.codebase.url=file:/home/jarda/src/apifest08/currency/dist +jnlp.descriptor=application +jnlp.enabled=false +jnlp.offline-allowed=false +jnlp.signed=false +meta.inf.dir=${src.dir}/META-INF +platform.active=default_platform +run.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +# Space-separated list of JVM arguments used when running the project +# (you may also define separate properties like run-sys-prop.name=value instead of -Dname=value +# or test-sys-prop.name=value to set system properties for unit tests): +run.jvmargs= +run.test.classpath=\ + ${javac.test.classpath}:\ + ${build.test.classes.dir} +src.dir=src +test.src.dir=test diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution07/nbproject/project.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution07/nbproject/project.xml Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,16 @@ + + + org.netbeans.modules.java.j2seproject + + + Currency Convertor Solution 07 + 1.6.5 + + + + + + + + + diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution07/src/org/apidesign/apifest08/currency/ConversionRate.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution07/src/org/apidesign/apifest08/currency/ConversionRate.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,91 @@ +package org.apidesign.apifest08.currency; + +import java.math.BigDecimal; +import java.math.RoundingMode; + +/** + * A rate of conversion from one currency to another. + * @author jdvorak + */ +public class ConversionRate { + + private final MonetaryAmount srcUnitAmount; + private final MonetaryAmount tgtUnitAmount; + private final int tgtScale; + private final RoundingMode roundingMode; + + /** + * A new conversion rate that gives tgtUnitAmount per every srcUnitAmount. + * @param srcUnitAmount the amount of source currency + * @param tgtUnitAmount the corresponding amount of target currency + * @param tgtScale the scale of the target amounts + * @param roundingMode the rounding mode to use when producing the target amounts + */ + public ConversionRate( final MonetaryAmount srcUnitAmount, final MonetaryAmount tgtUnitAmount, final int targetScale, final RoundingMode roundingMode ) { + this.srcUnitAmount = srcUnitAmount; + this.tgtUnitAmount = tgtUnitAmount; + this.tgtScale = targetScale; + this.roundingMode = roundingMode; + } + + /** + * A new conversion rate that gives tgtUnitAmount per every srcUnitAmount, default number of fraction digits and the given rounding mode. + * @param srcUnitAmount the amount of source currency + * @param tgtUnitAmount the corresponding amount of target currency + * @param roundingMode the rounding mode to use + */ + public ConversionRate( final MonetaryAmount srcUnitAmount, final MonetaryAmount tgtUnitAmount, final RoundingMode roundingMode ) { + this( srcUnitAmount, tgtUnitAmount, tgtUnitAmount.getCurrency().getDefaultFractionDigits(), roundingMode ); + } + + /** + * A new conversion rate that gives tgtUnitAmount per every srcUnitAmount, default number of fraction digits and {@link RoundingMode#HALF_EVEN}. + * @param srcUnitAmount the amount of source currency + * @param tgtUnitAmount the corresponding amount of target currency + */ + public ConversionRate( final MonetaryAmount srcUnitAmount, final MonetaryAmount tgtUnitAmount ) { + this( srcUnitAmount, tgtUnitAmount, RoundingMode.HALF_EVEN ); + } + + public RoundingMode getRoundingMode() { + return roundingMode; + } + + public MonetaryAmount getSrcUnitAmount() { + return srcUnitAmount; + } + + public int getTgtScale() { + return tgtScale; + } + + public MonetaryAmount getTgtUnitAmount() { + return tgtUnitAmount; + } + + /** + * Multiplies the given amount with the given rate. + * @param srcAmount + * @return + */ + public BigDecimal convert( final BigDecimal srcAmount ) { + return srcAmount + .multiply( tgtUnitAmount.getAmount() ) + .divide( srcUnitAmount.getAmount(), tgtScale, roundingMode ); + } + + /** + * Creates a monetary amount that corresponds to the given source amount multiplied by the rate. + * @param srcAmount the source amount + * @return the monetary amount in the target currency + * @throws IllegalArgumentException if the currency of srcAmount is not equal to the source currency of this rate + */ + public MonetaryAmount convert( final MonetaryAmount srcAmount ) { + if ( srcUnitAmount.getCurrency().equals( srcAmount.getCurrency() ) ) { + return new MonetaryAmount( convert( srcAmount.getAmount() ), tgtUnitAmount.getCurrency() ); + } else { + throw new IllegalArgumentException( "This rate converts from " + srcUnitAmount.getCurrency() + ", but a conversion from " + srcAmount.getCurrency() + " is attempted" ); + } + } + +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution07/src/org/apidesign/apifest08/currency/Convertor.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution07/src/org/apidesign/apifest08/currency/Convertor.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,109 @@ +package org.apidesign.apifest08.currency; + +import java.util.Currency; + +/** This is the skeleton class for your API. You need to make it public, so + * it is accessible to your client code (currently in Task1Test.java) file. + *

+ * Feel free to create additional classes or rename this one, just keep all + * the API and its implementation in this package. Do not spread it outside + * to other packages. + */ +public interface Convertor { + + /** + * Converts by taking a request and producing a response. + * If a convertor finds it cannot perform the requested conversion, + * it should return a non-null {@link ConversionResult} that has null {@link ConversionResult#getNetAmount()}. + * A convertor must not convert to a different currency than the one specified in the request. + *

+ * When the need comes to extend the semantics, one subclasses the ConversionRequest and/or ConversionResult classes. + *

+ * This method can be called as many times as you like. + * A {@link Convertor} shall be considered immutable wrt calls to {@link #convert(org.apidesign.apifest08.currency.Convertor.ConversionRequest). + * This method of a single {@link Convertor} can be called from many threads concurrently. + * @param req the conversion request; mustn't be null + * @return the result of carrying out the conversion request; never null + * @throws IllegalRequestSubtypeException when the particular implementation cannot handle a specific ConversionRequest type + */ + public ConversionResult convert( final ConversionRequest req ) throws IllegalRequestSubtypeException; + + /** + * The request for converting a monetary amout into another currency. + * Immutable. + */ + public class ConversionRequest { + + private final MonetaryAmount srcAmount; + private final Currency tgtCurrency; + + /** + * A request to convert srcAmount into tgtCurrency. + * @param srcAmount the source amount; must not be null + * @param tgtCurrency the currency we want it in afterwards; must not be null + */ + public ConversionRequest( final MonetaryAmount srcAmount, final Currency tgtCurrency ) { + this.srcAmount = srcAmount; + this.tgtCurrency = tgtCurrency; + if ( srcAmount == null ) { + throw new NullPointerException( "The source amount" ); + } + if ( tgtCurrency == null ) { + throw new NullPointerException( "The target currency" ); + } + if ( srcAmount.getCurrency().equals( tgtCurrency ) ) { + throw new IllegalArgumentException( "Cannot request conversion from " + srcAmount.getCurrency() + " to " + tgtCurrency ); + } + } + + /** + * The source amount. + */ + public MonetaryAmount getSrcAmount() { + return srcAmount; + } + + /** + * The target currency. + */ + public Currency getTgtCurrency() { + return tgtCurrency; + } + + } + + /** + * The result of converting a monetary amount into another currency. + * For now it records just the net amount one recieves from the conversion. + * Immutable. + *

+ * Extension note: + * Other items can be added further down the road, as the need for them arises. + * These items might provide info on other aspects of the conversion, + * such as the fee or a reason why the conversion might not be admissible. + */ + public class ConversionResult { + + private final MonetaryAmount netAmount; + + /** + * A new conversion result. + * @param netAmount the amount one recieves from the conversion; + * null means the conversion was not admissible + */ + public ConversionResult( final MonetaryAmount netAmount ) { + this.netAmount = netAmount; + } + + /** + * The amount one recieves from the conversion. + * If null, the conversion is not admissible. + * @return the amount + */ + public MonetaryAmount getNetAmount() { + return netAmount; + } + + } + +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution07/src/org/apidesign/apifest08/currency/DelegatingConvertor.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution07/src/org/apidesign/apifest08/currency/DelegatingConvertor.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,28 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package org.apidesign.apifest08.currency; + +/** + * + * @author jdvorak + */ +public class DelegatingConvertor implements Convertor { + + private final Convertor underlyingConvertor; + + public DelegatingConvertor( final Convertor underlyingConvertor ) { + this.underlyingConvertor = underlyingConvertor; + } + + protected Convertor getUnderlyingConvertor() { + return underlyingConvertor; + } + + public ConversionResult convert( final ConversionRequest req ) { + return underlyingConvertor.convert( req ); + } + +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution07/src/org/apidesign/apifest08/currency/IllegalRequestSubtypeException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution07/src/org/apidesign/apifest08/currency/IllegalRequestSubtypeException.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,30 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package org.apidesign.apifest08.currency; + +/** + * Rised when a {@link Convertor} implementation cannot handle a particular subtype of {@link Convertor.ConversionRequest}. + * @author jdvorak + */ +public class IllegalRequestSubtypeException extends IllegalArgumentException { + + public IllegalRequestSubtypeException() { + super(); + } + + public IllegalRequestSubtypeException( final String msg ) { + super( msg ); + } + + public IllegalRequestSubtypeException( final Throwable cause ) { + super( cause ); + } + + public IllegalRequestSubtypeException( final String msg, final Throwable cause ) { + super( msg, cause ); + } + +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution07/src/org/apidesign/apifest08/currency/MonetaryAmount.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution07/src/org/apidesign/apifest08/currency/MonetaryAmount.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,89 @@ +package org.apidesign.apifest08.currency; + +import java.math.BigDecimal; +import java.util.Currency; + +/** + * An amount of a currency. + * Immutable. + * @author jdvorak + */ +public class MonetaryAmount { + + private final BigDecimal amount; + private final Currency currency; + + /** + * A new amount. + * @param amount the quantity of the currency; must not be null + * @param currency the currency; must not be null + */ + public MonetaryAmount( final BigDecimal amount, final Currency currency ) { + this.amount = amount; + this.currency = currency; + if ( amount == null ) { + throw new NullPointerException( "The amount" ); + } + if ( currency == null ) { + throw new NullPointerException( "The currency" ); + } + } + + /** + * A new amount. + * @param amount the quantity of the currency; must not be null + * @param currency the currency; must not be null + */ + public MonetaryAmount( final double amount, final Currency currency ) { + this( new BigDecimal( amount ), currency ); + } + + /** + * The amount. + * @return the amount + */ + public BigDecimal getAmount() { + return amount; + } + + /** + * The currency. + * @return the currency + */ + public Currency getCurrency() { + return currency; + } + + /** + * The string representation of the monetary amount. + * @return the amount, a non-breakable space, the currency + */ + @Override + public String toString() { + return amount.toPlainString() + "\u00a0" + currency.toString(); + } + + /** + * Two monetary amounts are equal to each other iff they have equal amounts of equal currencies. + * @param other the other object + * @return equality + */ + @Override + public boolean equals( final Object other ) { + if ( other instanceof MonetaryAmount ) { + final MonetaryAmount otherMonetaryAmount = (MonetaryAmount) other; + return getAmount().equals( otherMonetaryAmount.getAmount() ) && getCurrency().equals( otherMonetaryAmount.getCurrency() ); + } + return false; + } + + /** + * The hash code combines the hash codes of the amount and of the currency. + * @return hash code + */ + @Override + public int hashCode() { + return amount.hashCode() * 37 + currency.hashCode(); + } + +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution07/src/org/apidesign/apifest08/currency/TableConvertor.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution07/src/org/apidesign/apifest08/currency/TableConvertor.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,71 @@ +package org.apidesign.apifest08.currency; + +import java.util.Currency; +import java.util.HashMap; +import java.util.Map; + +/** + * A {@link Convertor} that works from a pre-set conversion table. + * First use {@link #putIntoTable(org.apidesign.apifest08.currency.ConversionRate)} to set the conversion table. + * Then invoke the {@link #convert(org.apidesign.apifest08.currency.Convertor.ConversionRequest)} method as many times as you wish. + * @author jdvorak + */ +public class TableConvertor implements Convertor { + + private final Map> conversionTable = new HashMap>(); + + public TableConvertor() { + } + + /** + * Puts a rate into the table. + * @param rate + */ + public void putIntoTable( final ConversionRate rate ) { + final Currency srcCurrency = rate.getSrcUnitAmount().getCurrency(); + final Currency tgtCurrency = rate.getTgtUnitAmount().getCurrency(); + synchronized ( conversionTable ) { + Map targetTable = conversionTable.get( srcCurrency ); + if ( targetTable == null ) { + targetTable = new HashMap(); + conversionTable.put( srcCurrency, targetTable ); + } + targetTable.put( tgtCurrency, rate ); + } + } + + /** + * Carries out the conversion. + * If the table does not contain a conversion from the source currency to the target one, + * a {@link ConversionResult} is returned that has null netAmount. + * This implementation works with any {@link ConversionRequest}, it won't throw {@link IllegalRequestSubtypeException}. + * @param req the conversion request + * @return the conversion result + */ + public ConversionResult convert( final ConversionRequest req ) { + final Currency srcCurrency = req.getSrcAmount().getCurrency(); + final Currency tgtCurrency = req.getTgtCurrency(); + final ConversionRate rate = findConversionRate( srcCurrency, tgtCurrency ); + if ( rate != null ) { + final MonetaryAmount tgtAmount = rate.convert( req.getSrcAmount() ); + return new ConversionResult( tgtAmount ); + } else { + return new ConversionResult( null ); // did not find the pair of currencies in the table + } + } + + /** + * Looks up the conversion between the given currencies in the table. + * @param srcCurrency the source currency + * @param tgtCurrency the target currency + * @return the conversion rate; null means no conversion between the currencies was found in the table + */ + protected ConversionRate findConversionRate( final Currency srcCurrency, final Currency tgtCurrency ) { + synchronized ( conversionTable ) { + final Map targetTable = conversionTable.get(srcCurrency); + final ConversionRate rate = (targetTable != null) ? targetTable.get(tgtCurrency) : null; + return rate; + } + } + +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution07/src/org/apidesign/apifest08/currency/TimeRangeSpecificConvertor.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution07/src/org/apidesign/apifest08/currency/TimeRangeSpecificConvertor.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,109 @@ +package org.apidesign.apifest08.currency; + +import java.util.Currency; +import java.util.Date; +import org.apidesign.apifest08.currency.Convertor.ConversionRequest; +import org.apidesign.apifest08.currency.Convertor.ConversionResult; + +/** + * This {@link Convertor} delegates to an underlying one, provided that the request specifies time between from (included) and till (excluded). + * Otherwise it just refuses to convert. + * @author jdvorak + */ +public class TimeRangeSpecificConvertor extends DelegatingConvertor { + + private final Date from; + private final Date till; + + /** + * A new time range specific convertor. + * @param old the underlying convertor one delegates to + * @param from the beginning of the time interval + * @param till the end of the time interval + * @throws IllegalArgumentException unless from comes before till + */ + public TimeRangeSpecificConvertor( final Convertor old, final Date from, final Date till ) { + super( old ); + this.from = from; + this.till = till; + if (! from.before( till ) ) { + throw new IllegalArgumentException( "from must come before till" ); + } + } + + /** + * The beginning of the time interval. + */ + public Date getFrom() { + return from; + } + + /** + * The end of the time interval. + */ + public Date getTill() { + return till; + } + + /** + * The conversion method. + * Takes a {@link TimeSpecificConversionRequest}, other {@link ConversionRequest}s will result in an exception being thrown. + * @param req the request; must not be null; must be {@link TimeSpecificConversionRequest} or a subclass thereof + * @return the response + * @throws IllegalRequestSubtypeException iff req is not instance of {@link TimeSpecificConversionRequest} + */ + @Override + public ConversionResult convert( final ConversionRequest req ) { + if ( req instanceof TimeSpecificConversionRequest ) { + final Date time = ( (TimeSpecificConversionRequest) req ).getTime(); + if ( ( from == null || !from.after(time) ) && ( till == null || time.before(till) ) ) { + return super.convert( req ); + } else { + return new ConversionResult( null ); + } + } else { + throw new IllegalRequestSubtypeException( this.getClass().getName() + ".convert() requires a TimeSpecificConversionRequest to be passed in" ); + } + } + + /** + * The request for converting a monetary amount into another currency using the conditions that apply at a particular time. + * Immutable. + */ + public static class TimeSpecificConversionRequest extends Convertor.ConversionRequest { + + private final Date time; + + /** + * A request to convert srcAmount into tgtCurrency at the current time. + * @param srcAmount the source amount; must not be null + * @param tgtCurrency the currency we want it in afterwards; must not be null + */ + public TimeSpecificConversionRequest( final MonetaryAmount srcAmount, final Currency tgtCurrency ) { + this( srcAmount, tgtCurrency, new Date() ); + } + + /** + * A request to convert srcAmount into tgtCurrency at given time. + * @param srcAmount the source amount; must not be null + * @param tgtCurrency the currency we want it in afterwards; must not be null + * @param time the time instant when the conversion is to be carried out + */ + public TimeSpecificConversionRequest( final MonetaryAmount srcAmount, final Currency tgtCurrency, final Date time ) { + super( srcAmount, tgtCurrency ); + this.time = time; + if ( time == null ) { + throw new NullPointerException( "The time of conversion" ); + } + } + + /** + * The time as of which the conversion is to be carried out. + */ + public Date getTime() { + return time; + } + + } + +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution07/src/org/apidesign/apifest08/currency/anothervendor/ZigZaggingBidirectionalConvertor.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution07/src/org/apidesign/apifest08/currency/anothervendor/ZigZaggingBidirectionalConvertor.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,130 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package org.apidesign.apifest08.currency.anothervendor; + +import java.math.BigDecimal; +import java.util.Currency; +import java.util.Iterator; +import org.apidesign.apifest08.currency.Convertor; +import org.apidesign.apifest08.currency.IllegalRequestSubtypeException; +import org.apidesign.apifest08.currency.MonetaryAmount; + + +/** + * A convertor that changes the rate by a step amount on every conversion it performs. + * @author jdvorak + */ +public class ZigZaggingBidirectionalConvertor implements Convertor { + + private final MonetaryAmount srcRateAmount; + + private final Currency tgtCurrency; + + private final Iterator rateIterator; + + /** + * Costructor with the precise amounts. + * @param srcRateAmount + * @param tgtCurrency + * @param startAmount + * @param endAmount + * @param stepAmount + */ + public ZigZaggingBidirectionalConvertor( final MonetaryAmount srcRateAmount, final Currency tgtCurrency, final BigDecimal startAmount, final BigDecimal endAmount, final BigDecimal stepAmount ) { + this.srcRateAmount = srcRateAmount; + this.tgtCurrency = tgtCurrency; + this.rateIterator = new ZigZaggingBigDecimalIterator( startAmount, endAmount, stepAmount ); + } + + /** + * Do the conversion; updates the rate. + * @param req + * @return + * @throws org.apidesign.apifest08.currency.IllegalRequestSubtypeException + */ + public synchronized ConversionResult convert( ConversionRequest req ) throws IllegalRequestSubtypeException { + if ( tgtCurrency.equals( req.getTgtCurrency() ) ) { + if ( srcRateAmount.getCurrency().equals( req.getSrcAmount().getCurrency() ) ) { + final BigDecimal tgtRateAmount = rateIterator.next(); + final BigDecimal tgtAmount = req.getSrcAmount().getAmount().multiply( tgtRateAmount ).divide( srcRateAmount.getAmount() ); + return new ConversionResult( new MonetaryAmount( tgtAmount, tgtCurrency ) ); + } + } + if ( srcRateAmount.getCurrency().equals( req.getTgtCurrency() ) ) { + if ( tgtCurrency.equals( req.getSrcAmount().getCurrency() ) ) { + final BigDecimal tgtRateAmount = rateIterator.next(); + final BigDecimal tgtAmount = req.getSrcAmount().getAmount().multiply( srcRateAmount.getAmount() ).divide( tgtRateAmount ); + return new ConversionResult( new MonetaryAmount( tgtAmount, srcRateAmount.getCurrency() ) ); + } + } + return new ConversionResult( null ); + } + +} + +/** + * An iterator that goes zig first, then zag, then zig again, then zag again, ad libitum. + * @author jdvorak + */ +class ZigZaggingBigDecimalIterator implements Iterator { + + private BigDecimal zigBounce; + + private BigDecimal zagBounce; + + private BigDecimal step; + + private BigDecimal currentValue; + + protected ZigZaggingBigDecimalIterator( final BigDecimal zagBounce, final BigDecimal zigBounce, final BigDecimal step ) { + this. zigBounce = zigBounce; + this.zagBounce = zagBounce; + this.currentValue = zagBounce; + this.step = step; + + if ( zigBounce == null ) { + throw new NullPointerException( "zigAmount" ); + } + if ( zagBounce == null ) { + throw new NullPointerException( "zagAmount" ); + } + if ( step == null ) { + throw new NullPointerException( "stepAmount" ); + } + final int stepSign = step.signum(); + if ( stepSign == 0 ) { + throw new IllegalArgumentException( "stepAmount can't be zero" ); + } + if ( stepSign * zigBounce.compareTo( zagBounce ) < 0 ) { + throw new IllegalArgumentException( "stepAmount shall have the same sign as endAmount - startAmount" ); + } + } + + public boolean hasNext() { + return true; + } + + public BigDecimal next() { + final BigDecimal result = currentValue; + + currentValue = currentValue.add( step ); + final int stepSign = step.signum(); + final int currentMinusZigSign = currentValue.compareTo( zigBounce ); + if ( stepSign * currentMinusZigSign >= 0 ) { + final BigDecimal temp = zigBounce; + zigBounce = zagBounce; + zagBounce = temp; + step = step.negate(); + } + + return result; + } + + public void remove() { + throw new UnsupportedOperationException("Removal is not supported."); + } + +} \ No newline at end of file diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution07/test/org/apidesign/apifest08/test/ContractImposingDelegatingConvertor.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution07/test/org/apidesign/apifest08/test/ContractImposingDelegatingConvertor.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,53 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package org.apidesign.apifest08.test; + +import java.math.BigDecimal; +import java.util.Currency; +import junit.framework.Assert; +import org.apidesign.apifest08.currency.Convertor; +import org.apidesign.apifest08.currency.DelegatingConvertor; +import org.apidesign.apifest08.currency.MonetaryAmount; + +/** + * A delegating convertor that checks preconditions and postconditions. + * Useful for testing. + * @author jdvorak + */ +public class ContractImposingDelegatingConvertor extends DelegatingConvertor { + + public ContractImposingDelegatingConvertor( final Convertor underlyingConvertor ) { + super( underlyingConvertor ); + } + + @Override + public ConversionResult convert( final ConversionRequest req ) { + Assert.assertNotNull( "The request", req ); + final ConversionResult result = super.convert( req ); + Assert.assertNotNull( "Result of the convert() call", result ); + final MonetaryAmount netAmount = result.getNetAmount(); + if ( netAmount != null ) { + Assert.assertEquals( "Converted to a different currency than specified in the request", req.getTgtCurrency(), netAmount.getCurrency() ); + } + return result; + } + + /** + * Do some tests on our own. + * @return this + */ + public Convertor test() { + try { + final Currency aCurrency = Currency.getInstance( "EUR" ); + new ConversionRequest( new MonetaryAmount( BigDecimal.ONE, aCurrency ), aCurrency ); + Assert.fail( "Should have thrown an IllegalArgumentException" ); + } catch ( final IllegalArgumentException e ) { + Assert.assertEquals( "Cannot request conversion from EUR to EUR", e.getMessage() ); + } + return this; + } + +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution07/test/org/apidesign/apifest08/test/Task1Test.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution07/test/org/apidesign/apifest08/test/Task1Test.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,177 @@ +package org.apidesign.apifest08.test; + +import java.util.Currency; +import junit.framework.TestCase; +import org.apidesign.apifest08.currency.ConversionRate; +import org.apidesign.apifest08.currency.Convertor; +import org.apidesign.apifest08.currency.MonetaryAmount; +import org.apidesign.apifest08.currency.TableConvertor; + +/** Finish the Convertor API, and then write bodies of methods inside + * of this class to match the given tasks. To fullfil your task, use the + * API define in the org.apidesign.apifest08.currency package. + * Do not you reflection, or other hacks as your code + * shall run without any runtime permissions. + */ +public class Task1Test extends TestCase { + public Task1Test(String testName) { + super(testName); + } + + @Override + protected void setUp() throws Exception { + } + + @Override + protected void tearDown() throws Exception { + } + + // + // Imagine that there are three parts of the whole system: + // 1. there is someone who knows the current exchange rate + // 2. there is someone who wants to do the conversion + // 3. there is the API between 1. and 2. which allows them to communicate + // Please design such API + // + + protected static final Currency CZK = Currency.getInstance( "CZK" ); + protected static final Currency SKK = Currency.getInstance( "SKK" ); + protected static final Currency USD = Currency.getInstance( "USD" ); + + /** Create convertor that understands two currencies, CZK and + * USD. Make 1 USD == 17 CZK. + * USD. Make 1 USD == 17 CZK. This is a method provided for #1 group - + * e.g. those that know the exchange rate. They somehow need to create + * the objects from the API and tell them the exchange rate. The API itself + * knows nothing about any rates, before the createCZKtoUSD method is called. + * + * Creation of the convertor shall not require subclassing of any class + * or interface on the client side. + * + * @return prepared convertor ready for converting USD to CZK and CZK to USD + */ + public static Convertor createCZKtoUSD() { + final TableConvertor convertor = new TableConvertor(); + final MonetaryAmount amountInCZK = new MonetaryAmount( 17, CZK ); + final MonetaryAmount amountInUSD = new MonetaryAmount( 1, USD ); + convertor.putIntoTable( new ConversionRate( amountInCZK, amountInUSD ) ); + convertor.putIntoTable( new ConversionRate( amountInUSD, amountInCZK ) ); + return new ContractImposingDelegatingConvertor( convertor ).test(); + } + + /** Create convertor that understands two currencies, CZK and + * SKK. Make 100 SKK == 80 CZK. Again this is method for the #1 group - + * it knows the exchange rate, and needs to use the API to create objects + * with the exchange rate. Anyone shall be ready to call this method without + * any other method being called previously. The API itself shall know + * nothing about any rates, before this method is called. + * + * Creation of the convertor shall not require subclassing of any class + * or interface on the client side. + * + * @return prepared convertor ready for converting SKK to CZK and CZK to SKK + */ + public static Convertor createSKKtoCZK() { + final TableConvertor convertor = new TableConvertor(); + final MonetaryAmount amountInSKK = new MonetaryAmount( 100, SKK ); + final MonetaryAmount amountInCZK = new MonetaryAmount( 80, CZK ); + convertor.putIntoTable( new ConversionRate( amountInSKK, amountInCZK ) ); + convertor.putIntoTable( new ConversionRate( amountInCZK, amountInSKK ) ); + return new ContractImposingDelegatingConvertor( convertor ).test(); + } + + // + // now the methods for group #2 follow: + // this group knows nothing about exchange rates, but knows how to use + // the API to do conversions. It somehow (by calling one of the factory + // methods) gets objects from the API and uses them to do the conversions. + // + + /** Use the convertor from createCZKtoUSD method and do few conversions + * with it. + */ + public void testCurrencyCZKUSD() throws Exception { + final Convertor c = createCZKtoUSD(); + + // convert $5 to CZK using c: + final Convertor.ConversionResult r1 = c.convert( new Convertor.ConversionRequest( new MonetaryAmount( 5, USD ), CZK ) ); + final MonetaryAmount a1 = r1.getNetAmount(); + // assertEquals("Result is 85 CZK"); + assertNotNull( a1 ); + assertEquals( 85.0, a1.getAmount().doubleValue() ); + assertEquals( CZK, a1.getCurrency() ); + + // convert $8 to CZK + final Convertor.ConversionResult r2 = c.convert( new Convertor.ConversionRequest( new MonetaryAmount( 8, USD ), CZK ) ); + final MonetaryAmount a2 = r2.getNetAmount(); + // assertEquals("Result is 136 CZK"); + assertNotNull( a2 ); + assertEquals( 136.0, a2.getAmount().doubleValue() ); + assertEquals( CZK, a2.getCurrency() ); + + // convert 1003CZK to USD + final Convertor.ConversionResult r3 = c.convert( new Convertor.ConversionRequest( new MonetaryAmount( 1003, CZK ), USD ) ); + final MonetaryAmount a3 = r3.getNetAmount(); + // assertEquals("Result is 59 USD"); + assertNotNull( a3 ); + assertEquals( 59.0, a3.getAmount().doubleValue() ); + assertEquals( USD, a3.getCurrency() ); + } + + /** Use the convertor from createSKKtoCZK method and do few conversions + * with it. + */ + public void testCurrencySKKCZK() throws Exception { + final Convertor c = createSKKtoCZK(); + + // convert 16CZK using c: + final Convertor.ConversionResult r1 = c.convert( new Convertor.ConversionRequest( new MonetaryAmount( 16, CZK ), SKK ) ); + final MonetaryAmount a1 = r1.getNetAmount(); + // assertEquals("Result is 20 SKK"); + assertNotNull( a1 ); + assertEquals( 20.0, a1.getAmount().doubleValue() ); + assertEquals( SKK, a1.getCurrency() ); + + // convert 500SKK to CZK + final Convertor.ConversionResult r2 = c.convert( new Convertor.ConversionRequest( new MonetaryAmount( 500, SKK ), CZK ) ); + final MonetaryAmount a2 = r2.getNetAmount(); + // assertEquals("Result is 400 CZK"); + assertNotNull( a2 ); + assertEquals( 400.0, a2.getAmount().doubleValue() ); + assertEquals( CZK, a2.getCurrency() ); + } + + /** Verify that the CZK to USD convertor knows nothing about SKK. + */ + public void testCannotConvertToSKKwithCZKUSDConvertor() throws Exception { + final Convertor c = createCZKtoUSD(); + + // convert $5 to SKK, the API shall say this is not possible + final Convertor.ConversionResult r1 = c.convert( new Convertor.ConversionRequest( new MonetaryAmount( 5, USD ), SKK ) ); + final MonetaryAmount a1 = r1.getNetAmount(); + assertNull( a1 ); + + // convert 500 SKK to CZK, the API shall say this is not possible + final Convertor.ConversionResult r2 = c.convert( new Convertor.ConversionRequest( new MonetaryAmount( 5, SKK ), CZK ) ); + final MonetaryAmount a2 = r2.getNetAmount(); + assertNull( a2 ); + } + + /** Verify that the CZK to SKK convertor knows nothing about USD. + */ + public void testCannotConvertToUSDwithCZKSKKConvertor() throws Exception { + final Convertor c = createSKKtoCZK(); + + // convert $5 to SKK, the API shall say this is not possible + final Convertor.ConversionResult r1 = c.convert( new Convertor.ConversionRequest( new MonetaryAmount( 5, USD ), SKK ) ); + final MonetaryAmount a1 = r1.getNetAmount(); + assertNull( a1 ); + + // convert 500 CZK to USD, the API shall say this is not possible + final Convertor.ConversionResult r2 = c.convert( new Convertor.ConversionRequest( new MonetaryAmount( 5, CZK ), USD ) ); + final MonetaryAmount a2 = r2.getNetAmount(); + assertNull( a2 ); + } + +} + diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution07/test/org/apidesign/apifest08/test/Task2Test.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution07/test/org/apidesign/apifest08/test/Task2Test.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,192 @@ +package org.apidesign.apifest08.test; + +import java.util.Currency; +import junit.framework.TestCase; +import org.apidesign.apifest08.currency.ConversionRate; +import org.apidesign.apifest08.currency.Convertor; +import org.apidesign.apifest08.currency.IllegalRequestSubtypeException; +import org.apidesign.apifest08.currency.MonetaryAmount; +import org.apidesign.apifest08.currency.TableConvertor; + +/** There are many currencies around the world and many banks manipulate + * with more than one or two at the same time. As banks are usually the + * best paying clients, which is true even in case of your Convertor API, + * it is reasonable to listen to their requests. + *

+ * The quest for today is to enhance your existing convertor API to hold + * information about many currencies and allow conversions between any of them. + * Also, as conversion rates for diferent currencies usually arise from various + * bank departments, there is another important need. There is a need to + * compose two convertors into one by merging all the information about + * currencies they know about. + */ +public class Task2Test extends TestCase { + public Task2Test(String testName) { + super(testName); + } + + @Override + protected void setUp() throws Exception { + } + + @Override + protected void tearDown() throws Exception { + } + + protected static final Currency CZK = Currency.getInstance( "CZK" ); + protected static final Currency SKK = Currency.getInstance( "SKK" ); + protected static final Currency USD = Currency.getInstance( "USD" ); + + // As in Task1Test, keep in mind, that there are three parts + // of the whole system: + // 1. there is someone who knows the current exchange rate + // 2. there is someone who wants to do the conversion + // 3. there is the API between 1. and 2. which allows them to communicate + // + // Please backward compatibly enhance your existing API to support following + // usecases: + // + + /** Create convertor that understands two currencies, CZK and + * SKK. Make 100 SKK == 75 CZK. This is method for the group of users that + * knows the exchange rate, and needs to use the API to create objects + * with the exchange rate. Anyone shall be ready to call this method without + * any other method being called previously. The API itself shall know + * nothing about any rates, before this method is called. + */ + public static Convertor createTripleConvertor() { + // Rates: 1USD = 15CZK + // Rates: 1USD = 20SKK + // Rates: 75CZK = 100SKK + final TableConvertor convertor = new TableConvertor(); + final MonetaryAmount amountInUSD = new MonetaryAmount( 1, USD ); + final MonetaryAmount amountInCZK = new MonetaryAmount( 15, CZK ); + final MonetaryAmount amountInSKK = new MonetaryAmount( 20, SKK ); + convertor.putIntoTable( new ConversionRate( amountInCZK, amountInUSD ) ); + convertor.putIntoTable( new ConversionRate( amountInUSD, amountInCZK ) ); + convertor.putIntoTable( new ConversionRate( amountInSKK, amountInUSD ) ); + convertor.putIntoTable( new ConversionRate( amountInUSD, amountInSKK ) ); + convertor.putIntoTable( new ConversionRate( amountInSKK, amountInCZK ) ); + convertor.putIntoTable( new ConversionRate( amountInCZK, amountInSKK ) ); + return new ContractImposingDelegatingConvertor( convertor ).test(); + } + + /** Define convertor that understands three currencies. Use it. + */ + public void testConvertorForUSDandCZKandSKK() throws Exception { + final Convertor c = createTripleConvertor(); + + // convert $5 to CZK using c: + final Convertor.ConversionResult r1 = c.convert( new Convertor.ConversionRequest( new MonetaryAmount( 5, USD ), CZK ) ); + final MonetaryAmount a1 = r1.getNetAmount(); + // assertEquals("Result is 75 CZK"); + assertNotNull( a1 ); + assertEquals( 75.0, a1.getAmount().doubleValue() ); + assertEquals( CZK, a1.getCurrency() ); + + // convert $5 to SKK using c: + final Convertor.ConversionResult r2 = c.convert( new Convertor.ConversionRequest( new MonetaryAmount( 5, USD ), SKK ) ); + final MonetaryAmount a2 = r2.getNetAmount(); + // assertEquals("Result is 100 SKK"); + assertNotNull( a2 ); + assertEquals( 100.0, a2.getAmount().doubleValue() ); + assertEquals( SKK, a2.getCurrency() ); + + // convert 200SKK to CZK using c: + final Convertor.ConversionResult r3 = c.convert( new Convertor.ConversionRequest( new MonetaryAmount( 200, SKK ), CZK ) ); + final MonetaryAmount a3 = r3.getNetAmount(); + // assertEquals("Result is 150 CZK"); + assertNotNull( a3 ); + assertEquals( 150.0, a3.getAmount().doubleValue() ); + assertEquals( CZK, a3.getCurrency() ); + + // convert 200SKK to USK using c: + final Convertor.ConversionResult r4 = c.convert( new Convertor.ConversionRequest( new MonetaryAmount( 200, SKK ), USD ) ); + final MonetaryAmount a4 = r4.getNetAmount(); + // assertEquals("Result is 10 USD"); + assertNotNull( a4 ); + assertEquals( 10.0, a4.getAmount().doubleValue() ); + assertEquals( USD, a4.getCurrency() ); + } + + /** Merge all currency rates of convertor 1 with convertor 2. + * Implement this using your API, preferably this method just delegates + * into some API method which does the actual work, without requiring + * API clients to code anything complex. + */ + public static Convertor merge( final Convertor one, final Convertor two ) { + return new Convertor() { + + public ConversionResult convert( ConversionRequest req ) throws IllegalRequestSubtypeException { + final ConversionResult res1 = one.convert( req ); + final ConversionResult res2 = two.convert( req ); + if ( res1.getNetAmount() != null ) { + if ( res2.getNetAmount() != null ) { + // TODO check if they arrive at the same thing + return res1; + } else { + return res1; + } + } else { + if ( res2.getNetAmount() != null ) { + return res2; + } else { + // neither converts + return new ConversionResult( null ); + } + } + } + + }; + } + + /** Join the convertors from previous task, Task1Test and show that it + * can be used to do reasonable conversions. + */ + public void testConvertorComposition() throws Exception { + final Convertor c = merge( + Task1Test.createCZKtoUSD(), + Task1Test.createSKKtoCZK() + ); + + // convert $5 to CZK using c: + final Convertor.ConversionResult r1 = c.convert( new Convertor.ConversionRequest( new MonetaryAmount( 5, USD ), CZK ) ); + final MonetaryAmount a1 = r1.getNetAmount(); + // assertEquals("Result is 85 CZK"); + assertNotNull( a1 ); + assertEquals( 85.0, a1.getAmount().doubleValue() ); + assertEquals( CZK, a1.getCurrency() ); + + // convert $8 to CZK + final Convertor.ConversionResult r2 = c.convert( new Convertor.ConversionRequest( new MonetaryAmount( 8, USD ), CZK ) ); + final MonetaryAmount a2 = r2.getNetAmount(); + // assertEquals("Result is 136 CZK"); + assertNotNull( a2 ); + assertEquals( 136.0, a2.getAmount().doubleValue() ); + assertEquals( CZK, a2.getCurrency() ); + + // convert 1003CZK to USD + final Convertor.ConversionResult r3 = c.convert( new Convertor.ConversionRequest( new MonetaryAmount( 1003, CZK ), USD ) ); + final MonetaryAmount a3 = r3.getNetAmount(); + // assertEquals("Result is 59 USD"); + assertNotNull( a3 ); + assertEquals( 59.0, a3.getAmount().doubleValue() ); + assertEquals( USD, a3.getCurrency() ); + + // convert 16CZK using c: + final Convertor.ConversionResult r4 = c.convert( new Convertor.ConversionRequest( new MonetaryAmount( 16, CZK ), SKK ) ); + final MonetaryAmount a4 = r4.getNetAmount(); + // assertEquals("Result is 20 SKK"); + assertNotNull( a4 ); + assertEquals( 20.0, a4.getAmount().doubleValue() ); + assertEquals( SKK, a4.getCurrency() ); + + // convert 500SKK to CZK using c: + final Convertor.ConversionResult r5 = c.convert( new Convertor.ConversionRequest( new MonetaryAmount( 500, SKK ), CZK ) ); + final MonetaryAmount a5 = r5.getNetAmount(); + // assertEquals("Result is 400 CZK"); + assertNotNull( a5 ); + assertEquals( 400.0, a5.getAmount().doubleValue() ); + assertEquals( CZK, a5.getCurrency() ); + } +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution07/test/org/apidesign/apifest08/test/Task3Test.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution07/test/org/apidesign/apifest08/test/Task3Test.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,135 @@ +package org.apidesign.apifest08.test; + +import java.math.BigDecimal; +import java.util.Currency; +import junit.framework.TestCase; +import org.apidesign.apifest08.currency.Convertor; +import org.apidesign.apifest08.currency.MonetaryAmount; +import org.apidesign.apifest08.currency.anothervendor.ZigZaggingBidirectionalConvertor; + +/** The exchange rates are not always the same. They are changing. Day by day, + * hour by hour, minute by minute. For every bank it is important to always + * have the actual exchange rate available in the system. That is why let's + * create a pluggable convertor that will always have up to date value of its + * exchange rate. + *

+ * The quest for today is to allow 3rd party developer to write a convertor + * that adjusts its exchange rate everytime it is queried. This convertor is + * written by independent vendor, the vendor knows only your Convertor API, + * he does not know how the whole system looks and how the convertor is supposed + * to be used. + */ +public class Task3Test extends TestCase { + public Task3Test(String testName) { + super(testName); + } + + @Override + protected void setUp() throws Exception { + } + + @Override + protected void tearDown() throws Exception { + } + + protected static final Currency CZK = Currency.getInstance( "CZK" ); + protected static final Currency SKK = Currency.getInstance( "SKK" ); + protected static final Currency USD = Currency.getInstance( "USD" ); + + // Backward compatibly enhance your existing API to support following + // usecases: + // + + + /** Without knowing anything about the surrounding system, write an + * implementation of convertor that will return different rates everytime + * it is queried. Convert USD to CZK and vice versa. Start with the rate of + * 1USD = 16CZK and adjust it in favor of CZK by 0.01 CZK with every query. + * As soon as you reach 1USD = 15CZK adjust it by 0.01 CZK in favor of USD + * until you reach 1USD = 16CZK + * + * @return new instance of "online" USD and CZK convertor starting with rate 1USD = 16CZK + */ + public static Convertor createOnlineCZKUSDConvertor() { + // initial rate: 1USD = 16CZK + // 2nd query 1USD = 15.99CZK + // 3rd query 1USD = 15.98CZK + // until 1USD = 15.00CZK + // then 1USD = 15.01CZK + // then 1USD = 15.02CZK + // and so on and on up to 1USD = 16CZK + // and then another round to 15, etc. + final MonetaryAmount oneUSD = new MonetaryAmount( 1, USD ); + final BigDecimal startAmount = new BigDecimal( 16 ); + final BigDecimal endAmount = new BigDecimal( 15 ); + final BigDecimal stepAmount = BigDecimal.ONE.movePointLeft( 2 ).negate(); + return new ContractImposingDelegatingConvertor( new ZigZaggingBidirectionalConvertor( oneUSD, CZK, startAmount, endAmount, stepAmount ) ); + } + + public void testFewQueriesForOnlineConvertor() { + Convertor c = createOnlineCZKUSDConvertor(); + doFewQueriesForOnlineConvertor(c); + } + + static void doFewQueriesForOnlineConvertor( final Convertor c ) { + // convert $5 to CZK using c: + final Convertor.ConversionResult r1 = c.convert( new Convertor.ConversionRequest( new MonetaryAmount( 5, USD ), CZK ) ); + final MonetaryAmount a1 = r1.getNetAmount(); + //assertEquals("Result is 80 CZK"); + assertNotNull( a1 ); + assertEquals( 80.0, a1.getAmount().doubleValue() ); + assertEquals( CZK, a1.getCurrency() ); + + // convert $8 to CZK using c: + final Convertor.ConversionResult r2 = c.convert( new Convertor.ConversionRequest( new MonetaryAmount( 8, USD ), CZK ) ); + final MonetaryAmount a2 = r2.getNetAmount(); + //assertEquals("Result is 127.92 CZK"); + assertNotNull( a2 ); + assertEquals( 12792.0, a2.getAmount().movePointRight( 2 ).doubleValue() ); + assertEquals( CZK, a2.getCurrency() ); + + // convert $1 to CZK using c: + final Convertor.ConversionResult r3 = c.convert( new Convertor.ConversionRequest( new MonetaryAmount( 1, USD ), CZK ) ); + final MonetaryAmount a3 = r3.getNetAmount(); + //assertEquals("Result is 15.98 CZK"); + assertNotNull( a3 ); + assertEquals( 1598.0, a3.getAmount().movePointRight( 2 ).doubleValue() ); + assertEquals( CZK, a3.getCurrency() ); + + // convert 15.97CZK to USD using c: + final BigDecimal s4 = new BigDecimal( 1597 ).movePointLeft( 2 ); + final Convertor.ConversionResult r4 = c.convert( new Convertor.ConversionRequest( new MonetaryAmount( s4, CZK ), USD ) ); + final MonetaryAmount a4 = r4.getNetAmount(); + //assertEquals("Result is 1$"); + assertNotNull( a4 ); + assertEquals( 1.0, a4.getAmount().doubleValue() ); + assertEquals( USD, a4.getCurrency() ); + } + + /** Join the convertors and show they behave sane. + */ + public void testOnlineConvertorComposition() throws Exception { + final Convertor c = Task2Test.merge( + createOnlineCZKUSDConvertor(), + Task1Test.createSKKtoCZK() + ); + + // convert 16CZK using c: + final Convertor.ConversionResult r4 = c.convert( new Convertor.ConversionRequest( new MonetaryAmount( 16, CZK ), SKK ) ); + final MonetaryAmount a4 = r4.getNetAmount(); + // assertEquals("Result is 20 SKK"); + assertNotNull( a4 ); + assertEquals( 20.0, a4.getAmount().doubleValue() ); + assertEquals( SKK, a4.getCurrency() ); + + // convert 500SKK to CZK using c: + final Convertor.ConversionResult r5 = c.convert( new Convertor.ConversionRequest( new MonetaryAmount( 500, SKK ), CZK ) ); + final MonetaryAmount a5 = r5.getNetAmount(); + // assertEquals("Result is 400 CZK"); + assertNotNull( a5 ); + assertEquals( 400.0, a5.getAmount().doubleValue() ); + assertEquals( CZK, a5.getCurrency() ); + + doFewQueriesForOnlineConvertor(c); + } +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution07/test/org/apidesign/apifest08/test/Task4Test.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution07/test/org/apidesign/apifest08/test/Task4Test.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,204 @@ +package org.apidesign.apifest08.test; + +import org.apidesign.apifest08.currency.TimeRangeSpecificConvertor; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Currency; +import java.util.Date; +import junit.framework.TestCase; +import org.apidesign.apifest08.currency.ConversionRate; +import org.apidesign.apifest08.currency.Convertor; +import org.apidesign.apifest08.currency.Convertor.ConversionResult; +import org.apidesign.apifest08.currency.MonetaryAmount; +import org.apidesign.apifest08.currency.TableConvertor; +import org.apidesign.apifest08.currency.TimeRangeSpecificConvertor.TimeSpecificConversionRequest; + +/** The exchange rates are not always the same. They are changing. However + * as in order to predict the future, one needs to understand own past. That is + * why it is important to know the exchange rate as it was at any time during + * the past. + *

+ * Today's quest is to enhance the convertor API to deal with dates. + * One shall be able to convert a currency at any date. Each currencies rate shall + * be associated with a range between two Date objects. In order + * to keep compatibility with old API that knew nothing about dates, the + * rates associated then are applicable "for eternity". Any use of existing + * convert methods that do not accept a Date argument, uses the current + * System.currentTimeMillis() as default date. + */ +public class Task4Test extends TestCase { + public Task4Test(String testName) { + super(testName); + } + + @Override + protected void setUp() throws Exception { + } + + @Override + protected void tearDown() throws Exception { + } + + protected static final Currency CZK = Currency.getInstance( "CZK" ); + protected static final Currency SKK = Currency.getInstance( "SKK" ); + protected static final Currency USD = Currency.getInstance( "USD" ); + + // Backward compatibly enhance your existing API to support following + // usecases: + // + + /** Takes a convertor with any rates associated and creates new convertor + * that returns the same values as the old one for time between from to till. + * Otherwise it returns no results. This is just a helper method that + * shall call some real one in the API. + * + * @param old existing convertor + * @param from initial date (inclusive); null means since the Big Bang + * @param till final date (exclusive); null means until the End of Universe + * @return new convertor + */ + public static Convertor limitTo( final Convertor old, final Date from, final Date till ) { + return new TimeRangeSpecificConvertor( old, from, till ); + } + + private static final DateFormat DATE_FORMAT = new SimpleDateFormat( "yyyy-MM-dd HH:mm Z" ); + + protected static Date parseGmtDate( final String string ) { + final String zonedString = string + " GMT+0:00"; + try { + return DATE_FORMAT.parse( zonedString ); + } catch ( final ParseException ex ) { + throw new IllegalArgumentException( "Cannot parse " + zonedString, ex ); + } + } + + public void testCompositionOfLimitedConvertors() throws Exception { + final Date d1 = parseGmtDate( "2008-10-01 0:00" ); + final Date d2 = parseGmtDate( "2008-10-02 0:00" ); + final Date d3 = parseGmtDate( "2008-10-03 0:00" ); + + final Convertor c = Task2Test.merge( + limitTo(Task1Test.createCZKtoUSD(), d1, d2), + limitTo(Task1Test.createSKKtoCZK(), d2, d3) + ); + + // convert $5 to CZK using c: + final ConversionResult r1 = c.convert( new TimeSpecificConversionRequest( new MonetaryAmount( 5, USD ), CZK ) ); + final MonetaryAmount a1 = r1.getNetAmount(); + // cannot convert as no rate is applicable to current date + assertNull( a1 ); + + // convert $8 to CZK using c: + final ConversionResult r2 = c.convert( new TimeSpecificConversionRequest( new MonetaryAmount( 8, USD ), CZK ) ); + final MonetaryAmount a2 = r2.getNetAmount(); + // cannot convert as no rate is applicable to current date + assertNull( a2 ); + + // convert 1003CZK to USD using c: + final ConversionResult r3 = c.convert( new TimeSpecificConversionRequest( new MonetaryAmount( 1003, CZK ), USD ) ); + final MonetaryAmount a3 = r3.getNetAmount(); + // cannot convert as no rate is applicable to current date + assertNull( a3 ); + + // convert 16CZK using c: + final ConversionResult r4 = c.convert( new TimeSpecificConversionRequest( new MonetaryAmount( 16, CZK ), USD ) ); + final MonetaryAmount a4 = r4.getNetAmount(); + // cannot convert as no rate is applicable to current date + assertNull( a4 ); + + // convert 500SKK to CZK using c: + final ConversionResult r5 = c.convert( new TimeSpecificConversionRequest( new MonetaryAmount( 500, SKK ), CZK ) ); + final MonetaryAmount a5 = r5.getNetAmount(); + // cannot convert as no rate is applicable to current date + assertNull( a5 ); + + // convert $5 to CZK using c at 2008-10-01 6:00 GMT: + final ConversionResult r6 = c.convert( new TimeSpecificConversionRequest( new MonetaryAmount( 5, USD ), CZK, parseGmtDate( "2008-10-01 6:00" ) ) ); + final MonetaryAmount a6 = r6.getNetAmount(); + // assertEquals("Result is 85 CZK"); + assertNotNull( a6 ); + assertEquals( 85.0, a6.getAmount().doubleValue() ); + assertEquals( CZK, a6.getCurrency() ); + + // convert $8 to CZK using c at 2008-10-01 6:00 GMT: + final ConversionResult r7 = c.convert( new TimeSpecificConversionRequest( new MonetaryAmount( 8, USD ), CZK, parseGmtDate( "2008-10-01 6:00" ) ) ); + final MonetaryAmount a7 = r7.getNetAmount(); + // assertEquals("Result is 136 CZK"); + assertNotNull( a7 ); + assertEquals( 136.0, a7.getAmount().doubleValue() ); + assertEquals( CZK, a7.getCurrency() ); + + // convert 1003CZK to USD using c at 2008-10-01 6:00 GMT: + final ConversionResult r8 = c.convert( new TimeSpecificConversionRequest( new MonetaryAmount( 1003, CZK ), USD, parseGmtDate( "2008-10-01 6:00" ) ) ); + final MonetaryAmount a8 = r8.getNetAmount(); + // assertEquals("Result is 59 USD"); + assertNotNull( a8 ); + assertEquals( 59.0, a8.getAmount().doubleValue() ); + assertEquals( USD, a8.getCurrency() ); + + // convert 16CZK using c at 2008-10-02 9:00 GMT: + final ConversionResult r9 = c.convert( new TimeSpecificConversionRequest( new MonetaryAmount( 16, CZK ), SKK, parseGmtDate( "2008-10-02 9:00" ) ) ); + final MonetaryAmount a9 = r9.getNetAmount(); + // assertEquals("Result is 20 SKK"); + assertNotNull( a9 ); + assertEquals( 20.0, a9.getAmount().doubleValue() ); + assertEquals( SKK, a9.getCurrency() ); + + // convert 500SKK to CZK using c at 2008-10-02 9:00 GMT: + final ConversionResult r10 = c.convert( new TimeSpecificConversionRequest( new MonetaryAmount( 500, SKK ), CZK, parseGmtDate( "2008-10-02 9:00" ) ) ); + final MonetaryAmount a10 = r10.getNetAmount(); + // assertEquals("Result is 400 CZK"); + assertNotNull( a10 ); + assertEquals( 400.0, a10.getAmount().doubleValue() ); + assertEquals( CZK, a10.getCurrency() ); + + // convert 500SKK to CZK using c at 2008-10-01 6:00 GMT: + final ConversionResult r11 = c.convert( new TimeSpecificConversionRequest( new MonetaryAmount( 500, SKK ), CZK, parseGmtDate( "2008-10-01 6:00" ) ) ); + final MonetaryAmount a11 = r11.getNetAmount(); + // cannot convert as no rate is applicable to current date + assertNull( a11 ); + } + + /** Create convertor that understands two currencies, CZK and + * SKK. Make 100 SKK == 90 CZK. + * + * @return prepared convertor ready for converting SKK to CZK and CZK to SKK + */ + public static Convertor createSKKtoCZK2() { + final TableConvertor convertor = new TableConvertor(); + final MonetaryAmount amountInSKK = new MonetaryAmount( 100, SKK ); + final MonetaryAmount amountInCZK = new MonetaryAmount( 90, CZK ); + convertor.putIntoTable( new ConversionRate( amountInSKK, amountInCZK ) ); + convertor.putIntoTable( new ConversionRate( amountInCZK, amountInSKK ) ); + return new ContractImposingDelegatingConvertor( convertor ).test(); + } + + public void testDateConvetorWithTwoDifferentRates() throws Exception { + final Date d1 = parseGmtDate( "2008-10-01 0:00" ); + final Date d2 = parseGmtDate( "2008-10-02 0:00" ); + final Date d3 = parseGmtDate( "2008-10-03 0:00" ); + + final Convertor c = Task2Test.merge( + limitTo(createSKKtoCZK2(), d1, d2), + limitTo(Task1Test.createSKKtoCZK(), d2, d3) + ); + + // convert 500SKK to CZK using c at 2008-10-02 9:00 GMT: + final ConversionResult r1 = c.convert( new TimeSpecificConversionRequest( new MonetaryAmount( 500, SKK ), CZK, parseGmtDate( "2008-10-02 9:00" ) ) ); + final MonetaryAmount a1 = r1.getNetAmount(); + // assertEquals("Result is 400 CZK"); + assertNotNull( a1 ); + assertEquals( 400.0, a1.getAmount().doubleValue() ); + assertEquals( CZK, a1.getCurrency() ); + + // convert 500SKK to CZK using c at 2008-10-01 6:00 GMT: + final ConversionResult r2 = c.convert( new TimeSpecificConversionRequest( new MonetaryAmount( 500, SKK ), CZK, parseGmtDate( "2008-10-01 6:00" ) ) ); + final MonetaryAmount a2 = r2.getNetAmount(); + // assertEquals("Result is 450 CZK"); + assertNotNull( a2 ); + assertEquals( 450.0, a2.getAmount().doubleValue() ); + assertEquals( CZK, a2.getCurrency() ); + } + +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution11/build.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution11/build.xml Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,69 @@ + + + + + + Builds, tests, and runs the project. + + + diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution11/nbproject/build-impl.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution11/nbproject/build-impl.xml Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,629 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set src.dir + Must set test.src.dir + Must set build.dir + Must set dist.dir + Must set build.classes.dir + Must set dist.javadoc.dir + Must set build.test.classes.dir + Must set build.test.results.dir + Must set build.classes.excludes + Must set dist.jar + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + + + + + + java -cp "${run.classpath.with.dist.jar}" ${main.class} + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + java -jar "${dist.jar.resolved}" + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set run.class + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set debug.class + + + + + Must set fix.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + Some tests failed; see details above. + + + + + + + + + Must select some files in the IDE or set test.includes + + + + Some tests failed; see details above. + + + + + Must select one file in the IDE or set test.class + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + + + + + + + + + + + diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution11/nbproject/genfiles.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution11/nbproject/genfiles.properties Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,8 @@ +build.xml.data.CRC32=2ab820eb +build.xml.script.CRC32=58a52595 +build.xml.stylesheet.CRC32=be360661 +# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. +# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. +nbproject/build-impl.xml.data.CRC32=0e1e702f +nbproject/build-impl.xml.script.CRC32=c899f2cf +nbproject/build-impl.xml.stylesheet.CRC32=487672f9 diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution11/nbproject/project.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution11/nbproject/project.properties Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,68 @@ +application.title=currency +application.vendor=apidesign.org +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.tab-size=8 +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.text-limit-width=80 +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.usedProfile=default +build.classes.dir=${build.dir}/classes +build.classes.excludes=**/*.java,**/*.form +# This directory is removed when the project is cleaned: +build.dir=build +build.generated.dir=${build.dir}/generated +# Only compile against the classpath explicitly listed here: +build.sysclasspath=ignore +build.test.classes.dir=${build.dir}/test/classes +build.test.results.dir=${build.dir}/test/results +debug.classpath=\ + ${run.classpath} +debug.test.classpath=\ + ${run.test.classpath} +# This directory is removed when the project is cleaned: +dist.dir=dist +dist.jar=${dist.dir}/currency.jar +dist.javadoc.dir=${dist.dir}/javadoc +excludes= +file.reference.junit-4.4.jar=../../libs/junit-4.4.jar +file.reference.src-apifest08=.. +includes=** +jar.compress=false +javac.classpath= +# Space-separated list of extra javac options +javac.compilerargs=-Xlint:unchecked +javac.deprecation=false +javac.source=1.5 +javac.target=1.5 +javac.test.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir}:\ + ${file.reference.junit-4.4.jar} +javadoc.additionalparam= +javadoc.author=false +javadoc.encoding= +javadoc.noindex=false +javadoc.nonavbar=false +javadoc.notree=false +javadoc.private=false +javadoc.splitindex=true +javadoc.use=true +javadoc.version=false +javadoc.windowtitle= +jnlp.codebase.type=local +jnlp.codebase.url=file:/home/jarda/src/apifest08/currency/dist +jnlp.descriptor=application +jnlp.enabled=false +jnlp.offline-allowed=false +jnlp.signed=false +meta.inf.dir=${src.dir}/META-INF +platform.active=default_platform +run.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +# Space-separated list of JVM arguments used when running the project +# (you may also define separate properties like run-sys-prop.name=value instead of -Dname=value +# or test-sys-prop.name=value to set system properties for unit tests): +run.jvmargs= +run.test.classpath=\ + ${javac.test.classpath}:\ + ${build.test.classes.dir} +src.dir=src +test.src.dir=test diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution11/nbproject/project.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution11/nbproject/project.xml Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,16 @@ + + + org.netbeans.modules.java.j2seproject + + + Currency Convertor Solution 11 + 1.6.5 + + + + + + + + + diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution11/src/org/apidesign/apifest08/currency/Computer.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution11/src/org/apidesign/apifest08/currency/Computer.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,61 @@ +package org.apidesign.apifest08.currency; + +/** + * Interface declaring method for computing conversion. + * + * Because of a vague definition of currency amount's type, + * the interface has a generic type. + * + * @author ked + * @see http://wiki.apidesign.org/wiki/APIDesignPatterns:ResponseReply + */ +interface Computer { + + void compute(ComputerRequest request, ComputerResponse response); + + final class ComputerRequest { + + private AmountType input; + private AmountType inputCurrencyRatio; + private AmountType outputCurrencyRatio; + + AmountType getInput() { + return input; + } + + void setInput(AmountType input) { + this.input = input; + } + + AmountType getInputCurrencyRatio() { + return inputCurrencyRatio; + } + + void setInputCurrencyRatio(AmountType inputCurrencyRatio) { + this.inputCurrencyRatio = inputCurrencyRatio; + } + + AmountType getOutputCurrencyRatio() { + return outputCurrencyRatio; + } + + void setOutputCurrencyRatio(AmountType outputCurrencyRatio) { + this.outputCurrencyRatio = outputCurrencyRatio; + } + } + + final class ComputerResponse { + + private AmountType result; + + AmountType getResult() { + return result; + } + + void setResult(AmountType result) { + this.result = result; + } + } + + +} \ No newline at end of file diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution11/src/org/apidesign/apifest08/currency/Convertor.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution11/src/org/apidesign/apifest08/currency/Convertor.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,389 @@ +package org.apidesign.apifest08.currency; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import org.apidesign.apifest08.currency.Computer.ComputerRequest; +import org.apidesign.apifest08.currency.Computer.ComputerResponse; + +/** + * Convertor. + * + * In Task 1's version provides conversion between currency values + * with amount stored in integer or double, that are identified + * with string value. Exchange rates are immutable. + * + * In Task2's version provides support for multiple exchange rates + * between different currencies & merging exchange rates from + * existing convertors into new convertor's instance. + * No time for javadoc these features, sorry. + * + * In Task3's version supports reading of current exchange rates + * from data sources. Data sources are merged during convertors' merging + * as well as static exchange rates. + * No time for javadoc, again. + * + * In Task4's version takes into account validity range of data sources, + * can convert using an exchange rate value according to the specified instant + * of the time and provides a method for creating a new convertor with the same + * data sources as the old one, but with their validity ranges limited + * to the specified range. + * As usual, no time for javadoc. + * + * @author ked + */ +public final class Convertor { + + Computer computer; + // each static exchange rate is a special case of an exchange rate data source + // historically separated + List> staticExchangeRateDataSources = + new ArrayList>(); + List> exchangeRateDataSources = + new ArrayList>(); + + // --- + // BASICS + // --- + Convertor(Computer computer) { + this.computer = computer; + } + + void addExchangeRateDataSources( + List> target, + Collection> exchangeRateDataSources) { + for (ExchangeRateDataSource exchangeRateDataSource : exchangeRateDataSources) { + if (isOverlappingExchangeRate( + exchangeRateDataSource.getCurrencyAIdentifier(), + exchangeRateDataSource.getCurrencyBIdentifier(), + exchangeRateDataSource.getValidFrom(), + exchangeRateDataSource.getValidTill())) { + throw new IllegalArgumentException("Duplicate exchange rate!"); + } + target.add(exchangeRateDataSource); + } + } + + ExchangeRateValue findExchangeRate( + IdentifierType currencyA, + IdentifierType currencyB, + Date instant) { + ExchangeRateValue result = null; + result = findExchangeRateInternal(staticExchangeRateDataSources, currencyA, currencyB, instant); + if (result != null) { + return result; + } + result = findExchangeRateInternal(exchangeRateDataSources, currencyA, currencyB, instant); + return result; + } + + ExchangeRateValue findExchangeRateInternal( + List> where, + IdentifierType currencyA, + IdentifierType currencyB, + Date instant) { + for (ExchangeRateDataSource exchangeRateDataSource : where) { + if (((exchangeRateDataSource.getCurrencyAIdentifier().equals(currencyA) && exchangeRateDataSource.getCurrencyBIdentifier().equals(currencyB)) || + (exchangeRateDataSource.getCurrencyAIdentifier().equals(currencyB) && exchangeRateDataSource.getCurrencyBIdentifier().equals(currencyA))) && + DateUtil.isInRange(instant, exchangeRateDataSource.getValidFrom(), exchangeRateDataSource.getValidTill())) { + return exchangeRateDataSource.getExchangeRate(); + } + } + return null; + } + + boolean isOverlappingExchangeRate( + IdentifierType currencyA, + IdentifierType currencyB, + Date from, + Date to) { + boolean result = false; + result = isOverlappingExchangeRateInternal(staticExchangeRateDataSources, currencyA, currencyB, from, to); + if (result == true) { + return result; + } + result = isOverlappingExchangeRateInternal(exchangeRateDataSources, currencyA, currencyB, from, to); + return result; + } + + boolean isOverlappingExchangeRateInternal( + List> where, + IdentifierType currencyA, + IdentifierType currencyB, + Date from, + Date to) { + for (ExchangeRateDataSource exchangeRateDataSource : where) { + if (((exchangeRateDataSource.getCurrencyAIdentifier().equals(currencyA) && exchangeRateDataSource.getCurrencyBIdentifier().equals(currencyB)) || + (exchangeRateDataSource.getCurrencyAIdentifier().equals(currencyB) && exchangeRateDataSource.getCurrencyBIdentifier().equals(currencyA))) && + DateUtil.isRangesOverlapping(from, to, exchangeRateDataSource.getValidFrom(), exchangeRateDataSource.getValidTill())) { + return true; + } + } + return false; + } + + /** + * Convert an amount of the one currency to an amount of the another one currency + * with respect to previously specified exchange rates. + * + * @param targetCurrency an identifier of the requested currency + * @param currencyValue an amount of the another one currency + * @return an amount of the requested currency + */ + public CurrencyValue convert( + IdentifierType targetCurrency, + CurrencyValue currencyValue) { + return convert(targetCurrency, currencyValue, new Date()); // System.currentTimeMillis() + } + + public CurrencyValue convert( + IdentifierType targetCurrency, + CurrencyValue currencyValue, + Date instant) { + ExchangeRateValue exchangeRate = + findExchangeRate(currencyValue.getIdentifier(), targetCurrency, instant); + if (exchangeRate == null) { + throw new IllegalArgumentException("Inappropriate currencies to convert!"); + } + + ComputerRequest computerRequest = new ComputerRequest(); + computerRequest.setInput(currencyValue.getAmount()); + + IdentifierType targetCurrencyRef; // just for backward compatibility :-( + if (exchangeRate.getCurrencyA().getIdentifier().equals(targetCurrency)) { + computerRequest.setInputCurrencyRatio(exchangeRate.getCurrencyB().getAmount()); + computerRequest.setOutputCurrencyRatio(exchangeRate.getCurrencyA().getAmount()); + targetCurrencyRef = exchangeRate.getCurrencyA().getIdentifier(); + } else { + computerRequest.setInputCurrencyRatio(exchangeRate.getCurrencyA().getAmount()); + computerRequest.setOutputCurrencyRatio(exchangeRate.getCurrencyB().getAmount()); + targetCurrencyRef = exchangeRate.getCurrencyB().getIdentifier(); + } + + ComputerResponse computerResponse = new ComputerResponse(); + computer.compute(computerRequest, computerResponse); + + return CurrencyValue.getCurrencyValue( + computerResponse.getResult(), + targetCurrencyRef); + } + + // --- + // LIMITING + // --- + Collection> limitDataSources( + Collection> source, + Date from, Date till) { + Collection> result = + new ArrayList>(); + + for (ExchangeRateDataSource dataSource : source) { + result.add(ExchangeRateDataSource.getExchangeRateDataSource( + dataSource.getCurrencyAIdentifier(), dataSource.getCurrencyBIdentifier(), + dataSource.getExchangeRateProvider(), + DateUtil.getRangesIntersectionBottom(dataSource.getValidFrom(), from), + DateUtil.getRangesIntersectionTop(dataSource.getValidTill(), till))); + } + + return result; + } + + public Convertor limitConvertor(Date from, Date till) { + Collection> limitedStatic = + limitDataSources(staticExchangeRateDataSources, from, till); + Collection> limited = + limitDataSources(exchangeRateDataSources, from, till); + + Convertor c = new Convertor(computer); + c.addExchangeRateDataSources(c.staticExchangeRateDataSources, limitedStatic); + c.addExchangeRateDataSources(c.exchangeRateDataSources, limited); + return c; + } + + // --- + // MERGING + // --- + static Convertor mergeConvertors( + Computer computer, + Collection> convertors) { + Set> mergedStatic = + new HashSet>(); + Set> merged = + new HashSet>(); + for (Convertor convertor : convertors) { + mergedStatic.addAll(convertor.staticExchangeRateDataSources); + } + for (Convertor convertor : convertors) { + merged.addAll(convertor.exchangeRateDataSources); + } + + Convertor c = new Convertor(computer); + c.addExchangeRateDataSources(c.staticExchangeRateDataSources, mergedStatic); + c.addExchangeRateDataSources(c.exchangeRateDataSources, merged); + return c; + } + + static Convertor mergeConvertors( + Computer computer, + Convertor convertorA, + Convertor convertorB) { + Collection> convertors = + new ArrayList>(); + convertors.add(convertorA); + convertors.add(convertorB); + return mergeConvertors(computer, convertors); + } + + public static Convertor mergeConvertorsDoubleString( + Collection> convertors) { + return mergeConvertors(DoubleComputer, convertors); + } + + public static Convertor mergeConvertorsDoubleString( + Convertor convertorA, + Convertor convertorB) { + return mergeConvertors(DoubleComputer, convertorA, convertorB); + } + + public static Convertor mergeConvertorsIntegerString( + Collection> convertors) { + return mergeConvertors(IntegerComputer, convertors); + } + + public static Convertor mergeConvertorsIntegerString( + Convertor convertorA, + Convertor convertorB) { + return mergeConvertors(IntegerComputer, convertorA, convertorB); + } + + // --- + // CREATION + // --- + static Convertor getConvertor( + Computer computer, Collection> exchangeRates) { + Convertor c = new Convertor(computer); + Collection> exchangeRateDataSources = + new ArrayList>(); + for (ExchangeRateValue exchangeRate : exchangeRates) { + exchangeRateDataSources.add( + ExchangeRateDataSource.getExchangeRateDataSource( + exchangeRate.getCurrencyA().getIdentifier(), exchangeRate.getCurrencyB().getIdentifier(), + StaticExchangeRateProvider.getStaticExchangeRateProvider(exchangeRate))); + } + c.addExchangeRateDataSources(c.staticExchangeRateDataSources, exchangeRateDataSources); + return c; + } + + static Convertor getConvertorDataSource( + Computer computer, Collection> exchangeRateDataSources) { + Convertor c = new Convertor(computer); + c.addExchangeRateDataSources(c.exchangeRateDataSources, exchangeRateDataSources); + return c; + } + + static Convertor getConvertor( + Computer computer, ExchangeRateValue exchangeRate) { + Collection> exchangeRates = + new ArrayList>(); + exchangeRates.add(exchangeRate); + return getConvertor(computer, exchangeRates); + } + + static Convertor getConvertorDataSource( + Computer computer, ExchangeRateDataSource exchangeRateDataSource) { + Collection> exchangeRateDataSources = + new ArrayList>(); + exchangeRateDataSources.add(exchangeRateDataSource); + return getConvertorDataSource(computer, exchangeRateDataSources); + } + + public static Convertor getConvertorDoubleString( + Collection> exchangeRates) { + return getConvertor(DoubleComputer, exchangeRates); + } + + public static Convertor getConvertorDoubleString( + ExchangeRateValue exchangeRate) { + return getConvertor(DoubleComputer, exchangeRate); + } + + public static Convertor getConvertorDataSourceDoubleString( + Collection> exchangeRateDataSources) { + return getConvertorDataSource(DoubleComputer, exchangeRateDataSources); + } + + public static Convertor getConvertorDataSourceDoubleString( + ExchangeRateDataSource exchangeRateDataSource) { + return getConvertorDataSource(DoubleComputer, exchangeRateDataSource); + } + + public static Convertor getConvertorIntegerString( + Collection> exchangeRates) { + return getConvertor(IntegerComputer, exchangeRates); + } + + public static Convertor getConvertorIntegerString( + ExchangeRateValue exchangeRate) { + return getConvertor(IntegerComputer, exchangeRate); + } + + public static Convertor getConvertorDataSourceIntegerString( + Collection> exchangeRateDataSources) { + return getConvertorDataSource(IntegerComputer, exchangeRateDataSources); + } + + public static Convertor getConvertorDataSourceIntegerString( + ExchangeRateDataSource exchangeRateDataSource) { + return getConvertorDataSource(IntegerComputer, exchangeRateDataSource); + } + + // --- + // BACKWARD COMPATIBILITY - CREATION + // --- + /** + * Creates convertor for Double|String values with specified exchange rate + * between two currencies. + * + * @param firstCurrencyExchangeRate first currency + * @param secondCurrencyExchangeRate second currency + * @return convertor + */ + public static Convertor getConvertorDoubleString( + CurrencyValue firstCurrencyExchangeRate, + CurrencyValue secondCurrencyExchangeRate) { + return getConvertorDoubleString(ExchangeRateValue.getExchangeRate(firstCurrencyExchangeRate, secondCurrencyExchangeRate)); + } + + /** + * Creates convertor for Integer|String values with specified exchange rate + * between two currencies. + * + * @param firstCurrencyExchangeRate first currency + * @param secondCurrencyExchangeRate second currency + * @return convertor + */ + public static Convertor getConvertorIntegerString( + CurrencyValue firstCurrencyExchangeRate, + CurrencyValue secondCurrencyExchangeRate) { + return getConvertorIntegerString(ExchangeRateValue.getExchangeRate(firstCurrencyExchangeRate, secondCurrencyExchangeRate)); + } + + // --- + // COMPUTERS + // --- + static final Computer DoubleComputer = new Computer() { + + public void compute(ComputerRequest request, ComputerResponse response) { + response.setResult(request.getInput() * request.getOutputCurrencyRatio() / request.getInputCurrencyRatio()); + } + }; + static final Computer IntegerComputer = new Computer() { + + public void compute(ComputerRequest request, ComputerResponse response) { + response.setResult(request.getInput() * request.getOutputCurrencyRatio() / request.getInputCurrencyRatio()); + } + }; +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution11/src/org/apidesign/apifest08/currency/CurrencyValue.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution11/src/org/apidesign/apifest08/currency/CurrencyValue.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,72 @@ +package org.apidesign.apifest08.currency; + +import java.io.Serializable; + +/** + * Value class, holding an amount of the currency & an identifier of the currency. + * Designed to be an immutable. + * + * Because of a vague definition of types of the both fields, + * the class has generic types, used as types of the fields. + * These types should be immutable classes, too. + * + * @author ked + */ +public final class CurrencyValue implements Serializable { + + private final AmountType amount; + private final IdentifierType identifier; + + private CurrencyValue(AmountType amount, IdentifierType identifier) { + this.amount = amount; + this.identifier = identifier; + } + + public AmountType getAmount() { + return amount; + } + + public IdentifierType getIdentifier() { + return identifier; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final CurrencyValue other = (CurrencyValue) obj; + if (this.amount != other.amount && (this.amount == null || !this.amount.equals(other.amount))) { + return false; + } + if (this.identifier != other.identifier && (this.identifier == null || !this.identifier.equals(other.identifier))) { + return false; + } + return true; + } + + @Override + public int hashCode() { + int hash = 7; + hash = 97 * hash + (this.amount != null ? this.amount.hashCode() : 0); + hash = 97 * hash + (this.identifier != null ? this.identifier.hashCode() : 0); + return hash; + } + + /** + * Creates new instance. + * Generic types of the new instance are derived from types of the parameters. + * + * @param type of the currency amount + * @param type of the currency identifier + * @param amount currency amount + * @param identifier currency identifier + * @return new instance + */ + public static CurrencyValue getCurrencyValue(AmountType amount, IdentifierType identifier) { + return new CurrencyValue(amount, identifier); + } +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution11/src/org/apidesign/apifest08/currency/DateUtil.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution11/src/org/apidesign/apifest08/currency/DateUtil.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,68 @@ +package org.apidesign.apifest08.currency; + +import java.util.Date; + +/** + * Date util helper class. + * @author ked + */ +final class DateUtil { + + private DateUtil() {}; + + static boolean isInRange(Date instant, Date from, Date till) { + if ((from == null || instant.equals(from) || instant.after(from)) && + (till == null || instant.before(till))) { + return true; + } else { + return false; + } + } + + static boolean isRangesOverlapping(Date fromA, Date tillA, Date fromB, Date tillB) { + if ((fromA == null && tillA == null) || (fromB == null && tillB == null)) { + return true; + } + if (fromA != null && isInRange(fromA, fromB, tillB)) { + return true; + } + if (tillA != null && !tillA.equals(fromB) && isInRange(tillA, fromB, tillB)) { + return true; + } + if (fromB != null && isInRange(fromB, fromA, tillA)) { + return true; + } + if (tillB != null && !tillB.equals(fromA) && isInRange(tillB, fromA, tillA)) { + return true; + } + return false; + } + + static Date getRangesIntersectionBottom(Date fromA, Date fromB) { + if (fromA == null) { + return fromB; + } + if (fromB == null) { + return fromA; + } + if (fromA.after(fromB)) { + return fromA; + } else { + return fromB; + } + } + + static Date getRangesIntersectionTop(Date tillA, Date tillB) { + if (tillA == null) { + return tillB; + } + if (tillB == null) { + return tillA; + } + if (tillA.before(tillB)) { + return tillA; + } else { + return tillB; + } + } +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution11/src/org/apidesign/apifest08/currency/ExchangeRateDataSource.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution11/src/org/apidesign/apifest08/currency/ExchangeRateDataSource.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,154 @@ +package org.apidesign.apifest08.currency; + +import java.util.Date; +import org.apidesign.apifest08.currency.ExchangeRateProvider.ExchangeRateRequest; +import org.apidesign.apifest08.currency.ExchangeRateProvider.ExchangeRateResponse; + +/** + * Exchange rate data source. + * + * @author ked + */ +public final class ExchangeRateDataSource { + + private final IdentifierType currencyAIdentifier; + private final IdentifierType currencyBIdentifier; + private final ExchangeRateProvider exchangeRateProvider; + private final Date validFrom; + private final Date validTill; + + private ExchangeRateDataSource( + IdentifierType currencyAIdentifier, + IdentifierType currencyBIdentifier, + ExchangeRateProvider exchangeRateProvider, + Date validFrom, + Date validTill) { + if (currencyAIdentifier == null || + currencyBIdentifier == null || + currencyAIdentifier.equals(currencyBIdentifier)) { + throw new IllegalArgumentException("Inappropriate exchange rates' identifiers!"); + } + if (validFrom != null && + validTill != null && + !validTill.after(validFrom)) { + throw new IllegalArgumentException("Inappropriate exchange rate validity!"); + } + + this.currencyAIdentifier = currencyAIdentifier; + this.currencyBIdentifier = currencyBIdentifier; + this.exchangeRateProvider = exchangeRateProvider; + this.validFrom = validFrom; + this.validTill = validTill; + } + + public IdentifierType getCurrencyAIdentifier() { + return currencyAIdentifier; + } + + public IdentifierType getCurrencyBIdentifier() { + return currencyBIdentifier; + } + + ExchangeRateProvider getExchangeRateProvider() { + return exchangeRateProvider; + } + + public Date getValidFrom() { + return validFrom != null ? (Date) validFrom.clone() : null; + } + + public Date getValidTill() { + return validTill != null ? (Date) validTill.clone() : null; + } + + public ExchangeRateValue getExchangeRate() { + return getExchangeRate(new Date()); // System.currentTimeMillis() + } + + public ExchangeRateValue getExchangeRate(Date instant) { + ExchangeRateRequest request = + new ExchangeRateRequest(); + ExchangeRateResponse response = + new ExchangeRateResponse(); + + request.setCurrencyAIdentifier(currencyAIdentifier); + request.setCurrencyBIdentifier(currencyBIdentifier); + request.setInstant(instant); + + exchangeRateProvider.getExchangeRate(request, response); + + ExchangeRateValue result = response.getExchangeRate(); + if (result.getCurrencyA().getIdentifier().equals(currencyAIdentifier) && + result.getCurrencyB().getIdentifier().equals(currencyBIdentifier)) { + return result; + } else { + throw new IllegalStateException("Data source's provider returned inappropriate exchange rate!"); + } + } + + public static ExchangeRateDataSource getExchangeRateDataSource( + IdentifierType currencyAIdentifier, + IdentifierType currencyBIdentifier, + ExchangeRateProvider exchangeRateProvider) { + return getExchangeRateDataSource( + currencyAIdentifier, + currencyBIdentifier, + exchangeRateProvider, + null, + null); + } + + public static ExchangeRateDataSource getExchangeRateDataSource( + IdentifierType currencyAIdentifier, + IdentifierType currencyBIdentifier, + ExchangeRateProvider exchangeRateProvider, + Date validFrom, + Date validTill) { + return new ExchangeRateDataSource( + currencyAIdentifier, + currencyBIdentifier, + exchangeRateProvider, + validFrom, + validTill); + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final ExchangeRateDataSource other = + (ExchangeRateDataSource) obj; + if (this.currencyAIdentifier != other.currencyAIdentifier && + (this.currencyAIdentifier == null || !this.currencyAIdentifier.equals(other.currencyAIdentifier))) { + return false; + } + if (this.currencyBIdentifier != other.currencyBIdentifier && + (this.currencyBIdentifier == null || !this.currencyBIdentifier.equals(other.currencyBIdentifier))) { + return false; + } + if (this.exchangeRateProvider != other.exchangeRateProvider && + (this.exchangeRateProvider == null || !this.exchangeRateProvider.equals(other.exchangeRateProvider))) { + return false; + } + if (this.validFrom != other.validFrom && (this.validFrom == null || !this.validFrom.equals(other.validFrom))) { + return false; + } + if (this.validTill != other.validTill && (this.validTill == null || !this.validTill.equals(other.validTill))) { + return false; + } + return true; + } + + @Override + public int hashCode() { + int hash = 7; + hash = 83 * hash + (this.currencyAIdentifier != null ? this.currencyAIdentifier.hashCode() : 0); + hash = 83 * hash + (this.currencyBIdentifier != null ? this.currencyBIdentifier.hashCode() : 0); + hash = 83 * hash + (this.exchangeRateProvider != null ? this.exchangeRateProvider.hashCode() : 0); + return hash; + } +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution11/src/org/apidesign/apifest08/currency/ExchangeRateProvider.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution11/src/org/apidesign/apifest08/currency/ExchangeRateProvider.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,66 @@ +package org.apidesign.apifest08.currency; + +import java.util.Date; + +/** + * Exchange rate provider. + * + * @author ked + * @see http://wiki.apidesign.org/wiki/APIDesignPatterns:ResponseReply + */ +public interface ExchangeRateProvider { + + public void getExchangeRate( + ExchangeRateRequest request, + ExchangeRateResponse response); + + public final class ExchangeRateRequest { + + private IdentifierType currencyAIdentifier; + private IdentifierType currencyBIdentifier; + private Date instant; + + ExchangeRateRequest() { + } + + public IdentifierType getCurrencyAIdentifier() { + return currencyAIdentifier; + } + + void setCurrencyAIdentifier(IdentifierType currencyAIdentifier) { + this.currencyAIdentifier = currencyAIdentifier; + } + + public IdentifierType getCurrencyBIdentifier() { + return currencyBIdentifier; + } + + void setCurrencyBIdentifier(IdentifierType currencyBIdentifier) { + this.currencyBIdentifier = currencyBIdentifier; + } + + public Date getInstant() { + return instant; + } + + void setInstant(Date instant) { + this.instant = instant; + } + } + + public final class ExchangeRateResponse { + + private ExchangeRateValue exchangeRate; + + ExchangeRateResponse() { + } + + ExchangeRateValue getExchangeRate() { + return exchangeRate; + } + + public void setExchangeRate(ExchangeRateValue exchangeRate) { + this.exchangeRate = exchangeRate; + } + } +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution11/src/org/apidesign/apifest08/currency/ExchangeRateValue.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution11/src/org/apidesign/apifest08/currency/ExchangeRateValue.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,78 @@ +package org.apidesign.apifest08.currency; + +import java.io.Serializable; + +/** + * Value class, holding an exchange rate between two currencies. + * Designed to be an immutable. + * + * @author ked + */ +public final class ExchangeRateValue implements Serializable { + + private final CurrencyValue currencyA; + private final CurrencyValue currencyB; + + private ExchangeRateValue( + CurrencyValue currencyA, + CurrencyValue currencyB) { + if (currencyA.getIdentifier() == null || + currencyB.getIdentifier() == null || + currencyA.getIdentifier().equals(currencyB)) { + throw new IllegalArgumentException("Inappropriate exchange rates' identifiers!"); + } + + this.currencyA = currencyA; + this.currencyB = currencyB; + } + + public CurrencyValue getCurrencyA() { + return currencyA; + } + + public CurrencyValue getCurrencyB() { + return currencyB; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final ExchangeRateValue other = (ExchangeRateValue) obj; + if (this.currencyA != other.currencyA && (this.currencyA == null || !this.currencyA.equals(other.currencyA))) { + return false; + } + if (this.currencyB != other.currencyB && (this.currencyB == null || !this.currencyB.equals(other.currencyB))) { + return false; + } + return true; + } + + @Override + public int hashCode() { + int hash = 3; + hash = 71 * hash + (this.currencyA != null ? this.currencyA.hashCode() : 0); + hash = 71 * hash + (this.currencyB != null ? this.currencyB.hashCode() : 0); + return hash; + } + + /** + * Creates new instance. + * Generic types of the new instance are derived from types of the parameters. + * + * @param type of the currency amount + * @param type of the currency identifier + * @param currencyA one currency of the exchange rate + * @param currencyB another currency of the exchange rate + * @return new instance + */ + public static ExchangeRateValue getExchangeRate( + CurrencyValue currencyA, + CurrencyValue currencyB) { + return new ExchangeRateValue(currencyA, currencyB); + } +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution11/src/org/apidesign/apifest08/currency/StaticExchangeRateProvider.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution11/src/org/apidesign/apifest08/currency/StaticExchangeRateProvider.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,48 @@ +package org.apidesign.apifest08.currency; + +/** + * Static exchange rate provider. + * + * @author ked + */ +final class StaticExchangeRateProvider implements ExchangeRateProvider { + + final ExchangeRateValue exchangeRate; + + private StaticExchangeRateProvider(ExchangeRateValue exchangeRate) { + this.exchangeRate = exchangeRate; + } + + public void getExchangeRate(ExchangeRateRequest request, ExchangeRateResponse response) { + response.setExchangeRate(exchangeRate); + } + + static StaticExchangeRateProvider getStaticExchangeRateProvider(ExchangeRateValue exchangeRate) { + return new StaticExchangeRateProvider(exchangeRate); + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + + if (getClass() != obj.getClass()) { + return false; + } + + final StaticExchangeRateProvider other = (StaticExchangeRateProvider) obj; + if (this.exchangeRate != other.exchangeRate && (this.exchangeRate == null || !this.exchangeRate.equals(other.exchangeRate))) { + return false; + } + + return true; + } + + @Override + public int hashCode() { + int hash = 7; + hash = 67 * hash + (this.exchangeRate != null ? this.exchangeRate.hashCode() : 0); + return hash; + } +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution11/test/org/apidesign/apifest08/test/Task1Test.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution11/test/org/apidesign/apifest08/test/Task1Test.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,157 @@ +package org.apidesign.apifest08.test; + +import junit.framework.TestCase; +import org.apidesign.apifest08.currency.Convertor; +import org.apidesign.apifest08.currency.CurrencyValue; + +/** Finish the Convertor API, and then write bodies of methods inside + * of this class to match the given tasks. To fullfil your task, use the + * API define in the org.apidesign.apifest08.currency package. + * Do not you reflection, or other hacks as your code + * shall run without any runtime permissions. + */ +public class Task1Test extends TestCase { + public Task1Test(String testName) { + super(testName); + } + + @Override + protected void setUp() throws Exception { + } + + @Override + protected void tearDown() throws Exception { + } + + // + // Imagine that there are three parts of the whole system: + // 1. there is someone who knows the current exchange rate + // 2. there is someone who wants to do the conversion + // 3. there is the API between 1. and 2. which allows them to communicate + // Please design such API + // + + /** Create convertor that understands two currencies, CZK and + * USD. Make 1 USD == 17 CZK. This is a method provided for #1 group - + * e.g. those that know the exchange rate. They somehow need to create + * the objects from the API and tell them the exchange rate. The API itself + * knows nothing about any rates, before the createCZKtoUSD method is called. + * + * Creation of the convertor shall not require subclassing of any class + * or interface on the client side. + * + * @return prepared convertor ready for converting USD to CZK and CZK to USD + */ + public static Convertor createCZKtoUSD() { + return Convertor.getConvertorDoubleString( + CurrencyValue.getCurrencyValue(1d, "USD"), + CurrencyValue.getCurrencyValue(17d, "CZK") + ); + } + + /** Create convertor that understands two currencies, CZK and + * SKK. Make 100 SKK == 80 CZK. Again this is method for the #1 group - + * it knows the exchange rate, and needs to use the API to create objects + * with the exchange rate. Anyone shall be ready to call this method without + * any other method being called previously. The API itself shall know + * nothing about any rates, before this method is called. + * + * Creation of the convertor shall not require subclassing of any class + * or interface on the client side. + * + * @return prepared convertor ready for converting SKK to CZK and CZK to SKK + */ + public static Convertor createSKKtoCZK() { + return Convertor.getConvertorDoubleString( + CurrencyValue.getCurrencyValue(100d, "SKK"), + CurrencyValue.getCurrencyValue(80d, "CZK") + ); + } + + // + // now the methods for group #2 follow: + // this group knows nothing about exchange rates, but knows how to use + // the API to do conversions. It somehow (by calling one of the factory + // methods) gets objects from the API and uses them to do the conversions. + // + + /** Use the convertor from createCZKtoUSD method and do few conversions + * with it. + */ + public void testCurrencyCZKUSD() throws Exception { + Convertor c = createCZKtoUSD(); + + CurrencyValue result; + + // convert $5 to CZK using c: + // assertEquals("Result is 85 CZK"); + result = c.convert("CZK", CurrencyValue.getCurrencyValue(5d, "USD")); + assertEquals(CurrencyValue.getCurrencyValue(85d, "CZK"), result); + + // convert $8 to CZK + // assertEquals("Result is 136 CZK"); + result = c.convert("CZK", CurrencyValue.getCurrencyValue(8d, "USD")); + assertEquals(CurrencyValue.getCurrencyValue(136d, "CZK"), result); + + // convert 1003CZK to USD + // assertEquals("Result is 59 USD"); + result = c.convert("USD", CurrencyValue.getCurrencyValue(1003d, "CZK")); + assertEquals(CurrencyValue.getCurrencyValue(59d, "USD"), result); + } + + /** Use the convertor from createSKKtoCZK method and do few conversions + * with it. + */ + public void testCurrencySKKCZK() throws Exception { + Convertor c = createSKKtoCZK(); + + CurrencyValue result; + + // convert 16CZK using c: + // assertEquals("Result is 20 SKK"); + result = c.convert("SKK", CurrencyValue.getCurrencyValue(16d, "CZK")); + assertEquals(CurrencyValue.getCurrencyValue(20d, "SKK"), result); + + // convert 500SKK to CZK + // assertEquals("Result is 400 CZK"); + result = c.convert("CZK", CurrencyValue.getCurrencyValue(500d, "SKK")); + assertEquals(CurrencyValue.getCurrencyValue(400d, "CZK"), result); + } + + /** Verify that the CZK to USD convertor knows nothing about SKK. + */ + public void testCannotConvertToSKKwithCZKUSDConvertor() throws Exception { + Convertor c = createCZKtoUSD(); + try { + // convert $5 to SKK, the API shall say this is not possible + c.convert("SKK", CurrencyValue.getCurrencyValue(16d, "CZK")); + fail("Should not convert"); + } catch (Exception e) { + } + try { + // convert 500 SKK to CZK, the API shall say this is not possible + c.convert("CZK", CurrencyValue.getCurrencyValue(500d, "SKK")); + fail("Should not convert"); + } catch (Exception e) { + } + + } + + /** Verify that the CZK to SKK convertor knows nothing about USD. + */ + public void testCannotConvertToUSDwithSKKCZKConvertor() throws Exception { + Convertor c = createSKKtoCZK(); + try { + // convert $5 to SKK, the API shall say this is not possible + c.convert("SKK", CurrencyValue.getCurrencyValue(5d, "USD")); + fail("Should not convert"); + } catch (Exception e) { + } + try { + // convert 500 CZK to USD, the API shall say this is not possible + c.convert("USD", CurrencyValue.getCurrencyValue(500d, "CZK")); + fail("Should not convert"); + } catch (Exception e) { + } + } +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution11/test/org/apidesign/apifest08/test/Task2Test.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution11/test/org/apidesign/apifest08/test/Task2Test.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,140 @@ +package org.apidesign.apifest08.test; + +import java.util.ArrayList; +import java.util.Collection; +import junit.framework.TestCase; +import org.apidesign.apifest08.currency.Convertor; +import org.apidesign.apifest08.currency.CurrencyValue; +import org.apidesign.apifest08.currency.ExchangeRateValue; + +/** There are many currencies around the world and many banks manipulate + * with more than one or two at the same time. As banks are usually the + * best paying clients, which is true even in case of your Convertor API, + * it is reasonable to listen to their requests. + *

+ * The quest for today is to enhance your existing convertor API to hold + * information about many currencies and allow conversions between any of them. + * Also, as conversion rates for diferent currencies usually arise from various + * bank departments, there is another important need. There is a need to + * compose two convertors into one by merging all the information about + * currencies they know about. + */ +public class Task2Test extends TestCase { + + public Task2Test(String testName) { + super(testName); + } + + @Override + protected void setUp() throws Exception { + } + + @Override + protected void tearDown() throws Exception { + } + + // As in Task1Test, keep in mind, that there are three parts + // of the whole system: + // 1. there is someone who knows the current exchange rate + // 2. there is someone who wants to do the conversion + // 3. there is the API between 1. and 2. which allows them to communicate + // + // Please backward compatibly enhance your existing API to support following + // usecases: + // + /** Create convertor that understands two currencies, CZK and + * SKK. Make 100 SKK == 75 CZK. This is method for the group of users that + * knows the exchange rate, and needs to use the API to create objects + * with the exchange rate. Anyone shall be ready to call this method without + * any other method being called previously. The API itself shall know + * nothing about any rates, before this method is called. + */ + public static Convertor createTripleConvertor() { + // Rates: 1USD = 15CZK + // Rates: 1USD = 20SKK + // Rates: 75CZK = 100SKK + Collection> exchangeRates = + new ArrayList>(); + exchangeRates.add(ExchangeRateValue.getExchangeRate( + CurrencyValue.getCurrencyValue(1d, "USD"), + CurrencyValue.getCurrencyValue(15d, "CZK"))); + exchangeRates.add(ExchangeRateValue.getExchangeRate( + CurrencyValue.getCurrencyValue(1d, "USD"), + CurrencyValue.getCurrencyValue(20d, "SKK"))); + exchangeRates.add(ExchangeRateValue.getExchangeRate( + CurrencyValue.getCurrencyValue(75d, "CZK"), + CurrencyValue.getCurrencyValue(100d, "SKK"))); + return Convertor.getConvertorDoubleString(exchangeRates); + } + + /** Define convertor that understands three currencies. Use it. + */ + public void testConvertorForUSDandCZKandSKK() throws Exception { + Convertor c = createTripleConvertor(); + + CurrencyValue result; + // convert $5 to CZK using c: + // assertEquals("Result is 75 CZK"); + result = c.convert("CZK", CurrencyValue.getCurrencyValue(5d, "USD")); + assertEquals(CurrencyValue.getCurrencyValue(75d, "CZK"), result); + + // convert $5 to SKK using c: + // assertEquals("Result is 100 SKK"); + result = c.convert("SKK", CurrencyValue.getCurrencyValue(5d, "USD")); + assertEquals(CurrencyValue.getCurrencyValue(100d, "SKK"), result); + + // convert 200SKK to CZK using c: + // assertEquals("Result is 150 CZK"); + result = c.convert("CZK", CurrencyValue.getCurrencyValue(200d, "SKK")); + assertEquals(CurrencyValue.getCurrencyValue(150d, "CZK"), result); + + // convert 200SKK to USK using c: + // assertEquals("Result is 10 USD"); + result = c.convert("USD", CurrencyValue.getCurrencyValue(200d, "SKK")); + assertEquals(CurrencyValue.getCurrencyValue(10d, "USD"), result); + } + + /** Merge all currency rates of convertor 1 with convertor 2. + * Implement this using your API, preferably this method just delegates + * into some API method which does the actual work, without requiring + * API clients to code anything complex. + */ + public static Convertor merge(Convertor one, Convertor two) { + return Convertor.mergeConvertorsDoubleString(one, two); + } + + /** Join the convertors from previous task, Task1Test and show that it + * can be used to do reasonable conversions. + */ + public void testConvertorComposition() throws Exception { + Convertor c = merge( + Task1Test.createCZKtoUSD(), + Task1Test.createSKKtoCZK()); + + CurrencyValue result; + // convert $5 to CZK using c: + // assertEquals("Result is 85 CZK"); + result = c.convert("CZK", CurrencyValue.getCurrencyValue(5d, "USD")); + assertEquals(CurrencyValue.getCurrencyValue(85d, "CZK"), result); + + // convert $8 to CZK using c: + // assertEquals("Result is 136 CZK"); + result = c.convert("CZK", CurrencyValue.getCurrencyValue(8d, "USD")); + assertEquals(CurrencyValue.getCurrencyValue(136d, "CZK"), result); + + // convert 1003CZK to USD using c: + // assertEquals("Result is 59 USD"); + result = c.convert("USD", CurrencyValue.getCurrencyValue(1003d, "CZK")); + assertEquals(CurrencyValue.getCurrencyValue(59d, "USD"), result); + + // convert 16CZK using c: + // assertEquals("Result is 20 SKK"); + result = c.convert("SKK", CurrencyValue.getCurrencyValue(16d, "CZK")); + assertEquals(CurrencyValue.getCurrencyValue(20d, "SKK"), result); + + // convert 500SKK to CZK using c: + // assertEquals("Result is 400 CZK"); + result = c.convert("CZK", CurrencyValue.getCurrencyValue(500d, "SKK")); + assertEquals(CurrencyValue.getCurrencyValue(400d, "CZK"), result); + } +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution11/test/org/apidesign/apifest08/test/Task3Test.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution11/test/org/apidesign/apifest08/test/Task3Test.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,136 @@ +package org.apidesign.apifest08.test; + +import junit.framework.TestCase; +import org.apidesign.apifest08.currency.Convertor; +import org.apidesign.apifest08.currency.CurrencyValue; +import org.apidesign.apifest08.currency.ExchangeRateDataSource; +import org.apidesign.apifest08.currency.ExchangeRateProvider; +import org.apidesign.apifest08.currency.ExchangeRateProvider.ExchangeRateRequest; +import org.apidesign.apifest08.currency.ExchangeRateProvider.ExchangeRateResponse; +import org.apidesign.apifest08.currency.ExchangeRateValue; + +/** The exchange rates are not always the same. They are changing. Day by day, + * hour by hour, minute by minute. For every bank it is important to always + * have the actual exchange rate available in the system. That is why let's + * create a pluggable convertor that will always have up to date value of its + * exchange rate. + *

+ * The quest for today is to allow 3rd party developer to write a convertor + * that adjusts its exchange rate everytime it is queried. This convertor is + * written by independent vendor, the vendor knows only your Convertor API, + * he does not know how the whole system looks and how the convertor is supposed + * to be used. + */ +public class Task3Test extends TestCase { + + public Task3Test(String testName) { + super(testName); + } + + @Override + protected void setUp() throws Exception { + } + + @Override + protected void tearDown() throws Exception { + } + + // Backward compatibly enhance your existing API to support following + // usecases: + // + /** Without knowing anything about the surrounding system, write an + * implementation of convertor that will return different rates everytime + * it is queried. Convert USD to CZK and vice versa. Start with the rate of + * 1USD = 16CZK and adjust it in favor of CZK by 0.01 CZK with every query. + * As soon as you reach 1USD = 15CZK adjust it by 0.01 CZK in favor of USD + * until you reach 1USD = 16CZK + * + * @return new instance of "online" USD and CZK convertor starting with rate 1USD = 16CZK + */ + public static Convertor createOnlineCZKUSDConvertor() { + // initial rate: 1USD = 16CZK + // 2nd query 1USD = 15.99CZK + // 3rd query 1USD = 15.98CZK + // until 1USD = 15.00CZK + // then 1USD = 15.01CZK + // then 1USD = 15.02CZK + // and so on and on up to 1USD = 16CZK + // and then another round to 15, etc. + return Convertor.getConvertorDataSourceDoubleString( + ExchangeRateDataSource.getExchangeRateDataSource( + "USD", "CZK", new ExchangeRateProvider() { + + double currentRate = 16d; + double step; + + public void getExchangeRate(ExchangeRateRequest request, + ExchangeRateResponse response) { + if ((request.getCurrencyAIdentifier().equals("CZK") && request.getCurrencyBIdentifier().equals("USD")) || + (request.getCurrencyAIdentifier().equals("USD") && request.getCurrencyBIdentifier().equals("CZK"))) { + response.setExchangeRate(ExchangeRateValue.getExchangeRate( + CurrencyValue.getCurrencyValue(1d, "USD"), + CurrencyValue.getCurrencyValue(currentRate, "CZK"))); + + if (currentRate == 16d) { + step = -0.01; + } + if (currentRate == 15d) { + step = 0.01; + } + currentRate += step; + } else { + throw new IllegalArgumentException("No exchange rate for requested currencies!"); + } + } + })); + } + + public void testFewQueriesForOnlineConvertor() { + Convertor c = createOnlineCZKUSDConvertor(); + doFewQueriesForOnlineConvertor(c); + } + + static void doFewQueriesForOnlineConvertor(Convertor c) { + CurrencyValue result; + // convert $5 to CZK using c: + //assertEquals("Result is 80 CZK"); + result = c.convert("CZK", CurrencyValue.getCurrencyValue(5d, "USD")); + assertEquals(CurrencyValue.getCurrencyValue(80d, "CZK"), result); + + // convert $8 to CZK using c: + //assertEquals("Result is 127.92 CZK"); + result = c.convert("CZK", CurrencyValue.getCurrencyValue(8d, "USD")); + assertEquals(CurrencyValue.getCurrencyValue(127.92d, "CZK"), result); + + // convert $1 to CZK using c: + //assertEquals("Result is 15.98 CZK"); + result = c.convert("CZK", CurrencyValue.getCurrencyValue(1d, "USD")); + assertEquals(CurrencyValue.getCurrencyValue(15.98d, "CZK"), result); + + // convert 15.97CZK to USD using c: + //assertEquals("Result is 1$"); + result = c.convert("USD", CurrencyValue.getCurrencyValue(15.97d, "CZK")); + assertEquals(CurrencyValue.getCurrencyValue(1d, "USD"), result); + } + + /** Join the convertors and show they behave sane. + */ + public void testOnlineConvertorComposition() throws Exception { + Convertor c = Task2Test.merge( + createOnlineCZKUSDConvertor(), + Task1Test.createSKKtoCZK()); + + CurrencyValue result; + // convert 16CZK to SKK using c: + // assertEquals("Result is 20 SKK"); + result = c.convert("SKK", CurrencyValue.getCurrencyValue(16d, "CZK")); + assertEquals(CurrencyValue.getCurrencyValue(20d, "SKK"), result); + + // convert 500SKK to CZK using c: + // assertEquals("Result is 400 CZK"); + result = c.convert("CZK", CurrencyValue.getCurrencyValue(500d, "SKK")); + assertEquals(CurrencyValue.getCurrencyValue(400d, "CZK"), result); + + doFewQueriesForOnlineConvertor(c); + } +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution11/test/org/apidesign/apifest08/test/Task4Test.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution11/test/org/apidesign/apifest08/test/Task4Test.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,194 @@ +package org.apidesign.apifest08.test; + +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; +import junit.framework.TestCase; +import org.apidesign.apifest08.currency.Convertor; +import org.apidesign.apifest08.currency.CurrencyValue; +import org.apidesign.apifest08.currency.ExchangeRateValue; + +/** The exchange rates are not always the same. They are changing. However + * as in order to predict the future, one needs to understand own past. That is + * why it is important to know the exchange rate as it was at any time during + * the past. + *

+ * Today's quest is to enhance the convertor API to deal with dates. + * One shall be able to convert a currency at any date. Each currencies rate shall + * be associated with a range between two Date objects. In order + * to keep compatibility with old API that knew nothing about dates, the + * rates associated then are applicable "for eternity". Any use of existing + * convert methods that do not accept a Date argument, uses the current + * System.currentTimeMillis() as default date. + */ +public class Task4Test extends TestCase { + public Task4Test(String testName) { + super(testName); + } + + @Override + protected void setUp() throws Exception { + } + + @Override + protected void tearDown() throws Exception { + } + + // Backward compatibly enhance your existing API to support following + // usecases: + // + + /** Takes a convertor with any rates associated and creates new convertor + * that returns the same values as the old one for time between from to till. + * Otherwise it returns no results. This is just a helper method that + * shall call some real one in the API. + * + * @param old existing convertor + * @param from initial date (inclusive) + * @param till final date (exclusive) + * @return new convertor + */ + public static Convertor limitTo(Convertor old, Date from, Date till) { + return old.limitConvertor(from, till); + } + + + public void testCompositionOfLimitedConvertors() throws Exception { + Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT")); + cal.clear(); + cal.set(2008, 9, 1, 0, 0); + Date d1 = cal.getTime(); // 2008-10-01 0:00 GMT + cal.set(2008, 9, 2, 0, 0); + Date d2 = cal.getTime(); // 2008-10-02 0:00 GMT + cal.set(2008, 9, 3, 0, 0); + Date d3 = cal.getTime(); // 2008-10-03 0:00 GMT + + Convertor c = Task2Test.merge( + limitTo(Task1Test.createCZKtoUSD(), d1, d2), + limitTo(Task1Test.createSKKtoCZK(), d2, d3) + ); + + CurrencyValue result; + // convert $5 to CZK using c: + // cannot convert as no rate is applicable to current date + try { + c.convert("CZK", CurrencyValue.getCurrencyValue(5d, "USD")); + fail("Should not convert"); + } catch (Exception e) { + } + + // convert $8 to CZK using c: + // cannot convert as no rate is applicable to current date + try { + c.convert("CZK", CurrencyValue.getCurrencyValue(8d, "USD")); + fail("Should not convert"); + } catch (Exception e) { + } + + // convert 1003CZK to USD using c: + // cannot convert as no rate is applicable to current date + try { + c.convert("USD", CurrencyValue.getCurrencyValue(1003d, "CZK")); + fail("Should not convert"); + } catch (Exception e) { + } + + // convert 16CZK using c: + // cannot convert as no rate is applicable to current date + try { + c.convert("SKK", CurrencyValue.getCurrencyValue(16d, "CZK")); + fail("Should not convert"); + } catch (Exception e) { + } + + // convert 500SKK to CZK using c: + // cannot convert as no rate is applicable to current date + try { + c.convert("CZK", CurrencyValue.getCurrencyValue(500d, "SKK")); + fail("Should not convert"); + } catch (Exception e) { + } + + // convert $5 to CZK using c at 2008-10-01 6:00 GMT: + // assertEquals("Result is 85 CZK"); + cal.set(2008, 9, 1, 6, 0); + result = c.convert("CZK", CurrencyValue.getCurrencyValue(5d, "USD"), cal.getTime()); + assertEquals(CurrencyValue.getCurrencyValue(85d, "CZK"), result); + + // convert $8 to CZK using c at 2008-10-01 6:00 GMT: + // assertEquals("Result is 136 CZK"); + cal.set(2008, 9, 1, 6, 0); + result = c.convert("CZK", CurrencyValue.getCurrencyValue(8d, "USD"), cal.getTime()); + assertEquals(CurrencyValue.getCurrencyValue(136d, "CZK"), result); + + // convert 1003CZK to USD using c at 2008-10-01 6:00 GMT: + // assertEquals("Result is 59 USD"); + cal.set(2008, 9, 1, 6, 0); + result = c.convert("USD", CurrencyValue.getCurrencyValue(1003d, "CZK"), cal.getTime()); + assertEquals(CurrencyValue.getCurrencyValue(59d, "USD"), result); + + // convert 16CZK using c at 2008-10-02 9:00 GMT: + // assertEquals("Result is 20 SKK"); + cal.set(2008, 9, 2, 9, 0); + result = c.convert("SKK", CurrencyValue.getCurrencyValue(16d, "CZK"), cal.getTime()); + assertEquals(CurrencyValue.getCurrencyValue(20d, "SKK"), result); + + // convert 500SKK to CZK using c at 2008-10-02 9:00 GMT: + // assertEquals("Result is 400 CZK"); + cal.set(2008, 9, 2, 9, 0); + result = c.convert("CZK", CurrencyValue.getCurrencyValue(500d, "SKK"), cal.getTime()); + assertEquals(CurrencyValue.getCurrencyValue(400d, "CZK"), result); + + // convert 500SKK to CZK using c at 2008-10-01 6:00 GMT: + // cannot convert as no rate is applicable to current date + cal.set(2008, 9, 1, 6, 0); + try { + result = c.convert("CZK", CurrencyValue.getCurrencyValue(500d, "SKK"), cal.getTime()); + fail("Should not convert"); + } catch (Exception e) { + } + } + + /** Create convertor that understands two currencies, CZK and + * SKK. Make 100 SKK == 90 CZK. + * + * @return prepared convertor ready for converting SKK to CZK and CZK to SKK + */ + public static Convertor createSKKtoCZK2() { + return Convertor.getConvertorDoubleString( + ExchangeRateValue.getExchangeRate( + CurrencyValue.getCurrencyValue(100d, "SKK"), + CurrencyValue.getCurrencyValue(90d, "CZK"))); + } + + public void testDateConvetorWithTwoDifferentRates() throws Exception { + Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT")); + cal.clear(); + cal.set(2008, 9, 1, 0, 0); + Date d1 = cal.getTime(); // 2008-10-01 0:00 GMT + cal.set(2008, 9, 2, 0, 0); + Date d2 = cal.getTime(); // 2008-10-02 0:00 GMT + cal.set(2008, 9, 3, 0, 0); + Date d3 = cal.getTime(); // 2008-10-03 0:00 GMT + + Convertor c = Task2Test.merge( + limitTo(createSKKtoCZK2(), d1, d2), + limitTo(Task1Test.createSKKtoCZK(), d2, d3) + ); + + CurrencyValue result; + // convert 500SKK to CZK using c at 2008-10-02 9:00 GMT: + // assertEquals("Result is 400 CZK"); + cal.set(2008, 9, 2, 9, 0); + result = c.convert("CZK", CurrencyValue.getCurrencyValue(500d, "SKK"), cal.getTime()); + assertEquals(CurrencyValue.getCurrencyValue(400d, "CZK"), result); + + // convert 500SKK to CZK using c at 2008-10-01 6:00 GMT: + // assertEquals("Result is 450 CZK"); + cal.set(2008, 9, 1, 6, 0); + result = c.convert("CZK", CurrencyValue.getCurrencyValue(500d, "SKK"), cal.getTime()); + assertEquals(CurrencyValue.getCurrencyValue(450d, "CZK"), result); + } + +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution13/build.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution13/build.xml Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,69 @@ + + + + + + Builds, tests, and runs the project. + + + diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution13/nbproject/build-impl.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution13/nbproject/build-impl.xml Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,642 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set src.dir + Must set test.src.dir + Must set build.dir + Must set dist.dir + Must set build.classes.dir + Must set dist.javadoc.dir + Must set build.test.classes.dir + Must set build.test.results.dir + Must set build.classes.excludes + Must set dist.jar + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + + + + + + java -cp "${run.classpath.with.dist.jar}" ${main.class} + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + java -jar "${dist.jar.resolved}" + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set run.class + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set debug.class + + + + + Must set fix.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + Some tests failed; see details above. + + + + + + + + + Must select some files in the IDE or set test.includes + + + + Some tests failed; see details above. + + + + + Must select one file in the IDE or set test.class + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + + + + + + + + + + + diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution13/nbproject/genfiles.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution13/nbproject/genfiles.properties Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,8 @@ +build.xml.data.CRC32=2ab820eb +build.xml.script.CRC32=58a52595 +build.xml.stylesheet.CRC32=be360661 +# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. +# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. +nbproject/build-impl.xml.data.CRC32=de21ce77 +nbproject/build-impl.xml.script.CRC32=0903858a +nbproject/build-impl.xml.stylesheet.CRC32=e55b27f5 diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution13/nbproject/project.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution13/nbproject/project.properties Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,68 @@ +application.title=currency +application.vendor=apidesign.org +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.tab-size=8 +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.text-limit-width=80 +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.usedProfile=default +build.classes.dir=${build.dir}/classes +build.classes.excludes=**/*.java,**/*.form +# This directory is removed when the project is cleaned: +build.dir=build +build.generated.dir=${build.dir}/generated +# Only compile against the classpath explicitly listed here: +build.sysclasspath=ignore +build.test.classes.dir=${build.dir}/test/classes +build.test.results.dir=${build.dir}/test/results +debug.classpath=\ + ${run.classpath} +debug.test.classpath=\ + ${run.test.classpath} +# This directory is removed when the project is cleaned: +dist.dir=dist +dist.jar=${dist.dir}/currency.jar +dist.javadoc.dir=${dist.dir}/javadoc +excludes= +file.reference.junit-4.4.jar=../../libs/junit-4.4.jar +file.reference.src-apifest08=.. +includes=** +jar.compress=false +javac.classpath= +# Space-separated list of extra javac options +javac.compilerargs=-Xlint:unchecked +javac.deprecation=false +javac.source=1.5 +javac.target=1.5 +javac.test.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir}:\ + ${file.reference.junit-4.4.jar} +javadoc.additionalparam= +javadoc.author=false +javadoc.encoding= +javadoc.noindex=false +javadoc.nonavbar=false +javadoc.notree=false +javadoc.private=false +javadoc.splitindex=true +javadoc.use=true +javadoc.version=false +javadoc.windowtitle= +jnlp.codebase.type=local +jnlp.codebase.url=file:/home/jarda/src/apifest08/currency/dist +jnlp.descriptor=application +jnlp.enabled=false +jnlp.offline-allowed=false +jnlp.signed=false +meta.inf.dir=${src.dir}/META-INF +platform.active=default_platform +run.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +# Space-separated list of JVM arguments used when running the project +# (you may also define separate properties like run-sys-prop.name=value instead of -Dname=value +# or test-sys-prop.name=value to set system properties for unit tests): +run.jvmargs= +run.test.classpath=\ + ${javac.test.classpath}:\ + ${build.test.classes.dir} +src.dir=src +test.src.dir=test diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution13/nbproject/project.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution13/nbproject/project.xml Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,16 @@ + + + org.netbeans.modules.java.j2seproject + + + Currency Convertor Solution 13 + 1.6.5 + + + + + + + + + diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution13/src/org/apidesign/apifest08/currency/ConversionNotSupportedException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution13/src/org/apidesign/apifest08/currency/ConversionNotSupportedException.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,85 @@ +package org.apidesign.apifest08.currency; + +/** + * Conversion not suported exception. This expecption may optionaly describe which conversion was required and failed. + * Required conversion can be found in {@link #getFromCurrecyCode() } and {@link #getToCurrecyCode() }. + * + * @author arnostvalicek + * @since version2 + */ +public class ConversionNotSupportedException extends ConvertorException { + String from; + String to; + boolean reversed; + + public ConversionNotSupportedException() { + super(); + } + + public ConversionNotSupportedException(String message) { + super(message); + } + + public ConversionNotSupportedException(String message, Throwable cause) { + super(message, cause); + } + + public ConversionNotSupportedException(Throwable cause) { + super(cause); + } + + /** + * Create exception witd additional information about currencies which are not supported in coversion. + * @param from Code of source currency. + * @param to Code of target currency. + * @param twoWay Set to false if From->To is not supported. + * Set to true if both ways From->To and To->From conversions are not supported. + * + */ + public ConversionNotSupportedException(String from, String to, boolean twoWay) { + this.from = from; + this.to = to; + this.reversed = true; + } + + @Override + public String toString() { + if (from!=null && to !=null) { + if (reversed) { + return "Neither conversion nor reverted conversion from " + from + " to " + to + " is supported,"; + } else { + return "Conversion from " + from + " to " + to + " is not supported,"; + } + } else { + return super.toString(); + } + } + + /** + * Returns code of source currency. This value may be null. + * @return Returns code of source currency. + */ + public String getFromCurrecyCode() { + return from; + } + + /** + * Returns code of target currency. This value may be null. + * @return Returns code of target currency. + */ public String getToCurrecyCode() { + return to; + } + + /** + * Returns if one way or two way conversion is not supported. + * + * Value false means one way conversion is not supported. + * Value true means that neither direct nor back conversion is not supported. + * + * @return Returs false for one way conversion, true for two way conversion. + */ + public boolean getTwoWayConversion() { + return reversed; + } + +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution13/src/org/apidesign/apifest08/currency/ConversionResult.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution13/src/org/apidesign/apifest08/currency/ConversionResult.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,56 @@ + +package org.apidesign.apifest08.currency; + +import java.math.BigDecimal; + +/** + * Result of currency conversion. Holds converted value and remainder. + *

+ * Converted describes value converted to target currenty. Remainder describes + * how much from original amount was not possible to convert. Convertor never loses any (small) money + * in conversion error (rounding), but instead of rounding is converts only as much as possible and keeps rest as remainder. + * + * @author arnostvalicek + */ +public class ConversionResult { + private BigDecimal converted; + private BigDecimal remainder; + + /** + * Get converted value. + * @return Returns converted value. + */ + public BigDecimal getConverted() { + return converted; + } + + void setConverted(BigDecimal converted) { + this.converted = converted; + } + + + /** + * Get remainder of conversion. Remainder is set if part of converted amount which can't be converted + * because this target currency precision can't handle small numbers. Remainder value is in from currency + *

+ * Converter never loses any precision in conversion. Remainer describes how much of amount can't be converted. + * If we substract remainder from amount we will be able to get exact conversion. + * + * @return Returns remainder of conversion. + */ + public BigDecimal getRemainder() { + return remainder; + } + + void setRemainder(BigDecimal remainder) { + this.remainder = remainder; + } + + @Override + public String toString() { + return getClass().getSimpleName()+": converter:"+getConverted()+", remainder:"+getRemainder(); + } + + + +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution13/src/org/apidesign/apifest08/currency/Convertor.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution13/src/org/apidesign/apifest08/currency/Convertor.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,335 @@ +package org.apidesign.apifest08.currency; + +import java.math.BigDecimal; +import java.math.MathContext; +import java.math.RoundingMode; +import java.util.Date; + +/** Convertor able to convert amount from one currency to other currency. + *

+ * Conversion method are: + *

+ * + * Exchange rate is provided by {@link ExchangeRateProvider}. + */ +public class Convertor { + private Convertor[] convertors; + private IDateProviderEngine dateProvider; + boolean remainderAllowed = true; //if false, remained is not allowed (should be true ideally, but can't handle it now) + private ExchangeRateProvider exchangeRateProvider; + private Date fromDate; + private Date toDate; + + /** Create new Convertor as merge of provided convertors. Merged convertor will use + * provided convertors to convert between currencies. + *

+ * Only one should be able to provide conversion between currencies. If more than one convertos + * are able to convert currency, one of conversions will be used (it is not defined which). + * + * @since version 2 + * @param convertors Convertor used to create merge-convertor. + * @return Returns new convertor instance. + */ + public static Convertor createConvertorAsMerge(Convertor[] convertors) { + for (int i=0;iConvertor using ExchangeRateProvider. + * + * @param exchangeRateProvider {@link ExchangeRateProvider} used to get exchange rate. + * + * @return Returns Convertor which can be used to convert money. + * @since version1 + */ + public static Convertor createConvertor(ExchangeRateProvider exchangeRateProvider) { + Convertor c = new Convertor(); + + c.exchangeRateProvider = exchangeRateProvider; + return c; + } + + /** + * Convert amount from fromCurrency to toCurrency as specified + * in ExchangeRateProvider. + * + * @param amount Amount which should be converted. Can't be negative value (can be zero or positive). + * @return Return ConversionResult which holds conversion result. + * @since version1 + * @deprecated since version2. Use {@link #convert(ConvertorCurrency, ConvertorCurrency, BigDecimal) } - explicitly specify conversion currencies. + */ + public ConversionResult convert(BigDecimal amount) { + return convertValue(exchangeRateProvider.getFromCurrency(), exchangeRateProvider.getToCurrency(),amount, false,false,null); + } + + /** + * Convert amount from toCurrency to fromCurrency as specified + * in ExchangeRateProvider. This is reverted order than suggested by names of currency fields in ExchangeRate. + * + * @param amount Amount which should be converted. Can't be negative value (can be zero or positive). + * @return Return ConversionResult which holds conversion result. + * @since version1 + * @deprecated since version2. Use {@link #convert(ConvertorCurrency, ConvertorCurrency, BigDecimal) } - explicitly specify conversion currencies. + */ + public ConversionResult convertBack(BigDecimal amount) { + return convertValue(exchangeRateProvider.getFromCurrency(), exchangeRateProvider.getToCurrency(),amount, true,false,null); + } + + private ConversionResult convertUsingSimpleConvertor(ConvertorCurrency fromCurrency, ConvertorCurrency toCurrency, boolean reversibleExRate, BigDecimal amount, boolean convertBack,Date date) throws ConversionNotSupportedException, RuntimeException { + if (date == null) { + date = dateProvider.getCurrentDate(); + } + + ExchangeRate rate; + if (reversibleExRate) { + rate = exchangeRateProvider.getReversibleExchangeRate(fromCurrency, toCurrency, date); + } else { + rate = exchangeRateProvider.getExchangeRate(fromCurrency, toCurrency, date); + } + if (rate == null) { + return null; + } + ConversionResult result = new ConversionResult(); + + int fromFranctionDigits = fromCurrency.getDefaultFractionDigits(); + int toFractionDigits = toCurrency.getDefaultFractionDigits(); + + int usedFractionDigits = Math.max(fromFranctionDigits, toFractionDigits); + + //if (toFractionDigits != 2) { + // throw new ConvertorException("Can't process currency with defaultFractionDigits!=2, " + toCurrency + " has " + toFractionDigits + " defaultFractionDigits"); + //} + //if (fromFranctionDigits != 2) { + // throw new ConvertorException("Can't process currency with defaultFractionDigits!=2, " + fromCurrency + " has " + fromFranctionDigits + " defaultFractionDigits"); + //} + + if (amount.signum() == -1) { + throw new RuntimeException("Can convert only non-negative value, current value is " + amount); + } + + + MathContext context = new MathContext(0, RoundingMode.DOWN); + + BigDecimal from; + BigDecimal to; + if (convertBack) { + //converting in reverted way + to = rate.getFromValue(); + from = rate.getToValue(); + } else { + //converting in normal way + from = rate.getFromValue(); + to = rate.getToValue(); + } + + BigDecimal amountCent = amount.movePointRight(usedFractionDigits); + + final BigDecimal multiplied = amountCent.multiply(to, context); + BigDecimal[] division = multiplied.divideAndRemainder(from, context); + + if (!remainderAllowed && !(BigDecimal.ZERO.equals(division[1]))) { + throw new RuntimeException("Remained is not allowed - remaining amount is " + division[1] + " cents"); + } else { + result.setRemainder(BigDecimal.ZERO.setScale(fromFranctionDigits)); + } + + BigDecimal converted = division[0].movePointLeft(usedFractionDigits); + converted = converted.setScale(toFractionDigits,RoundingMode.DOWN); //XXX ugly + result.setConverted(converted); + BigDecimal[] convertedInBase = converted.multiply(from).divideAndRemainder(to); + BigDecimal x2 = convertedInBase[0].add(convertedInBase[1]); + BigDecimal remainder = amount.subtract(x2); + result.setRemainder(remainder); + //System.out.println("ConvertedInBase="+Arrays.asList(convertedInBase)+":"+x2 +" ("+amount+") ["+converted+"] <"+from+","+to+"> ->"+remainder); + return result; + } + + + private ConversionResult convertValue(ConvertorCurrency fromCurrency, ConvertorCurrency toCurrency,BigDecimal amount, boolean convertBack,boolean reversibleExRate,Date date) throws RuntimeException { + //result.setRemainder(...); + if (!dateIsInLimit(date)) { + return null; + } + if (convertors.length==0) { + return convertUsingSimpleConvertor(fromCurrency, toCurrency, reversibleExRate, amount, convertBack,date); + } else { + ConversionResult result = null; + for (int i = 0;ivalue from fromCurrency to toCurrency. + *

+ * Exchange rate is provided by exchange rate provider which was specified when Convertor was created. + * This method is using only exchange rate from->to and not trying to use reverted excange rate to->from. + *

+ * This method is using date from IDateProviderEngine to get exchange rate (see {@link #getDateProvider() }. + * + * @param fromCurrency Source currency to convert from. + * @param toCurrency Target currency to convert to. + * @param value Value in source currency which should be converted. + * @return Return conversion result. + * @since version2 + * @throws ConversionNotSupportedException If conversion from fromCurrency to toCurrency is not supported. + */ + public ConversionResult convert(ConvertorCurrency fromCurrency, ConvertorCurrency toCurrency, BigDecimal value) { + Date defaultDate = dateProvider.getCurrentDate(); + ConversionResult result = convertValue(fromCurrency, toCurrency, value, false,false,defaultDate); + if (result==null) { + //throw new ConversionNotSupportedException("Conversion from " + fromCurrency + " to " + toCurrency + " is not supported"); + throw new ConversionNotSupportedException(fromCurrency.getCurrencyCode(),toCurrency.getCurrencyCode(),false); + } + return result; + } + /** + * Same as {@link #convert(ConvertorCurrency, ConvertorCurrency, java.math.BigDecimal)} but using provided rate instead of + * IDateProviderEngine. + * + * @param fromCurrency Source currency to convert from. + * @param toCurrency Target currency to convert to. + * @param value Value in source currency which should be converted. + * @return Return conversion result. + * @param date Conversion date + * @return Return conversion result. + */ + public ConversionResult convert(ConvertorCurrency fromCurrency, ConvertorCurrency toCurrency, BigDecimal value, Date date) { + ConversionResult result = convertValue(fromCurrency, toCurrency, value, false,false,date); + if (result==null) { + throw new ConversionNotSupportedException(fromCurrency.getCurrencyCode(),toCurrency.getCurrencyCode(),false); + } + return result; + } + + /** + * Convert value from fromCurrency to toCurrency. + * Exchange rate is provided by exchange rate provider which was specified when Convertor was created. + *

+ * This method is using only exchange rate from->to and if not found, it is trying to use reverted excange rate to->from. + *

+ * This method is using date from IDateProviderEngine to get exchange rate (see {@link #getDateProvider() }. + * + * @param fromCurrency Source currency to convert from. + * @param toCurrency Target currency to convert to. + * @param value Value in source currency which should be converted. + * @return Return conversion result. + * @since version2 + * @throws ConversionNotSupportedException If conversion from fromCurrency to toCurrency + * is not supported and neither conversion from toCurrency to fromCurrency is not supported. + */ + public ConversionResult convertWithReversibleRates(ConvertorCurrency fromCurrency, ConvertorCurrency toCurrency, BigDecimal value) { + Date defaultDate = dateProvider.getCurrentDate(); + ConversionResult result = convertValue(fromCurrency, toCurrency, value, false,true,defaultDate); + if (result==null) { + //throw new ConversionNotSupportedException("Neither onversion nor reverted conversion from " + fromCurrency + " to " + toCurrency + " is not supported,"); + throw new ConversionNotSupportedException(fromCurrency.getCurrencyCode(),toCurrency.getCurrencyCode(),true); + } + return result; + } + + /** + * Same as {@link #convertWithReversibleRates(ConvertorCurrency, ConvertorCurrency, java.math.BigDecimal)} but using provided rate instead of + * IDateProviderEngine. + * + * @param fromCurrency Source currency to convert from. + * @param toCurrency Target currency to convert to. + * @param value Value in source currency which should be converted. + * @return Return conversion result. + * @param date Conversion date + * @return Return conversion result. + */ + public ConversionResult convertWithReversibleRates(ConvertorCurrency fromCurrency, ConvertorCurrency toCurrency, BigDecimal value, Date date) { + ConversionResult result = convertValue(fromCurrency, toCurrency, value, false,true,date); + if (result==null) { + throw new ConversionNotSupportedException(fromCurrency.getCurrencyCode(),toCurrency.getCurrencyCode(),true); + } + return result; + } + + private boolean dateIsInLimit(Date date) { + boolean result; +// if (date==null) { +// result = true; +// } else + if (fromDate == null && toDate == null) { + result = true; + } else if (fromDate.getTime()<=date.getTime() && date.getTime()<=toDate.getTime()) { + result = true; + } else { + result = false; + } + + return result; + } + + + public void limitAllowedDates(Date from, Date till) { + if (from==null) { + throw new NullPointerException("from Date can't be null"); + } + if (till==null) { + throw new NullPointerException("till Date can't be null"); + } + if (from.getTime()>till.getTime()) { + throw new IllegalArgumentException("From date "+from+" must be before tii date "+till); + } + this.fromDate = from; + this.toDate = till; + } + + + /** Return current date provider. + * @return Returns current date provider. + */ + public IDateProviderEngine getDateProvider() { + return dateProvider; + } + + + /** + * Set date provider. Date provider is used to get "current date". Current date + * is used by methods {@link #convert(ConvertorCurrency, ConvertorCurrency, java.math.BigDecimal)} and + * {@link #convertWithReversibleRates(ConvertorCurrency, ConvertorCurrency, java.math.BigDecimal)}. + * + * @param dateProvider Date provider which should be used by Convertor. + */ + public void setDateProvider(IDateProviderEngine dateProvider) { + this.dateProvider = dateProvider; + } + + +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution13/src/org/apidesign/apifest08/currency/ConvertorCurrency.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution13/src/org/apidesign/apifest08/currency/ConvertorCurrency.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,97 @@ + +package org.apidesign.apifest08.currency; + +import java.util.Currency; + +/** + * Desription of currency. + * + * Java has similar class {@link java.util.Currency}, but original class is not flexible + * enough, we use our own implementation of currency. + * + * @author arnostvalicek + */ +public class ConvertorCurrency { + private String currencyCode; + private int fractionDigits; + + + /** + * Static method providing instance of ConvertorCurrency based on currency code. + *

+ * currencyCode is one of codes supported by Java class {@link java.util.Currency}. + * + * @param currencyCode Code of required currency. + * @return Returns required ConvertorCurrency + */ + public static ConvertorCurrency getInstance(String currencyCode) { + ConvertorCurrency convertorCurrency = new ConvertorCurrency(); + Currency currency = Currency.getInstance(currencyCode); + convertorCurrency.setCurrencyCode(currency.getCurrencyCode()); + convertorCurrency.setDefaultFractionDigits(currency.getDefaultFractionDigits()); + return convertorCurrency; + } + + /** + * Static method providing instance of ConvertorCurrency base of currency code. + * + * @param currencyCode Code of required currency. + * @param fractionDigits Number of fraction digits for currency. + * @return Returns required ConvertorCurrency + * @since version4 + */ + public static ConvertorCurrency getInstance(String currencyCode, int fractionDigits) { + ConvertorCurrency convertorCurrency = new ConvertorCurrency(); + convertorCurrency.setCurrencyCode(currencyCode); + convertorCurrency.setDefaultFractionDigits(fractionDigits); + return convertorCurrency; + } + + /** + * Gets the default number of fraction digits used with this currency. For example, the default number of fraction digits for the Euro is 2, while for the Japanese Yen it's 0. + * @return Returns the default number of fraction digits used with this currency. + */ + public int getDefaultFractionDigits() { + return fractionDigits; + } + + private void setDefaultFractionDigits(int value) { + this.fractionDigits = value; + } + + /** + * Get currency code. + * @return Returns currency code. + */ + public String getCurrencyCode() { + return currencyCode; + } + + private void setCurrencyCode(String value) { + currencyCode = value; + } + + @Override + public boolean equals(Object obj) { + boolean result; + if (obj instanceof ConvertorCurrency) { + ConvertorCurrency that = (ConvertorCurrency) obj; + result = getCurrencyCode().equals(that.getCurrencyCode()) && getDefaultFractionDigits()==that.getDefaultFractionDigits(); + } else { + result = false; + } + return result; + } + + @Override + public int hashCode() { + return currencyCode==null ? 47/*??*/ : currencyCode.hashCode(); + } + + + @Override + public String toString() { + return "ConvertorCurrency[" + (currencyCode != null ? currencyCode : "NO-BASE-CURRENCY")+"]"; + } + +} \ No newline at end of file diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution13/src/org/apidesign/apifest08/currency/ConvertorException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution13/src/org/apidesign/apifest08/currency/ConvertorException.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,25 @@ +package org.apidesign.apifest08.currency; + +/** + * Common Convertor exception. + * + * @author arnostvalicek + */ +public class ConvertorException extends RuntimeException { + + public ConvertorException(Throwable cause) { + super(cause); + } + + public ConvertorException(String message, Throwable cause) { + super(message, cause); + } + + public ConvertorException(String message) { + super(message); + } + + public ConvertorException() { + } + +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution13/src/org/apidesign/apifest08/currency/DateProvider.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution13/src/org/apidesign/apifest08/currency/DateProvider.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,36 @@ +package org.apidesign.apifest08.currency; + +import java.util.Date; + +/** + * Provider for current date. + * + * @author arnostvalicek + * @since version4. + */ +public class DateProvider { + private DateProvider() { + + } + + /** + * Create date provider based on current system time. + * @see java.lang.System#currentTimeMillis() + */ + public static IDateProviderEngine createCurrentDateProvider() { + return new CurrentDateProvider(); + } + + /** + * Date provider based on current system time. + * @see java.lang.System#currentTimeMillis() + */ + private static class CurrentDateProvider implements IDateProviderEngine { + + public Date getCurrentDate() { + return new Date(); + } + + } + +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution13/src/org/apidesign/apifest08/currency/ExchangeRate.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution13/src/org/apidesign/apifest08/currency/ExchangeRate.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,68 @@ + +package org.apidesign.apifest08.currency; + +import java.math.BigDecimal; + +/** + * Exchange rate value. Contains from and to value. + * + * @author arnostvalicek + */ +public class ExchangeRate { + private BigDecimal numberFor; + private BigDecimal numberGet; + + /** + * Constructor for new exchange rate holding two values - from value and to value + * @param fromValue Exchange rate from value + * @param toValue Exchange rate to value + */ + public ExchangeRate(BigDecimal fromValue, BigDecimal toValue) { + this.numberFor = fromValue; + this.numberGet = toValue; + } + + /** + * Create new instance of ExchangeRate based on provided exchange rate, but swapping its + * from and to value. + *

+ * Provided exchange rate is not chaged, this method returns different instance describing reverted exchange rate. + * + * @param rate Exchange rate which describes rate to be reverted. + * @return Instance of reverted rate. + */ + public static ExchangeRate createRevertedRate(ExchangeRate rate) { + ExchangeRate reverted = new ExchangeRate(rate.getToValue(), rate.getFromValue()); + return reverted; + } + + @Override + public String toString() { + return "for "+numberFor+" recieve "+numberGet+" @"+getClass().getName(); + } + + /** + * Return exchange rate from value stored in this object. + * @return Returns from value for this exchange rate. + */ + public BigDecimal getFromValue() { + return numberFor; + } + + /** + * Return exchange rate to value stored in this object. + * @return Returns to value for this exchange rate. + */ + public BigDecimal getToValue() { + return numberGet; + } + + +// public ExchangeRate createExchangeRate(BigDecimal forValue, BigDecimal getValue) { +// ExchangeRate rate = new ExchangeRate(forValue, getValue); +// return rate; +// } + + + +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution13/src/org/apidesign/apifest08/currency/ExchangeRateProvider.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution13/src/org/apidesign/apifest08/currency/ExchangeRateProvider.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,318 @@ +package org.apidesign.apifest08.currency; + +import java.math.BigDecimal; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +/** + * Exchange rate provider. Provides exchange rate for two currencies (method {@link #getExchangeRate(ConvertorCurrency, ConvertorCurrency)} ). + *

+ * Several method can be created to create ExchangeRateProvider: + *

+ *

+ * Date dependend exchange rate to be implemented. + * + * @author arnostvalicek + */ +public class ExchangeRateProvider { + + IExchangeRateEngine exrateEngine; + IDateExchangeRateEngine dateExrateEngine; + + /** + * Simple constructor for ExchangeRateProviderM which can provide fixed exchange rate. + * + * Describes conversion from ONE to to ONE currency. + * + * @param fromValue From value. BigDecimal value, precision should be set to currency precision. + * @param fromCurrency From currency. + * @param toValue To value. BigDecimal value, precision should be set to currency precision. + * @param toCurrency To currency. + * @deprecated deprecated since task2. Use {@link #createExchangeRateProvider() } instead of this constructor. + */ + public ExchangeRateProvider(BigDecimal fromValue, ConvertorCurrency fromCurrency, BigDecimal toValue, ConvertorCurrency toCurrency) { + this.exrateEngine = FixedOneExchangeRateEngine.createEngine(fromValue, fromCurrency, toValue, toCurrency); + } + + private ExchangeRateProvider() { + } + + /** + * Static method to create new exchange rate provider. This exchange rate provider does not contain + * any exchange rates (this is difference to public constructor). + * @return New ExchangeRateProvider + */ + public static ExchangeRateProvider createExchangeRateProvider() { + ExchangeRateProvider provider = new ExchangeRateProvider(); + provider.exrateEngine = FixedExchangeRateEngine.createEngine(); + return provider; + } + + /** + * Static method to create exchange rate provider which is using provided IExchangeRateEngine. This exchange rate provider is using + * IExchangeRateEngine to get actual exchange rate. + * @param exchangeRateEngine IExchangeRateEngine used to get exchange rate. + * @return Returns instance of ExchangeRateProvider + */ + public static ExchangeRateProvider createExchangeRateProvider(IExchangeRateEngine exchangeRateEngine) { + ExchangeRateProvider provider = new ExchangeRateProvider(); + provider.exrateEngine = exchangeRateEngine; + return provider; + } + + /** + * Static method to create exchange rate provider which is using provided IExIDateExchangeRateEnginechangeRateEngine. This exchange rate provider is using + * IExchangeRateEngine to get actual exchange rate. + * @param exchangeRateEngine IDateExchangeRateEngine used to get exchange rate. + * @return Returns instance of ExchangeRateProvider + */ + public static ExchangeRateProvider createDateExchangeRateProvider(IDateExchangeRateEngine exchangeRateEngine) { + ExchangeRateProvider provider = new ExchangeRateProvider(); + provider.dateExrateEngine = exchangeRateEngine; + return provider; + } + + /** + * Add new exchange rate to to this simple exchange rate provider. + *

+ * Example of specifiing conversion rate: 100 SKK == 80 CZK:
+ * addFixedCurencyRate(ConvertorCurrency.getInstance("SKK"), new BigDecimal(100), ConvertorCurrency.getInstance("CZK"), new BigDecimal(80)); + *

+ * This method may be used only when ExchangeRateProvider is created using {@link #createExchangeRateProvider() } - creating exchange rate provider without external IExchangeRateEngine. + * + * @param fromCurrency Source currency. + * @param fromValue Valye for from currency. + * @param toCurrency Target currency. + * @param toValue Value for target currency. + * @throws IllegalStateException Throws exception when adding fixed currency rate to exchange rate provider which is not created using {@link #createExchangeRateProvider() }. + */ + public synchronized void addFixedCurencyRate(ConvertorCurrency fromCurrency, BigDecimal fromValue, ConvertorCurrency toCurrency, BigDecimal toValue) { + if (exrateEngine instanceof FixedExchangeRateEngine) { + ((FixedExchangeRateEngine) exrateEngine).addFixedCurencyRate(fromCurrency, fromValue, toCurrency, toValue); + } else { + throw new IllegalStateException("Cuurency rate can be added only to ExchangeRateProvider created with FixedExchangeRateEngine - using method createExchangeRateProvider()"); + } + } + + /** + * Get fixed exange rate for currencies (from->to). + * @return Returns exchange rate. + * @deprecated deprecated since task2. Use {@link #getExchangeRate(ConvertorCurrency, ConvertorCurrency) } + */ + public ExchangeRate getExchangeRate() { + //works only for FixedExchangeRateEngine + if (exrateEngine instanceof FixedOneExchangeRateEngine) { + FixedOneExchangeRateEngine engine = (FixedOneExchangeRateEngine) exrateEngine; + return new ExchangeRate(engine.getFromValue(), engine.getToValue()); + } else { + throw new IllegalStateException("Method supported only for MinimalFixedExchangeRateEngine. This method is deprecated"); + } + + } + + /** + * Get fixed exange rate for currencies (from->to). + * @param fromCurrency Source currency. + * @param toCurrency Target currency. + * @return Returns exchange rate or null if exchange rate not found. + */ + public ExchangeRate getExchangeRate(ConvertorCurrency fromCurrency, ConvertorCurrency toCurrency) { + return getExchangeRateImpl(fromCurrency, toCurrency,null); + } + + /** + * Get exange rate for currencies (from->to) for date. + * @param fromCurrency Source currency. + * @param toCurrency Target currency. + * @param date Conversion date. + * @return Returns exchange rate or null if exchange rate not found. + */ + public ExchangeRate getExchangeRate(ConvertorCurrency fromCurrency, ConvertorCurrency toCurrency, Date date) { + return getExchangeRateImpl(fromCurrency, toCurrency,date); + } + + /** + * Get fixed exange rate for currencies (from->to) or reversed exchange rate (to->from). + * @param fromCurrency Source currency. + * @param toCurrency Target currency. + * @return Returns exchange rate or null if exchange rate not found. + */ + public ExchangeRate getReversibleExchangeRate(ConvertorCurrency fromCurrency, ConvertorCurrency toCurrency) { + return getReversibleExrateImpl(fromCurrency, toCurrency,null); + } + + /** + * Get exange rate for currencies (from->to) or reversed exchange rate (to->from) for date. + * @param fromCurrency Source currency. + * @param toCurrency Target currency. + * @param date Conversion date. + * @return Returns exchange rate or null if exchange rate not found. + */ + public ExchangeRate getReversibleExchangeRate(ConvertorCurrency fromCurrency, ConvertorCurrency toCurrency, Date date) { + return getReversibleExrateImpl(fromCurrency, toCurrency, date); + } + + /** + * Get exchange rate for currencies (from->to) based on provided date. + * @param date Date for which exchange rate should be provided. + * @return Returns exchange rate + * @deprecated deprecated since task2. No real implementation in version2. + */ + public ExchangeRate getExchangeRate(Date date) { + //works only for FixedExchangeRateEngine + if (exrateEngine instanceof FixedOneExchangeRateEngine) { + FixedOneExchangeRateEngine engine = (FixedOneExchangeRateEngine) exrateEngine; + return new ExchangeRate(engine.getFromValue(), engine.getToValue()); + } else { + throw new IllegalStateException("Method supported only for FixedOneExchangeRateEngine. This method is deprecated"); + } + } + + ConvertorCurrency getFromCurrency() { + if (exrateEngine instanceof FixedOneExchangeRateEngine) { + FixedOneExchangeRateEngine engine = (FixedOneExchangeRateEngine) exrateEngine; + return engine.getFromCurrency(); + } else { + throw new IllegalStateException("Method supported only for FixedOneExchangeRateEngine. This method is deprecated"); + } + } + + ConvertorCurrency getToCurrency() { + if (exrateEngine instanceof FixedOneExchangeRateEngine) { + FixedOneExchangeRateEngine engine = (FixedOneExchangeRateEngine) exrateEngine; + return engine.getToCurrency(); + } else { + throw new IllegalStateException("Method supported only for FixedOneExchangeRateEngine. This method is deprecated"); + } + } + + + private ExchangeRate getReversibleExrateImpl(ConvertorCurrency fromCurrency, ConvertorCurrency toCurrency,Date date) { + ExchangeRate rate = getExchangeRateImpl(fromCurrency, toCurrency, date); + if (rate == null) { + ExchangeRate revertedRate = getExchangeRateImpl(toCurrency, fromCurrency, date); + if (revertedRate != null) { + rate = ExchangeRate.createRevertedRate(revertedRate); + } + } + return rate; + } + + private ExchangeRate getExchangeRateImpl(ConvertorCurrency fromCurrency, ConvertorCurrency toCurrency,Date date) { + ExchangeRate result; + if (exrateEngine!=null) { + result = exrateEngine.getExchangeRate(fromCurrency, toCurrency); + } else if (dateExrateEngine!=null) { + result = dateExrateEngine.getExchangeRate(fromCurrency, toCurrency, date); + } else { + throw new IllegalStateException("No exchange rate engine provided"); + } + return result; + } + + private static class FixedOneExchangeRateEngine implements IExchangeRateEngine { + + BigDecimal fromValue; + ConvertorCurrency fromCurrency; + BigDecimal toValue; + ConvertorCurrency toCurrency; + + private FixedOneExchangeRateEngine(BigDecimal fromValue, ConvertorCurrency fromCurrency, BigDecimal toValue, ConvertorCurrency toCurrency) { + this.fromValue = fromValue; + this.toValue = toValue; + this.fromCurrency = fromCurrency; + this.toCurrency = toCurrency; + } + + /** + * Create IExchangeRateEngine conveting from fromCurrency to toCurrency + * with echange rate fromValue:toValue + * @param fromValue + * @param fromCurrency + * @param toValue + * @param toCurrency + * @return Returns instance of FixedOneExchangeRateEngine. + */ + private static IExchangeRateEngine createEngine(BigDecimal fromValue, ConvertorCurrency fromCurrency, BigDecimal toValue, ConvertorCurrency toCurrency) { + return new FixedOneExchangeRateEngine(fromValue, fromCurrency, toValue, toCurrency); + } + + private BigDecimal getFromValue() { + return fromValue; + } + + private BigDecimal getToValue() { + return toValue; + } + + private ConvertorCurrency getFromCurrency() { + return fromCurrency; + } + + private ConvertorCurrency getToCurrency() { + return toCurrency; + } + + public ExchangeRate getExchangeRate(ConvertorCurrency fromCurrency, ConvertorCurrency toCurrency) { + if (!fromCurrency.equals(this.fromCurrency)) { + return null; + } + if (!toCurrency.equals(this.toCurrency)) { + return null; + } + return new ExchangeRate(fromValue, toValue); + } + } + + /** + * Exchange rate engine able to hold several fixed exchange rates. + * + * @author arnostvalicek + */ + private static class FixedExchangeRateEngine implements IExchangeRateEngine { + + private Map> exchangeRateMap = new HashMap>(); + + private FixedExchangeRateEngine() { + } + + /** + * Create instance of FixedExchangeRateEngine. + * @return Returns instance of FixedExchangeRateEngine. + */ + public static IExchangeRateEngine createEngine() { + return new FixedExchangeRateEngine(); + } + + public ExchangeRate getExchangeRate(ConvertorCurrency fromCurrency, ConvertorCurrency toCurrency) { + Map map2 = exchangeRateMap.get(fromCurrency); + if (map2 == null) { + return null; + } + ExchangeRate result = map2.get(toCurrency); + return result; + } + + public synchronized void addFixedCurencyRate(ConvertorCurrency fromCurrency, BigDecimal fromValue, ConvertorCurrency toCurrency, BigDecimal toValue) { + if (fromValue == null) { + throw new NullPointerException("fromValue can't be null"); + } + if (toValue == null) { + throw new NullPointerException("toValue can't be null"); + } + Map map2 = exchangeRateMap.get(fromCurrency); + if (map2 == null) { + map2 = new HashMap(); + exchangeRateMap.put(fromCurrency, map2); + } + + ExchangeRate rate = new ExchangeRate(fromValue, toValue); + map2.put(toCurrency, rate); + } + } +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution13/src/org/apidesign/apifest08/currency/IDateExchangeRateEngine.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution13/src/org/apidesign/apifest08/currency/IDateExchangeRateEngine.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,21 @@ +package org.apidesign.apifest08.currency; + +import java.util.Date; + +/** + * Interface for exchange rate engine using dates. + * + * @author arnostvalicek + */ +public interface IDateExchangeRateEngine { + /** + * Get exchange rate for conversion from fromCurrency to toCurrency at date. + * + * @param fromCurrency From currency. + * @param toCurrency To currency. + * @param date Conversion date. + * @return Returns ExchangeRate if exchange rate is known or null if exchanger rate is not known. + */ + public ExchangeRate getExchangeRate(ConvertorCurrency fromCurrency, ConvertorCurrency toCurrency, Date date); + +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution13/src/org/apidesign/apifest08/currency/IDateProviderEngine.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution13/src/org/apidesign/apifest08/currency/IDateProviderEngine.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,19 @@ +package org.apidesign.apifest08.currency; + +import java.util.Date; + +/** + * Date provider - provides current date. + * @see DateProvider#createCurrentDateProvider() + * @see Convertor#setDateProvider(IDateProviderEngine) + * @author arnostvalicek + * @since version4 + */ +public interface IDateProviderEngine { + /** + * Get current date. + * @return Return current date. + */ + public Date getCurrentDate(); + +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution13/src/org/apidesign/apifest08/currency/IExchangeRateEngine.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution13/src/org/apidesign/apifest08/currency/IExchangeRateEngine.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,18 @@ +package org.apidesign.apifest08.currency; + +/** + * Interface for exchange rate engine. + * + * @author arnostvalicek + */ +public interface IExchangeRateEngine { + + /** + * Get exchange rate for conversion from fromCurrency to toCurrency. + * + * @param fromCurrency From currency. + * @param toCurrency To currency. + * @return Returns ExchangeRate if exchange rate is known or null if exchanger rate is not known. + */ + public ExchangeRate getExchangeRate(ConvertorCurrency fromCurrency, ConvertorCurrency toCurrency); +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution13/test/org/apidesign/apifest08/test/BouncingExchangeRateEngine.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution13/test/org/apidesign/apifest08/test/BouncingExchangeRateEngine.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,79 @@ +package org.apidesign.apifest08.test; + +import java.math.BigDecimal; +import org.apidesign.apifest08.currency.ConvertorCurrency; +import org.apidesign.apifest08.currency.ExchangeRate; +import org.apidesign.apifest08.currency.IExchangeRateEngine; + +/** Exchange rate engine which is periodicaly changing echange rate. + * See http://wiki.apidesign.org/wiki/APIFest08:Task3 for further description. + * + * @author arnostvalicek + */ +public class BouncingExchangeRateEngine implements IExchangeRateEngine { + + ConvertorCurrency fromCurrency; + BigDecimal fromValue; + ConvertorCurrency toCurrency; + BigDecimal toValueStart; + BigDecimal toValueStop; + BigDecimal step; + + BigDecimal toValue; + + + + + private BouncingExchangeRateEngine(ConvertorCurrency fromCurrency, BigDecimal fromValue, ConvertorCurrency toCurrency, BigDecimal toValueStart, BigDecimal toValueStop, BigDecimal step) { + this.fromCurrency = fromCurrency; + this.fromValue = fromValue; + this.toCurrency = toCurrency; + this.toValueStart = toValueStart; + this.toValueStop = toValueStop; + this.step = step; + this.toValue = toValueStart; + } + + + public static IExchangeRateEngine create(ConvertorCurrency fromCurrency, BigDecimal fromValue, ConvertorCurrency toCurrency, BigDecimal toValueStart, BigDecimal toValueStop, BigDecimal step) { + return new BouncingExchangeRateEngine(fromCurrency, fromValue, toCurrency, toValueStart, toValueStop, step); + } + + public ExchangeRate getExchangeRate(ConvertorCurrency fromCurrency, ConvertorCurrency toCurrency) { + if (!fromCurrency.equals(this.fromCurrency)) { + return null; + } + if (!toCurrency.equals(this.toCurrency)) { + return null; + } + + ExchangeRate result = new ExchangeRate(fromValue, toValue); + + toValue = toValue.add(step); + +// if (step.signum()==1 && toValueStop.compareTo(toValue)==0) { +// System.out.println("A"); +// toValue=toValueStop; +// step = step.negate(); +// BigDecimal x = toValueStart; +// toValueStart=toValueStop; +// toValueStop=x; +// } else if (step.signum()==-1 && toValueStop.compareTo(toValue)==0) { +// System.out.println("B"); +// toValue=toValueStop; +// step = step.negate(); +// BigDecimal x = toValueStart; +// toValueStart=toValueStop; +// toValueStop=x; +// } + if (toValueStop.compareTo(toValue)==0) { + toValue=toValueStop; + step = step.negate(); + BigDecimal x = toValueStart; + toValueStart=toValueStop; + toValueStop=x; + } + return result; + } + +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution13/test/org/apidesign/apifest08/test/ConvertorWithDateExchangeRateTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution13/test/org/apidesign/apifest08/test/ConvertorWithDateExchangeRateTest.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,109 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package org.apidesign.apifest08.test; + +import java.math.BigDecimal; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import junit.framework.TestCase; +import org.apidesign.apifest08.currency.ConversionResult; +import org.apidesign.apifest08.currency.Convertor; +import org.apidesign.apifest08.currency.ConvertorCurrency; +import org.apidesign.apifest08.currency.ExchangeRate; +import org.apidesign.apifest08.currency.ExchangeRateProvider; +import org.apidesign.apifest08.currency.IDateExchangeRateEngine; +import org.apidesign.apifest08.currency.IDateProviderEngine; + +/** + * + * @author arnostvalicek + */ +public class ConvertorWithDateExchangeRateTest extends TestCase { + + private static ConvertorCurrency CZK = ConvertorCurrency.getInstance("CZK"); + private static ConvertorCurrency SKK = ConvertorCurrency.getInstance("SKK"); + private static ConvertorCurrency USD = ConvertorCurrency.getInstance("USD"); + private SimpleDateFormat df; + + @Override + protected void setUp() throws Exception { + super.setUp(); + df = new SimpleDateFormat("yyyy-MM-dd HH:mm zzzz"); + } + + @Override + protected void tearDown() throws Exception { + super.tearDown(); + df = null; + } + + private IDateExchangeRateEngine createDateEngine() { + IDateExchangeRateEngine engine = new IDateExchangeRateEngine() { + + public ExchangeRate getExchangeRate(ConvertorCurrency fromCurrency, ConvertorCurrency toCurrency, Date date) { + int day = date.getDay(); + if (day >= 1 && day <= 5) { + //weekday + return new ExchangeRate(new BigDecimal(1), new BigDecimal(2)); + } else { + //weekend + return new ExchangeRate(new BigDecimal(1), new BigDecimal(3)); + } + } + }; + return engine; + } + + private Convertor createConvertor() { + ExchangeRateProvider exchangeRateProvider = ExchangeRateProvider.createDateExchangeRateProvider(createDateEngine()); + Convertor c = Convertor.createConvertor(exchangeRateProvider); + return c; + } + + public void testConvertuUsingDifferentRatesForDays() throws ParseException { + Convertor c = createConvertor(); + { + Date d1 = df.parse("2008-10-15 9:00 GMT"); //Wednesday + ConversionResult resultWeekday = c.convert(CZK, SKK, new BigDecimal("2.3"), d1); + assertEquals("Weekday conversion", new BigDecimal("4.60"), resultWeekday.getConverted()); + } + { + Date d1 = df.parse("2008-10-18 9:00 GMT"); //Saturday + ConversionResult resultWeekday = c.convert(CZK, SKK, new BigDecimal("2.3"), d1); + assertEquals("Weekday conversion", new BigDecimal("6.90"), resultWeekday.getConverted()); + } + } + + public void testConvertUsingDifferenDefaultDay() throws ParseException { + class MyDateProvider implements IDateProviderEngine { + + private Date date; + + void setDate(Date date) { + this.date = date; + } + + public Date getCurrentDate() { + return date; + } + } + + Convertor c = createConvertor(); + MyDateProvider dp = new MyDateProvider(); + c.setDateProvider(dp); + + { + dp.setDate(df.parse("2008-10-15 9:00 GMT")); //Wednesday + ConversionResult resultWeekday = c.convert(CZK, SKK, new BigDecimal("2.3")); + assertEquals("Weekday conversion", new BigDecimal("4.60"), resultWeekday.getConverted()); + } + { + dp.setDate(df.parse("2008-10-18 9:00 GMT")); //Saturday + ConversionResult resultWeekday = c.convert(CZK, SKK, new BigDecimal("2.3")); + assertEquals("Weekday conversion", new BigDecimal("6.90"), resultWeekday.getConverted()); + } + } +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution13/test/org/apidesign/apifest08/test/RemainderTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution13/test/org/apidesign/apifest08/test/RemainderTest.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,80 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package org.apidesign.apifest08.test; + +import java.math.BigDecimal; +import java.text.SimpleDateFormat; +import junit.framework.TestCase; +import org.apidesign.apifest08.currency.ConversionResult; +import org.apidesign.apifest08.currency.Convertor; +import org.apidesign.apifest08.currency.ConvertorCurrency; +import org.apidesign.apifest08.currency.ExchangeRateProvider; + +/** + * + * @author arnostvalicek + */ +public class RemainderTest extends TestCase { + private static ConvertorCurrency CZK = ConvertorCurrency.getInstance("CZK"); + private static ConvertorCurrency SKK = ConvertorCurrency.getInstance("SKK"); + private static ConvertorCurrency USD = ConvertorCurrency.getInstance("USD"); + private SimpleDateFormat df; + + @Override + protected void setUp() throws Exception { + super.setUp(); + df = new SimpleDateFormat("yyyy-MM-dd HH:mm zzzz"); + + } + + @Override + protected void tearDown() throws Exception { + super.tearDown(); + } + + public void testRemainder1() { + Convertor c = Task2Test.createUsdToSkkConvertor(); + { + final BigDecimal convertedValue = new BigDecimal("12.34"); + ConversionResult result = c.convertWithReversibleRates(SKK,USD,convertedValue); + //System.out.println("Result = "+result); + assertEquals("Converted", new BigDecimal("0.61"),result.getConverted()); + assertEquals("Remainder", new BigDecimal("0.14"),result.getRemainder()); + + ConversionResult resultBack = c.convertWithReversibleRates(USD, SKK, result.getConverted()); + assertEquals("Conversion back", convertedValue, resultBack.getConverted().add(result.getRemainder())); + + } + { + ConversionResult result = c.convertWithReversibleRates(SKK,USD,new BigDecimal("20.00")); + //System.out.println("Result = "+result); + } + + { + ConversionResult result = c.convertWithReversibleRates(USD,SKK,new BigDecimal("1.00")); + //System.out.println("Result = "+result); + } + + } + + public void testRemainderStripCents() { + ConvertorCurrency CZK_cents=ConvertorCurrency.getInstance("CZK", 2); + ConvertorCurrency CZK_nocents=ConvertorCurrency.getInstance("CZK", 0); + + + ExchangeRateProvider exchangeRateProvider = ExchangeRateProvider.createExchangeRateProvider(); + exchangeRateProvider.addFixedCurencyRate(CZK_cents, new BigDecimal(1), CZK_nocents, new BigDecimal(1)); + + Convertor c = Convertor.createConvertor(exchangeRateProvider); + + ConversionResult result = c.convertWithReversibleRates(CZK_cents, CZK_nocents, new BigDecimal("2.34")); + assertEquals("Converted",new BigDecimal("2"),result.getConverted()); + assertEquals("Remainder",new BigDecimal("0.34"),result.getRemainder()); + } + + + +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution13/test/org/apidesign/apifest08/test/Task1Test.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution13/test/org/apidesign/apifest08/test/Task1Test.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,223 @@ +package org.apidesign.apifest08.test; + +import java.math.BigDecimal; +import junit.framework.TestCase; +import org.apidesign.apifest08.currency.ConversionResult; +import org.apidesign.apifest08.currency.Convertor; +import org.apidesign.apifest08.currency.ConvertorCurrency; +import org.apidesign.apifest08.currency.ExchangeRateProvider; +import org.apidesign.apifest08.currency.ConversionNotSupportedException; + +/** Finish the Convertor API, and then write bodies of methods inside + * of this class to match the given tasks. To fullfil your task, use the + * API define in the org.apidesign.apifest08.currency package. + * Do not you reflection, or other hacks as your code + * shall run without any runtime permissions. + */ +public class Task1Test extends TestCase { + public Task1Test(String testName) { + super(testName); + } + + @Override + protected void setUp() throws Exception { + } + + @Override + protected void tearDown() throws Exception { + } + + /** Create convertor that understands two currencies, CZK and + * USD. Make 1 USD == 17 CZK. + * + * Creation of the convertor shall not require subclassing of any class + * or interface on the client side. + * + * @return prepared convertor ready for converting USD to CZK and CZK to USD + */ + public static Convertor createCZKtoUSD() { + ConvertorCurrency fromCurrency = ConvertorCurrency.getInstance("CZK"); + ConvertorCurrency toCurrency = ConvertorCurrency.getInstance("USD"); + ExchangeRateProvider exchangeRateProvider = new ExchangeRateProvider(new BigDecimal(17), fromCurrency, new BigDecimal(1), toCurrency); + + return Convertor.createConvertor(exchangeRateProvider); + } + + /** Create convertor that understands two currencies, CZK and + * SKK. Make 100 SKK == 80 CZK. + * + * Creation of the convertor shall not require subclassing of any class + * or interface on the client side. + * + * @return prepared convertor ready for converting SKK to CZK and CZK to SKK + */ + public static Convertor createSKKtoCZK() { + ConvertorCurrency fromCurrency = ConvertorCurrency.getInstance("SKK"); + ConvertorCurrency toCurrency = ConvertorCurrency.getInstance("CZK"); + ExchangeRateProvider exchangeRateProvider = new ExchangeRateProvider(new BigDecimal(100), fromCurrency, new BigDecimal(80), toCurrency); + + return Convertor.createConvertor(exchangeRateProvider); + } + + + public static Convertor createCZKtoYEN() { + ConvertorCurrency fromCurrency = ConvertorCurrency.getInstance("CZK"); + ConvertorCurrency toCurrency = ConvertorCurrency.getInstance("JPY"); + ExchangeRateProvider exchangeRateProvider = new ExchangeRateProvider(new BigDecimal(1), fromCurrency, new BigDecimal(1), toCurrency); + + return Convertor.createConvertor(exchangeRateProvider); + } + + /** Use the convertor from createCZKtoUSD method and do few conversions + * with it. + */ + public void testCurrencyCZKUSD() throws Exception { + Convertor convertCzkUsd = createCZKtoUSD(); + + { + // convert $1 to CZK using c: + ConversionResult result = convertCzkUsd.convertBack(new BigDecimal(1)); + assertEquals("Result is 17 CZK", new BigDecimal("17.00"), result.getConverted()); + assertEquals("No Remainer", new BigDecimal("00.00").setScale(2), result.getRemainder()); + } + + { + // convert 17CKZ to $ using c: + ConversionResult result = convertCzkUsd.convert(new BigDecimal(17)); + assertEquals("Result is 1 $", new BigDecimal("1.00"), result.getConverted()); + assertEquals("No Remainer", new BigDecimal("00.00").setScale(2), result.getRemainder()); + } + + { + // convert $5 to CZK using c: + ConversionResult result = convertCzkUsd.convertBack(new BigDecimal(5)); + assertEquals("Result is 85 CZK", new BigDecimal("85.00"), result.getConverted()); + assertEquals("No Remainer", BigDecimal.ZERO.setScale(2), result.getRemainder()); + } + + { + // convert $8 to CZK + ConversionResult result = convertCzkUsd.convertBack(new BigDecimal(8)); + assertEquals("Result is 136 CZK", new BigDecimal("136.00"), result.getConverted()); + assertEquals("No Remainer", BigDecimal.ZERO.setScale(2), result.getRemainder()); + } + + { + // convert 1003CZK to USD + ConversionResult result = convertCzkUsd.convert(new BigDecimal(1003)); + assertEquals("Result is 59 USD", new BigDecimal("59.00"), result.getConverted()); + assertEquals("No Remainer", BigDecimal.ZERO.setScale(2), result.getRemainder()); + } + } + + /** Use the convertor from createSKKtoCZK method and do few conversions + * with it. + */ + public void testCurrencySKKCZK() throws Exception { + Convertor convertSkkCzk = createSKKtoCZK(); + { + // convert 100SKK using c: + ConversionResult result = convertSkkCzk.convert(new BigDecimal(100)); + assertEquals("Result is 80 CZK", new BigDecimal("80.00"), result.getConverted()); + } + { + // convert 80CZK using c: + ConversionResult result = convertSkkCzk.convertBack(new BigDecimal(80)); + assertEquals("Result is 100 SKK", new BigDecimal("100.00"), result.getConverted()); + } + + { + // convert 16CZK using c: + ConversionResult result = convertSkkCzk.convertBack(new BigDecimal(16)); + assertEquals("Result is 20 SKK", new BigDecimal("20.00"), result.getConverted()); + } + + { + // convert 500SKK to CZK + ConversionResult result = convertSkkCzk.convert(new BigDecimal(500)); + assertEquals("Result is 400 CZK", new BigDecimal("400.00"), result.getConverted()); + assertEquals("No Remainer", BigDecimal.ZERO.setScale(2), result.getRemainder()); + } + + { + // convert 501SKK to CZK + ConversionResult result = convertSkkCzk.convert(new BigDecimal(501)); + assertEquals("Result is 400 CZK", new BigDecimal("400.80"), result.getConverted()); + assertEquals("No Remainer", BigDecimal.ZERO.setScale(2), result.getRemainder()); + + } + } + + /** + * Convert SKK to CZK. Convertor can't convert whole amout (can't convert one SKK cent to CZK). Remaining + * amount is stored in remainder result. + * + * Test is currently failing, because implementation can't handle this case. + */ +// public void testConvertSmallUnits_failing() { +// Convertor convertSkkCzk = createSKKtoCZK(); +// { +// // convert 501SKK to CZK +// ConversionResult result = convertSkkCzk.convert(new BigDecimal("501.01")); +// assertEquals("Result is 400 CZK", new BigDecimal("400.80"), result.getConverted()); +// assertEquals("No Remainer", new BigDecimal("0.01"), result.getRemainder()); +// +// } +// +// } + + /** + * Test converting from CZK to JPY. Remained has scale of CZK. + * + * This test is currently failing, because converter implementation currently can't handle conversion from "cent" to "no-cent" currency. + */ +// public void testConvertCzkToJpy_failing() { +// Convertor convertSkkCzk = createCZKtoYEN(); +// { +// // convert 501SKK to CZK +// ConversionResult result = convertSkkCzk.convert(new BigDecimal("120.00")); +// assertEquals("Result is 120 YEN", new BigDecimal("120"), result.getConverted()); +// assertEquals("No Remainer", new BigDecimal("0.00"), result.getRemainder()); +// +// } +// } + + /** + * Test converting from JPY to CZK. Remained has scale of JPY. + * + * This test is currently failing, because converter implementation currently can't handle conversion from "cent" to "no-cent" currency. + */ +// public void testConvertJpyToCzk_failing() { +// Convertor convertSkkCzk = createCZKtoYEN(); +// { +// // convert 501SKK to CZK +// ConversionResult result = convertSkkCzk.convert(new BigDecimal("120.00")); +// assertEquals("Result is 120 YEN", new BigDecimal("120"), result.getConverted()); +// assertEquals("No Remainer", new BigDecimal("0"), result.getRemainder()); +// +// } +// } + + public void testCannotConvertToSKKwithCZKUSDConvertor() throws Exception { + Convertor c = createCZKtoUSD(); + // convert $5 to SKK, the API shall say this is not possible + try { + c.convert(ConvertorCurrency.getInstance("USD"), ConvertorCurrency.getInstance("SKK"), new BigDecimal(5)); + fail(); + } catch (ConversionNotSupportedException e) { + //expected error; + assertEquals("Exception From USD", "USD",e.getFromCurrecyCode()); + assertEquals("Exception To SKK", "SKK",e.getToCurrecyCode()); + } + // convert 500 SKK to CZK, the API shall say this is not possible + try { + c.convert(ConvertorCurrency.getInstance("SKK"), ConvertorCurrency.getInstance("CZK"), new BigDecimal(500)); + fail(); + } catch (ConversionNotSupportedException e) { + assertEquals("Exception From USD", "SKK",e.getFromCurrecyCode()); + assertEquals("Exception To SKK", "CZK",e.getToCurrecyCode()); } + } + + +} + diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution13/test/org/apidesign/apifest08/test/Task2Test.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution13/test/org/apidesign/apifest08/test/Task2Test.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,136 @@ +package org.apidesign.apifest08.test; + +import java.math.BigDecimal; +import junit.framework.TestCase; +import org.apidesign.apifest08.currency.Convertor; +import org.apidesign.apifest08.currency.ConvertorCurrency; +import org.apidesign.apifest08.currency.ExchangeRateProvider; + +/** There are many currencies around the world and many banks manipulate + * with more than one or two at the same time. As banks are usually the + * best paying clients, which is true even in case of your Convertor API, + * it is reasonable to listen to their requests. + *

+ * The quest for today is to enhance your existing convertor API to hold + * information about many currencies and allow conversions between any of them. + * Also, as conversion rates for diferent currencies usually arise from various + * bank departments, there is another important need. There is a need to + * compose two convertors into one by merging all the information about + * currencies they know about. + */ +public class Task2Test extends TestCase { + private static ConvertorCurrency currencyCZK = ConvertorCurrency.getInstance("CZK"); + private static ConvertorCurrency currencySKK = ConvertorCurrency.getInstance("SKK"); + private static ConvertorCurrency currencyUSD = ConvertorCurrency.getInstance("USD"); + + public Task2Test(String testName) { + super(testName); + } + + @Override + protected void setUp() throws Exception { + + } + + @Override + protected void tearDown() throws Exception { + } + + public static Convertor createUsdToSkkConvertor() { + ConvertorCurrency fromCurrency = currencyUSD; + ConvertorCurrency toCurrency = currencySKK; + ExchangeRateProvider exchangeRateProvider = new ExchangeRateProvider(new BigDecimal(1), fromCurrency, new BigDecimal(20), toCurrency); + + return Convertor.createConvertor(exchangeRateProvider); + + } + + // As in Task1Test, keep in mind, that there are three parts + // of the whole system: + // 1. there is someone who knows the current exchange rate + // 2. there is someone who wants to do the conversion + // 3. there is the API between 1. and 2. which allows them to communicate + // + // Please backward compatibly enhance your existing API to support following + // usecases: + // + + /** Create convertor that understands two currencies, CZK and + * SKK. Make 100 SKK == 75 CZK. This is method for the group of users that + * knows the exchange rate, and needs to use the API to create objects + * with the exchange rate. Anyone shall be ready to call this method without + * any other method being called previously. The API itself shall know + * nothing about any rates, before this method is called. + */ + public static Convertor createTripleConvertor() { + ExchangeRateProvider exRateProvider = ExchangeRateProvider.createExchangeRateProvider(); + + // Rates: 1USD = 15CZK + exRateProvider.addFixedCurencyRate(currencyUSD, new BigDecimal(1),currencyCZK, new BigDecimal(15)); + + // Rates: 1USD = 20SKK + exRateProvider.addFixedCurencyRate(currencyUSD, new BigDecimal(1), currencySKK, new BigDecimal(20)); + + // Rates: 75CZK = 100SKK + exRateProvider.addFixedCurencyRate(currencyCZK, new BigDecimal(75), currencySKK, new BigDecimal(100)); + + Convertor c = Convertor.createConvertor(exRateProvider); + + return c; + } + + /** Define convertor that understands three currencies. Use it. + */ + public void testConvertorForUSDandCZKandSKK() throws Exception { + Convertor c = createTripleConvertor(); + + // convert $5 to CZK using c: + assertEquals("Result is 75 CZK",new BigDecimal("75.00"),c.convertWithReversibleRates(currencyUSD, currencyCZK, new BigDecimal(5)).getConverted()); + + + // convert $5 to SKK using c: + assertEquals("Result is 100 SKK",new BigDecimal("100.00"),c.convertWithReversibleRates(currencyUSD, currencySKK, new BigDecimal(5)).getConverted()); + + // convert 200SKK to CZK using c: + assertEquals("Result is 150 CZK",new BigDecimal("150.00"),c.convertWithReversibleRates(currencySKK, currencyCZK, new BigDecimal(200)).getConverted()); + + // convert 200SKK to USK using c: + // assertEquals("Result is 10 USD"); + } + + /** Merge all currency rates of convertor 1 with convertor 2. + * Implement this using your API, preferably this method just delegates + * into some API method which does the actual work, without requiring + * API clients to code anything complex. + */ + public static Convertor merge(Convertor one, Convertor two) { + return Convertor.createConvertorAsMerge(new Convertor[]{one, two}); + } + + /** Join the convertors from previous task, Task1Test and show that it + * can be used to do reasonable conversions. + */ + public void testConvertorComposition() throws Exception { + Convertor c = merge( + Task1Test.createCZKtoUSD(), + Task1Test.createSKKtoCZK() + ); + + // convert $5 to CZK using c: + assertEquals("Result is 85 CZK",new BigDecimal("85.00"),c.convertWithReversibleRates(currencyUSD, currencyCZK, new BigDecimal(5)).getConverted()); + + // convert $8 to CZK using c: + // assertEquals("Result is 136 CZK"); + assertEquals("Result is 136 CZK",new BigDecimal("136.00"),c.convertWithReversibleRates(currencyUSD, currencyCZK, new BigDecimal(8)).getConverted()); + + // convert 1003CZK to USD using c: + assertEquals("Result is 59 USD",new BigDecimal("59.00"),c.convertWithReversibleRates(currencyCZK, currencyUSD, new BigDecimal(1003)).getConverted()); + + // convert 16CZK using c: + assertEquals("Result is 20 SKK",new BigDecimal("20.00"),c.convertWithReversibleRates(currencyCZK, currencySKK, new BigDecimal(16)).getConverted()); + + // convert 500SKK to CZK using c: + assertEquals("Result is 400 CZK",new BigDecimal("400.00"),c.convertWithReversibleRates(currencySKK, currencyCZK, new BigDecimal(500)).getConverted()); + + } +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution13/test/org/apidesign/apifest08/test/Task3Test.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution13/test/org/apidesign/apifest08/test/Task3Test.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,122 @@ +package org.apidesign.apifest08.test; + +import java.math.BigDecimal; +import junit.framework.TestCase; +import org.apidesign.apifest08.currency.Convertor; +import org.apidesign.apifest08.currency.ConvertorCurrency; +import org.apidesign.apifest08.currency.ExchangeRateProvider; +import org.apidesign.apifest08.currency.IExchangeRateEngine; + +/** The exchange rates are not always the same. They are changing. Day by day, + * hour by hour, minute by minute. For every bank it is important to always + * have the actual exchange rate available in the system. That is why let's + * create a pluggable convertor that will always have up to date value of its + * exchange rate. + *

+ * The quest for today is to allow 3rd party developer to write a convertor + * that adjusts its exchange rate everytime it is queried. This convertor is + * written by independent vendor, the vendor knows only your Convertor API, + * he does not know how the whole system looks and how the convertor is supposed + * to be used. + */ +public class Task3Test extends TestCase { + + private static ConvertorCurrency currencyCZK = ConvertorCurrency.getInstance("CZK"); + private static ConvertorCurrency currencySKK = ConvertorCurrency.getInstance("SKK"); + private static ConvertorCurrency currencyUSD = ConvertorCurrency.getInstance("USD"); + + public Task3Test(String testName) { + super(testName); + } + + @Override + protected void setUp() throws Exception { + } + + @Override + protected void tearDown() throws Exception { + } + + // Backward compatibly enhance your existing API to support following + // usecases: + // + + + /** Without knowing anything about the surrounding system, write an + * implementation of convertor that will return different rates everytime + * it is queried. Convert USD to CZK and vice versa. Start with the rate of + * 1USD = 16CZK and adjust it in favor of CZK by 0.01 CZK with every query. + * As soon as you reach 1USD = 15CZK adjust it by 0.01 CZK in favor of USD + * until you reach 1USD = 16CZK + * + * @return new instance of "online" USD and CZK convertor starting with rate 1USD = 16CZK + */ + public static Convertor createOnlineCZKUSDConvertor() { + // initial rate: 1USD = 16CZK + // 2nd query 1USD = 15.99CZK + // 3rd query 1USD = 15.98CZK + // until 1USD = 15.00CZK + // then 1USD = 15.01CZK + // then 1USD = 15.02CZK + // and so on and on up to 1USD = 16CZK + // and then another round to 15, etc. + IExchangeRateEngine engine = BouncingExchangeRateEngine.create( + currencyUSD, new BigDecimal(1), + currencyCZK, + new BigDecimal(16),new BigDecimal(15), + new BigDecimal("-0.01")); + ExchangeRateProvider exRateProvider = ExchangeRateProvider.createExchangeRateProvider(engine); + Convertor convertor = Convertor.createConvertor(exRateProvider); + return convertor; + } + + public void testFewQueriesForOnlineConvertor() { + Convertor c = createOnlineCZKUSDConvertor(); + doFewQueriesForOnlineConvertor(c); + } + + static void doFewQueriesForOnlineConvertor(Convertor c) { + // convert $5 to CZK using c: + assertEquals("Result is 80 CZK", new BigDecimal("80.00"), c.convertWithReversibleRates(currencyUSD, currencyCZK, new BigDecimal(5)).getConverted()); + + // convert $8 to CZK using c: + assertEquals("Result is 127.92 CZK", new BigDecimal("127.92"), c.convertWithReversibleRates(currencyUSD, currencyCZK, new BigDecimal(8)).getConverted()); + + // convert $1 to CZK using c: + assertEquals("Result is 15.98 CZK", new BigDecimal("15.98"), c.convertWithReversibleRates(currencyUSD, currencyCZK, new BigDecimal(1)).getConverted()); + + // convert 15.97CZK to USD using c: + assertEquals("Result is 15.98 CZK", new BigDecimal("1.00"), c.convertWithReversibleRates(currencyCZK, currencyUSD , new BigDecimal("15.97")).getConverted()); + } + + /** Join the convertors and show they behave sane. + */ + public void testOnlineConvertorComposition() throws Exception { + Convertor c = Task2Test.merge( + createOnlineCZKUSDConvertor(), + Task1Test.createSKKtoCZK() + ); + + // convert 16CZK to SKK using c: + assertEquals("Result is 20 CZK", new BigDecimal("20.00"), c.convertWithReversibleRates(currencyCZK, currencySKK , new BigDecimal("16")).getConverted()); + + // convert 500SKK to CZK using c: + assertEquals("Result is 400 CZK", new BigDecimal("400.00"), c.convertWithReversibleRates(currencySKK, currencyCZK , new BigDecimal("500")).getConverted()); + + doFewQueriesForOnlineConvertor(c); + } + +// public void testBouncing() { +// Convertor c=createOnlineCZKUSDConvertor(); +// +// IExchangeRateEngine engine = BouncingExchangeRateEngine.create( +// currencyUSD, new BigDecimal(1), +// currencyCZK, +// new BigDecimal("16.00"),new BigDecimal("15.00"), +// new BigDecimal("-0.01")); +// +// for (int i=0;i<300;i++) { +// System.out.println(engine.getExchangeRate(currencyUSD, currencyCZK).getToValue()); +// } +// } +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution13/test/org/apidesign/apifest08/test/Task4Test.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution13/test/org/apidesign/apifest08/test/Task4Test.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,188 @@ +package org.apidesign.apifest08.test; + +import java.math.BigDecimal; +import java.text.SimpleDateFormat; +import java.util.Date; +import junit.framework.TestCase; +import org.apidesign.apifest08.currency.ConversionNotSupportedException; +import org.apidesign.apifest08.currency.Convertor; +import org.apidesign.apifest08.currency.ConvertorCurrency; +import org.apidesign.apifest08.currency.ExchangeRateProvider; + +/** The exchange rates are not always the same. They are changing. However + * as in order to predict the future, one needs to understand own past. That is + * why it is important to know the exchange rate as it was at any time during + * the past. + *

+ * Today's quest is to enhance the convertor API to deal with dates. + * One shall be able to convert a currency at any date. Each currencies rate shall + * be associated with a range between two Date objects. In order + * to keep compatibility with old API that knew nothing about dates, the + * rates associated then are applicable "for eternity". Any use of existing + * convert methods that do not accept a Date argument, uses the current + * System.currentTimeMillis() as default date. + */ +public class Task4Test extends TestCase { + private static ConvertorCurrency CZK = ConvertorCurrency.getInstance("CZK"); + private static ConvertorCurrency SKK = ConvertorCurrency.getInstance("SKK"); + private static ConvertorCurrency USD = ConvertorCurrency.getInstance("USD"); + private SimpleDateFormat df; + + + public Task4Test(String testName) { + super(testName); + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + df = new SimpleDateFormat("yyyy-MM-dd HH:mm zzzz"); + } + + @Override + protected void tearDown() throws Exception { + super.tearDown(); + df = null; + } + + // Backward compatibly enhance your existing API to support following + // usecases: + // + + /** Takes a convertor with any rates associated and creates new convertor + * that returns the same values as the old one for time between from to till. + * Otherwise it returns no results. This is just a helper method that + * shall call some real one in the API. + * + * @param old existing convertor + * @param from initial date (inclusive) + * @param till final date (exclusive) + * @return new convertor + */ + public static Convertor limitTo(Convertor old, Date from, Date till) { + Convertor c = Convertor.createConvertorAsMerge(new Convertor[]{old}); + c.limitAllowedDates(from, till); + return c; + } + + + public void testCompositionOfLimitedConvertors() throws Exception { + Date d1 = df.parse("2008-10-01 0:00 GMT"); + Date d2 = df.parse("2008-10-02 0:00 GMT"); + Date d3 = df.parse("2008-10-03 0:00 GMT"); + + Convertor c = Task2Test.merge( + limitTo(Task1Test.createCZKtoUSD(), d1, d2), + limitTo(Task1Test.createSKKtoCZK(), d2, d3) + ); + + // convert $5 to CZK using c: + // cannot convert as no rate is applicable to current date + try { + c.convert(USD, CZK, new BigDecimal(5)); + fail(); + } catch (ConversionNotSupportedException e) { + //exception expected + } + + // convert $8 to CZK using c: + // cannot convert as no rate is applicable to current date + try { + c.convert(USD, CZK, new BigDecimal(8)); + fail(); + } catch (ConversionNotSupportedException e) { + //exception expected + } + + + // convert 1003CZK to USD using c: + // cannot convert as no rate is applicable to current date + try { + c.convert(CZK, USD, new BigDecimal(1003)); + fail(); + } catch (ConversionNotSupportedException e) { + //exception expected + } + + // convert 16CZK using c: + // cannot convert as no rate is applicable to current date + // ??? + try { + c.convert(CZK, USD, new BigDecimal(16)); + fail(); + } catch (ConversionNotSupportedException e) { + //exception expected + } + + // convert 500SKK to CZK using c: + // cannot convert as no rate is applicable to current date + try { + c.convert(SKK, CZK, new BigDecimal(500)); + fail(); + } catch (ConversionNotSupportedException e) { + //exception expected + } + + + // convert $5 to CZK using c at 2008-10-01 6:00 GMT: + // assertEquals("Result is 85 CZK"); + assertEquals("Result is 85 CZK", new BigDecimal("85.00"), c.convertWithReversibleRates(USD, CZK , new BigDecimal("5"),df.parse("2008-10-01 6:00 GMT")).getConverted()); + + // convert $8 to CZK using c at 2008-10-01 6:00 GMT: + // assertEquals("Result is 136 CZK"); + assertEquals("Result is 136 CZK", new BigDecimal("136.00"), c.convertWithReversibleRates(USD, CZK , new BigDecimal("8"),df.parse("2008-10-01 6:00 GMT")).getConverted()); + + // convert 1003CZK to USD using c at 2008-10-01 6:00 GMT: + // assertEquals("Result is 59 USD"); + assertEquals("Result is 59 USD", new BigDecimal("59.00"), c.convertWithReversibleRates(CZK, USD , new BigDecimal("1003"),df.parse("2008-10-01 6:00 GMT")).getConverted()); + + // convert 16CZK using c at 2008-10-02 9:00 GMT: + // assertEquals("Result is 20 SKK"); + assertEquals("Result is 20 SKK", new BigDecimal("20.00"), c.convertWithReversibleRates(CZK, SKK , new BigDecimal("16"),df.parse("2008-10-02 9:00 GMT")).getConverted()); + + // convert 500SKK to CZK using c at 2008-10-02 9:00 GMT: + // assertEquals("Result is 400 CZK"); + assertEquals("Result is 400 SKK", new BigDecimal("400.00"), c.convertWithReversibleRates(SKK, CZK , new BigDecimal("500"),df.parse("2008-10-02 9:00 GMT")).getConverted()); + + // convert 500SKK to CZK using c at 2008-10-01 6:00 GMT: + // cannot convert as no rate is applicable to current date + try { + c.convertWithReversibleRates(SKK, CZK , new BigDecimal("500"),df.parse("2008-10-01 6:00 GMT")).getConverted(); + fail(); + } catch (ConversionNotSupportedException e) { + //exception expected + } + + } + + /** Create convertor that understands two currencies, CZK and + * SKK. Make 100 SKK == 90 CZK. + * + * @return prepared convertor ready for converting SKK to CZK and CZK to SKK + */ + public static Convertor createSKKtoCZK2() { + ExchangeRateProvider exchangeRateProvider = ExchangeRateProvider.createExchangeRateProvider(); + exchangeRateProvider.addFixedCurencyRate(SKK, new BigDecimal("100.00"), CZK, new BigDecimal("90.00")); + Convertor c = Convertor.createConvertor(exchangeRateProvider); + return c; + } + + public void testDateConvetorWithTwoDifferentRates() throws Exception { + + Date d1 = df.parse("2008-10-01 0:00 GMT"); + Date d2 = df.parse("2008-10-02 0:00 GMT"); + Date d3 = df.parse("2008-10-03 0:00 GMT"); + + Convertor c = Task2Test.merge( + limitTo(createSKKtoCZK2(), d1, d2), + limitTo(Task1Test.createSKKtoCZK(), d2, d3) + ); + + // convert 500SKK to CZK using c at 2008-10-02 9:00 GMT: + assertEquals("Result is 400 CZK", new BigDecimal("400.00"), c.convertWithReversibleRates(SKK, CZK , new BigDecimal("500"),df.parse("2008-10-02 9:00 GMT")).getConverted()); + + // convert 500SKK to CZK using c at 2008-10-01 6:00 GMT: + assertEquals("Result is 450 CZK", new BigDecimal("450.00"), c.convertWithReversibleRates(SKK, CZK , new BigDecimal("500"),df.parse("2008-10-01 9:00 GMT")).getConverted()); + } + +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution14/build.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution14/build.xml Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,69 @@ + + + + + + Builds, tests, and runs the project. + + + diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution14/nbproject/build-impl.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution14/nbproject/build-impl.xml Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,642 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set src.dir + Must set test.src.dir + Must set build.dir + Must set dist.dir + Must set build.classes.dir + Must set dist.javadoc.dir + Must set build.test.classes.dir + Must set build.test.results.dir + Must set build.classes.excludes + Must set dist.jar + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + + + + + + java -cp "${run.classpath.with.dist.jar}" ${main.class} + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + java -jar "${dist.jar.resolved}" + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set run.class + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set debug.class + + + + + Must set fix.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + Some tests failed; see details above. + + + + + + + + + Must select some files in the IDE or set test.includes + + + + Some tests failed; see details above. + + + + + Must select one file in the IDE or set test.class + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + + + + + + + + + + + diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution14/nbproject/genfiles.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution14/nbproject/genfiles.properties Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,8 @@ +build.xml.data.CRC32=2ab820eb +build.xml.script.CRC32=58a52595 +build.xml.stylesheet.CRC32=be360661 +# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. +# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. +nbproject/build-impl.xml.data.CRC32=1d0fd5f2 +nbproject/build-impl.xml.script.CRC32=951643da +nbproject/build-impl.xml.stylesheet.CRC32=e55b27f5 diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution14/nbproject/project.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution14/nbproject/project.properties Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,68 @@ +application.title=currency +application.vendor=apidesign.org +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.tab-size=8 +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.text-limit-width=80 +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.usedProfile=default +build.classes.dir=${build.dir}/classes +build.classes.excludes=**/*.java,**/*.form +# This directory is removed when the project is cleaned: +build.dir=build +build.generated.dir=${build.dir}/generated +# Only compile against the classpath explicitly listed here: +build.sysclasspath=ignore +build.test.classes.dir=${build.dir}/test/classes +build.test.results.dir=${build.dir}/test/results +debug.classpath=\ + ${run.classpath} +debug.test.classpath=\ + ${run.test.classpath} +# This directory is removed when the project is cleaned: +dist.dir=dist +dist.jar=${dist.dir}/currency.jar +dist.javadoc.dir=${dist.dir}/javadoc +excludes= +file.reference.junit-4.4.jar=../../libs/junit-4.4.jar +file.reference.src-apifest08=.. +includes=** +jar.compress=false +javac.classpath= +# Space-separated list of extra javac options +javac.compilerargs= +javac.deprecation=false +javac.source=1.5 +javac.target=1.5 +javac.test.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir}:\ + ${file.reference.junit-4.4.jar} +javadoc.additionalparam= +javadoc.author=false +javadoc.encoding= +javadoc.noindex=false +javadoc.nonavbar=false +javadoc.notree=false +javadoc.private=false +javadoc.splitindex=true +javadoc.use=true +javadoc.version=false +javadoc.windowtitle= +jnlp.codebase.type=local +jnlp.codebase.url=file:/home/jarda/src/apifest08/currency/dist +jnlp.descriptor=application +jnlp.enabled=false +jnlp.offline-allowed=false +jnlp.signed=false +meta.inf.dir=${src.dir}/META-INF +platform.active=default_platform +run.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +# Space-separated list of JVM arguments used when running the project +# (you may also define separate properties like run-sys-prop.name=value instead of -Dname=value +# or test-sys-prop.name=value to set system properties for unit tests): +run.jvmargs= +run.test.classpath=\ + ${javac.test.classpath}:\ + ${build.test.classes.dir} +src.dir=src +test.src.dir=test diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution14/nbproject/project.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution14/nbproject/project.xml Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,16 @@ + + + org.netbeans.modules.java.j2seproject + + + Currency Convertor Solution 14 + 1.6.5 + + + + + + + + + diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution14/src/org/apidesign/apifest08/currency/Convertor.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution14/src/org/apidesign/apifest08/currency/Convertor.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,286 @@ +package org.apidesign.apifest08.currency; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Date; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** This is the skeleton class for your API. You need to make it public, so + * it is accessible to your client code (currently in Task1Test.java) file. + *

+ * Feel free to create additional classes or rename this one, just keep all + * the API and its implementation in this package. Do not spread it outside + * to other packages. + */ +public final class Convertor { + //version 1 fields + + private String currency1 = null; + private String currency2 = null; + private Rate rate = null; + + //version 2 field + private List currencyRates = null; + + //version - for compatible mode + private int instanceVersion = 0; //compatible mode because of problem with empty currency and CZE -> CZE (1:2) rate + + Convertor(String currency1, String currency2, Rate rate) { + instanceVersion = 1; + if ((currency1 == null) || (currency2 == null) || (rate == null)) { + throw new IllegalArgumentException("All arguments have to be non-null."); + } + this.currency1 = currency1; + this.currency2 = currency2; + this.rate = rate; + } + + Convertor(final CurrencyRate ... currencyRate) { + instanceVersion = 2; + + if (currencyRate == null) { + throw new IllegalArgumentException("Parameter cannot be null."); + } + if (currencyRate.length == 0) { + throw new IllegalArgumentException("CurrencyRates cannot be empty."); + } + Set> currencies = new HashSet>(); + List curRates = new ArrayList(); + for (int i = 0; i < currencyRate.length; i++) { + final CurrencyRate curRat = currencyRate[i]; + if (curRat == null) { + throw new IllegalArgumentException("Parameter cannot be null."); + } + //check that currencyRate is not defined twice + Pair curPair= new Pair(curRat.getCurrency1(), curRat.getCurrency2()); + if (currencies.contains(curPair)) { + throw new IllegalArgumentException("Pair of currencies in a currency rate cannot be defined twice"); + } + currencies.add(curPair); + + if (curRat instanceof TimeLimitedCurrencyRate) { + curRates.add((TimeLimitedCurrencyRate)curRat); + } else { + curRates.add(new TimeLimitedCurrencyRate() { //create delegate which implements TimeLimitedCurrencyRate + public long getFromTime() { + return Long.MIN_VALUE; + } + + public long getToTime() { + return Long.MAX_VALUE; + } + + public String getCurrency1() { + return curRat.getCurrency1(); + } + + public String getCurrency2() { + return curRat.getCurrency2(); + } + + public Rate getRate() { + return curRat.getRate(); + } + }); + } + } + this.currencyRates = Collections.unmodifiableList(curRates); + } + + Convertor(final int fakeParameter, final TimeLimitedCurrencyRate ... currencyRate) { //use fake parameter just to specify which constructor should be invoked + instanceVersion = 3; + + if (currencyRate == null) { + throw new IllegalArgumentException("Parameter cannot be null."); + } + List curRates = new ArrayList(); + for (int i = 0; i < currencyRate.length; i++) { + final TimeLimitedCurrencyRate curRat = currencyRate[i]; + if (curRat == null) { + throw new IllegalArgumentException("Parameter cannot be null."); + } + + curRates.add(curRat); + } + this.currencyRates = Collections.unmodifiableList(curRates); + } + + public double convert(String fromCurrency, String toCurrency, int amount) { + return convert(fromCurrency, toCurrency, amount, System.currentTimeMillis()); + } + + public double convert(String fromCurrency, String toCurrency, int amount, Date date) { + if (date == null) { + throw new IllegalArgumentException("Date cannot be null"); + } + return convert(fromCurrency, toCurrency, amount, date.getTime()); + } + + public double convert(String fromCurrency, String toCurrency, int amount, long time) { + if (instanceVersion == 1) { + if ((fromCurrency == null) || (toCurrency == null)) { + throw new IllegalArgumentException("All arguments have to be non-null."); + } + + if (currency1.equals(fromCurrency) && currency2.equals(toCurrency)) { + return rate.convertAtoB(amount); + } else if (currency2.equals(fromCurrency) && currency1.equals(toCurrency)) { + return rate.convertBtoA(amount); + } else { + throw new IllegalArgumentException("Convertor " + this.toString() + + " cannot work with currencies " + fromCurrency + " and " + toCurrency + "."); + } + } else { //instanceVersion >= 2 + //find suitable convertor + for (TimeLimitedCurrencyRate curRate : currencyRates) { + if ((curRate.getCurrency1().equals(fromCurrency))&& + (curRate.getCurrency2().equals(toCurrency))&& + (curRate.getFromTime() <= time) && + (curRate.getToTime() >= time)) + { + return curRate.getRate().convertAtoB(amount); + } + } + //suitable convertor not found, try to find inverse convertor + for (TimeLimitedCurrencyRate curRate : currencyRates) { + if ((curRate.getCurrency2().equals(fromCurrency))&& + (curRate.getCurrency1().equals(toCurrency))&& + (curRate.getFromTime() <= time) && + (curRate.getToTime() >= time)) + { + return curRate.getRate().convertBtoA(amount); + } + } + //even inverse convertor not found + throw new IllegalArgumentException("Cannot work with selected currencies."); + } + } + + public double convert(String fromCurrency, String toCurrency, double amount) { + return convert(fromCurrency, toCurrency, amount, System.currentTimeMillis()); + } + + public double convert(String fromCurrency, String toCurrency, double amount, Date date) { + if (date == null) { + throw new IllegalArgumentException("Date cannot be null"); + } + return convert(fromCurrency, toCurrency, amount, date.getTime()); + } + + public double convert(String fromCurrency, String toCurrency, double amount, long time) { + if (instanceVersion == 1) { + if ((fromCurrency == null) || (toCurrency == null)) { + throw new IllegalArgumentException("All arguments have to be non-null."); + } + + if (currency1.equals(fromCurrency) && currency2.equals(toCurrency)) { + return rate.convertAtoB(amount); + } else if (currency2.equals(fromCurrency) && currency1.equals(toCurrency)) { + return rate.convertBtoA(amount); + } else { + throw new IllegalArgumentException("Convertor " + this.toString() + + " cannot work with currencies " + fromCurrency + " and " + toCurrency + "."); + } + } else { //instanceVersion >= 2 + //find suitable convertor + for (TimeLimitedCurrencyRate curRate : currencyRates) { + if ((curRate.getCurrency1().equals(fromCurrency))&& + (curRate.getCurrency2().equals(toCurrency))&& + (curRate.getFromTime() <= time) && + (curRate.getToTime() >= time)) + { + return curRate.getRate().convertAtoB(amount); + } + } + //suitable convertor not found, try to find inverse convertor + for (TimeLimitedCurrencyRate curRate : currencyRates) { + if ((curRate.getCurrency2().equals(fromCurrency))&& + (curRate.getCurrency1().equals(toCurrency))&& + (curRate.getFromTime() <= time) && + (curRate.getToTime() >= time)) + { + return curRate.getRate().convertBtoA(amount); + } + } + //even inverse convertor not found + throw new IllegalArgumentException("Cannot work with selected currencies."); + } + } + + /** + * Returns currency rates. If instantiated with constructor from vesion 1 + * it creates new collection with one CurrencyRate. + * Note, it can cause exception because of empty currencies or same currencies. + */ + public Collection getCurrencyRates() { + if (instanceVersion == 1) { + List ret = new ArrayList(); + ret.add(new CurrencyRateImpl(currency1, currency2, rate)); //here it checks that currency rate is not nonsense + return Collections.unmodifiableCollection(ret); + } else { //instanceVersion >= 2 + List ret = new ArrayList(currencyRates); + return Collections.unmodifiableCollection(ret); + } + } + + public Collection getTimeLimitedCurrencyRates() { + if (instanceVersion == 1) { + List ret = new ArrayList(); + ret.add(new CurrencyRateImpl(currency1, currency2, rate)); //here it checks that currency rate is not nonsense + return Collections.unmodifiableCollection(ret); + } else { //instanceVersion >= 2 + List ret = new ArrayList(currencyRates); + return Collections.unmodifiableCollection(ret); + } + } + + @Override + public String toString() { + if (instanceVersion == 1) { + return currency1 + currency2; + } else { //instanceVersion == 2 + return super.toString(); //better be compatible in future :-) + } + } + + @Override + public boolean equals(Object obj) { + if (instanceVersion == 1) { + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final Convertor other = (Convertor) obj; + if (this.currency1 != other.currency1 && (this.currency1 == null || !this.currency1.equals(other.currency1))) { + return false; + } + if (this.currency2 != other.currency2 && (this.currency2 == null || !this.currency2.equals(other.currency2))) { + return false; + } + if (this.rate != other.rate && (this.rate == null || !this.rate.equals(other.rate))) { + return false; + } + return true; + } else { //instanceVersion == 2 + return super.equals(obj); //better be compatible in future :-) + } + } + + @Override + public int hashCode() { + if (instanceVersion == 1) { + int hash = 5; + hash = 67 * hash + (this.currency1 != null ? this.currency1.hashCode() : 0); + hash = 67 * hash + (this.currency2 != null ? this.currency2.hashCode() : 0); + hash = 67 * hash + (this.rate != null ? this.rate.hashCode() : 0); + return hash; + } else { //instanceVersion == 2 + return super.hashCode(); //better be compatible in future :-) + } + } +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution14/src/org/apidesign/apifest08/currency/ConvertorFactory.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution14/src/org/apidesign/apifest08/currency/ConvertorFactory.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,118 @@ + +package org.apidesign.apifest08.currency; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.List; + +public final class ConvertorFactory { + + //Singleton + private static ConvertorFactory thisFactory = new ConvertorFactory(); + private ConvertorFactory() {}; + public static ConvertorFactory newInstance() { //ehm, mistake - it should be named getInstance + return thisFactory; + } + + public Convertor createConvertor(String currency1, String currency2, Rate rate) { + return new Convertor(currency1, currency2, rate); + } + + public Convertor createConvertor(String currency1, String currency2, int amount1, int amount2) { + return new Convertor(currency1, currency2, new Rate(amount1, amount2)); + } + + public Convertor createConvertor(String currency1, String currency2, double amount1, double amount2) { + return new Convertor(currency1, currency2, new Rate(amount1, amount2)); + } + + public Convertor createConvertor(String currency1, String currency2, double rate) { + return new Convertor(currency1, currency2, new Rate(rate)); + } + + public Convertor createConvertor(CurrencyRate currencyRate) { + return new Convertor(currencyRate); + } + + public Convertor createConvertor(CurrencyRate ... currencyRates) { + return new Convertor(currencyRates); + } + + public Convertor mergeConvertors(Convertor ... convertors) { + if (convertors == null) { + throw new IllegalArgumentException("Parameter cannot be null."); + } + if (convertors.length == 0) { + throw new IllegalArgumentException("Convertors cannot be empty."); + } + List currRates = new ArrayList(); + List> currPairs = new ArrayList>(); + for (Convertor convertor : convertors) { + if (convertor == null) { + throw new IllegalArgumentException("Parameter cannot be null."); + } + for (CurrencyRate currRate : convertor.getCurrencyRates()) { + Pair currPair = new Pair(currRate.getCurrency1(), currRate.getCurrency2()); + if (currPairs.contains(currPair)) { + throw new IllegalArgumentException("Cannot merge - convertors contain same currency rates."); + } + currPairs.add(currPair); + currRates.add(currRate); + } + } + + return new Convertor(currRates.toArray(new CurrencyRate[0])); + } + + public Convertor mergeConvertorsIgnoreEqualCurrencies(Convertor ... convertors) { + if (convertors == null) { + throw new IllegalArgumentException("Parameter cannot be null."); + } + if (convertors.length == 0) { + throw new IllegalArgumentException("Convertors cannot be empty."); + } + List currRates = new ArrayList(); + for (Convertor convertor : convertors) { + if (convertor == null) { + throw new IllegalArgumentException("Parameter cannot be null."); + } + currRates.addAll(convertor.getTimeLimitedCurrencyRates()); + } + + return new Convertor(4, currRates.toArray(new TimeLimitedCurrencyRate[0])); + } + + public Convertor limitConvertor(Convertor convertor, Date fromDate, Date toDate) { + if ((convertor == null)||(fromDate == null)||(toDate == null)) { + throw new IllegalArgumentException("Parameter cannot be null"); + } + Collection timeLimitedCurrencyRates = convertor.getTimeLimitedCurrencyRates(); + List filteredRates = new ArrayList(); + for (final TimeLimitedCurrencyRate timeLimitedCurrencyRate : timeLimitedCurrencyRates) { + final long newFrom = java.lang.Math.max(fromDate.getTime(), timeLimitedCurrencyRate.getFromTime()); + final long newTo = java.lang.Math.min(toDate.getTime(), timeLimitedCurrencyRate.getToTime()); + if (newTo >= newFrom) { + filteredRates.add(new TimeLimitedCurrencyRate() { //create delegate + public long getFromTime() { + return newFrom; + } + public long getToTime() { + return newTo; + } + public String getCurrency1() { + return timeLimitedCurrencyRate.getCurrency1(); + } + public String getCurrency2() { + return timeLimitedCurrencyRate.getCurrency2(); + } + public Rate getRate() { + return timeLimitedCurrencyRate.getRate(); + } + }); + } + } + return new Convertor(4, filteredRates.toArray(new TimeLimitedCurrencyRate[0])); + } + +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution14/src/org/apidesign/apifest08/currency/CurrencyRate.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution14/src/org/apidesign/apifest08/currency/CurrencyRate.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,11 @@ +package org.apidesign.apifest08.currency; + +/** + * This is interface for creating currency rates. The rate can be static or can change in time. + * Implement this interface to inform the Convertor about the actual exchange rate between two currencies. + */ +public interface CurrencyRate { + public String getCurrency1(); + public String getCurrency2(); + public Rate getRate(); +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution14/src/org/apidesign/apifest08/currency/CurrencyRateFactory.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution14/src/org/apidesign/apifest08/currency/CurrencyRateFactory.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,37 @@ +package org.apidesign.apifest08.currency; + + +public final class CurrencyRateFactory { + + //Singleton + private static CurrencyRateFactory thisFactory = new CurrencyRateFactory(); + private CurrencyRateFactory() {}; + public static CurrencyRateFactory getInstance() { + return thisFactory; + } + + public CurrencyRate createCurrencyRate(final String currency1, final String currency2, final Rate rate) { + return new CurrencyRateImpl(currency1, currency2, rate); + } + + public CurrencyRate createCurrencyRate(final String currency1, final String currency2, int amount1, int amount2) { + return new CurrencyRateImpl(currency1, currency2, new Rate(amount1, amount2)); + } + + public CurrencyRate createCurrencyRate(final String currency1, final String currency2, double amount1, double amount2) { + return new CurrencyRateImpl(currency1, currency2, new Rate(amount1, amount2)); + } + + public TimeLimitedCurrencyRate createCurrencyRateTimeLimited(final String currency1, final String currency2, final Rate rate, long fromTime, long toTime) { + return new CurrencyRateImpl(currency1, currency2, rate, fromTime, toTime); + } + + public TimeLimitedCurrencyRate createCurrencyRateTimeLimited(final String currency1, final String currency2, int amount1, int amount2, long fromTime, long toTime) { + return new CurrencyRateImpl(currency1, currency2, new Rate(amount1, amount2), fromTime, toTime); + } + + public TimeLimitedCurrencyRate createCurrencyRateTimeLimited(final String currency1, final String currency2, double amount1, double amount2, long fromTime, long toTime) { + return new CurrencyRateImpl(currency1, currency2, new Rate(amount1, amount2), fromTime, toTime); + } + +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution14/src/org/apidesign/apifest08/currency/CurrencyRateImpl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution14/src/org/apidesign/apifest08/currency/CurrencyRateImpl.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,70 @@ + +package org.apidesign.apifest08.currency; + +public final class CurrencyRateImpl implements CurrencyRate, TimeLimitedCurrencyRate { + private String currency1; + private String currency2; + private Rate rate; + private long fromTime; + private long toTime; + + CurrencyRateImpl(final String currency1, final String currency2, final Rate rate) { + if ((currency1 == null)||(currency2 == null) || (rate == null)) { + throw new IllegalArgumentException("Argument cannot be null."); + } + if ("".equals(currency1) || "".equals(currency2)) { + throw new IllegalArgumentException("Name of currency cannot be empty string"); + } + if (currency1.equals(currency2)) { + throw new IllegalArgumentException("Currencies in rate cannot be the same"); + } + + this.currency1 = currency1; + this.currency2 = currency2; + this.rate = rate; + this.fromTime = Long.MIN_VALUE; + this.toTime = Long.MAX_VALUE; + } + + CurrencyRateImpl(final String currency1, final String currency2, final Rate rate, final long fromTime, final long toTime) { + if ((currency1 == null)||(currency2 == null) || (rate == null)) { + throw new IllegalArgumentException("Argument cannot be null."); + } + if ("".equals(currency1) || "".equals(currency2)) { + throw new IllegalArgumentException("Name of currency cannot be empty string"); + } + if (currency1.equals(currency2)) { + throw new IllegalArgumentException("Currencies in rate cannot be the same"); + } + if (fromTime > toTime) { + throw new IllegalArgumentException("Invalid time range"); + } + + this.currency1 = currency1; + this.currency2 = currency2; + this.rate = rate; + this.fromTime = fromTime; + this.toTime = toTime; + } + + public String getCurrency1() { + return currency1; + } + + public String getCurrency2() { + return currency2; + } + + public Rate getRate(){ + return rate; + } + + public long getFromTime() { + return fromTime; + } + + public long getToTime() { + return toTime; + } + +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution14/src/org/apidesign/apifest08/currency/Pair.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution14/src/org/apidesign/apifest08/currency/Pair.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,53 @@ + +package org.apidesign.apifest08.currency; + + +public final class Pair { + + private final A first; + private final B second; + + public Pair(A first, B second) { + this.first = first; + this.second = second; + } + + public A getFirst() { return first; } + public B getSecond() { return second; } + + @Override + public String toString() { + return "(" + first + ", " + second + ")"; + } + + private static boolean equals(Object x, Object y) { + return (x == null && y == null) || (x != null && x.equals(y)); + } + + @Override + public int hashCode() { + int hash = 5; + hash = 59 * hash + (this.first != null ? this.first.hashCode() : 0); + hash = 59 * hash + (this.second != null ? this.second.hashCode() : 0); + return hash; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final Pair other = (Pair) obj; + if (this.first != other.first && (this.first == null || !this.first.equals(other.first))) { + return false; + } + if (this.second != other.second && (this.second == null || !this.second.equals(other.second))) { + return false; + } + return true; + } + +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution14/src/org/apidesign/apifest08/currency/Rate.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution14/src/org/apidesign/apifest08/currency/Rate.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,68 @@ + +package org.apidesign.apifest08.currency; + +public final class Rate { + + private double rate; + + public Rate(int amountA, int amountB) { + rate = amountA / (double)amountB; + if (rate <= 0) { + throw new IllegalArgumentException("Exchange rate must be positive."); + } + } + + public Rate(double amountA, double amountB) { + rate = amountA / amountB; + if (rate <= 0) { + throw new IllegalArgumentException("Exchange rate must be positive."); + } + } + + public Rate(double rate) { + this.rate = rate; + if (this.rate <= 0) { + throw new IllegalArgumentException("Exchange rate must be positive."); + } + } + + public double convertAtoB(int a) { + return a / rate; + } + + public double convertAtoB(double a) { + return a / rate; + } + + public double convertBtoA(int b) { + return b * rate; + } + + public double convertBtoA(double b) { + return b * rate; + } + + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final Rate other = (Rate) obj; + return true; + } + + @Override + public int hashCode() { + int hash = 5; + return hash; + } + + @Override + public String toString() { + return ""+rate; + } +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution14/src/org/apidesign/apifest08/currency/TimeLimitedCurrencyRate.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution14/src/org/apidesign/apifest08/currency/TimeLimitedCurrencyRate.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,9 @@ +package org.apidesign.apifest08.currency; + + +public interface TimeLimitedCurrencyRate extends CurrencyRate { + + public long getFromTime(); + public long getToTime(); + +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution14/test/org/apidesign/apifest08/test/Task1Test.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution14/test/org/apidesign/apifest08/test/Task1Test.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,144 @@ +package org.apidesign.apifest08.test; + +import junit.framework.TestCase; +import org.apidesign.apifest08.currency.Convertor; +import org.apidesign.apifest08.currency.ConvertorFactory; + +/** Finish the Convertor API, and then write bodies of methods inside + * of this class to match the given tasks. To fullfil your task, use the + * API define in the org.apidesign.apifest08.currency package. + * Do not you reflection, or other hacks as your code + * shall run without any runtime permissions. + */ +public class Task1Test extends TestCase { + public Task1Test(String testName) { + super(testName); + } + + @Override + protected void setUp() throws Exception { + } + + @Override + protected void tearDown() throws Exception { + } + + // + // Imagine that there are three parts of the whole system: + // 1. there is someone who knows the current exchange rate + // 2. there is someone who wants to do the conversion + // 3. there is the API between 1. and 2. which allows them to communicate + // Please design such API + // + + /** Create convertor that understands two currencies, CZK and + * USD. Make 1 USD == 17 CZK. This is a method provided for #1 group - + * e.g. those that know the exchange rate. They somehow need to create + * the objects from the API and tell them the exchange rate. The API itself + * knows nothing about any rates, before the createCZKtoUSD method is called. + * + * Creation of the convertor shall not require subclassing of any class + * or interface on the client side. + * + * @return prepared convertor ready for converting USD to CZK and CZK to USD + */ + public static Convertor createCZKtoUSD() { + return ConvertorFactory.newInstance().createConvertor("CZK", "USD", 17, 1); + } + + /** Create convertor that understands two currencies, CZK and + * SKK. Make 100 SKK == 80 CZK. Again this is method for the #1 group - + * it knows the exchange rate, and needs to use the API to create objects + * with the exchange rate. Anyone shall be ready to call this method without + * any other method being called previously. The API itself shall know + * nothing about any rates, before this method is called. + * + * Creation of the convertor shall not require subclassing of any class + * or interface on the client side. + * + * @return prepared convertor ready for converting SKK to CZK and CZK to SKK + */ + public static Convertor createSKKtoCZK() { + return ConvertorFactory.newInstance().createConvertor("SKK", "CZK", 100, 80); + } + + // + // now the methods for group #2 follow: + // this group knows nothing about exchange rates, but knows how to use + // the API to do conversions. It somehow (by calling one of the factory + // methods) gets objects from the API and uses them to do the conversions. + // + + /** Use the convertor from createCZKtoUSD method and do few conversions + * with it. + */ + public void testCurrencyCZKUSD() throws Exception { + Convertor c = createCZKtoUSD(); + // convert $5 to CZK using c: + assertEquals("Result is 85 CZK", 85.0, c.convert("USD", "CZK", 5)); + + // convert $8 to CZK + assertEquals("Result is 136 CZK", 136.0, c.convert("USD", "CZK", 8)); + + // convert 1003CZK to USD + assertEquals("Result is 59 CZK", 59.0, c.convert("CZK", "USD", 1003)); + } + + /** Use the convertor from createSKKtoCZK method and do few conversions + * with it. + */ + public void testCurrencySKKCZK() throws Exception { + Convertor c = createSKKtoCZK(); + // convert 16CZK using c: + // assertEquals("Result is 20 SKK"); + assertEquals("Result is 20 SKK", 20.0, c.convert("CZK", "SKK", 16)); + + // convert 500SKK to CZK + // assertEquals("Result is 400 CZK"); + assertEquals("Result is 400 SKK", 400.0, c.convert("SKK", "CZK", 500)); + } + + /** Verify that the CZK to USD convertor knows nothing about SKK. + */ + public void testCannotConvertToSKKwithCZKUSDConvertor() throws Exception { + Convertor c = createCZKtoUSD(); + // convert $5 to SKK, the API shall say this is not possible + try { + c.convert("USD", "SKK", 5); + fail("Converting SKK with CZKUSD convertor is impossible"); + } catch (IllegalArgumentException e){ + //ok + } + + // convert 500 SKK to CZK, the API shall say this is not possible + try { + c.convert("SKK", "CZK", 500); + fail("Converting SKK with CZKUSD convertor is impossible"); + } catch (IllegalArgumentException e){ + //ok + } + + } + + /** Verify that the CZK to SKK convertor knows nothing about USD. + */ + public void testCannotConvertToUSDwithCZKSKKConvertor() throws Exception { + Convertor c = createSKKtoCZK(); + // convert $5 to SKK, the API shall say this is not possible + try { + c.convert("USD", "SKK", 5); + fail("Converting SKK with SKKCZK convertor is impossible"); + } catch (IllegalArgumentException e){ + //ok + } + + // convert 500 CZK to USD, the API shall say this is not possible + try { + c.convert("CZK", "USD", 500); + fail("Converting USD with SKKCZK convertor is impossible"); + } catch (IllegalArgumentException e){ + //ok + } + + } +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution14/test/org/apidesign/apifest08/test/Task2Test.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution14/test/org/apidesign/apifest08/test/Task2Test.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,169 @@ +package org.apidesign.apifest08.test; + +import junit.framework.TestCase; +import org.apidesign.apifest08.currency.Convertor; +import org.apidesign.apifest08.currency.ConvertorFactory; +import org.apidesign.apifest08.currency.CurrencyRate; +import org.apidesign.apifest08.currency.CurrencyRateFactory; + +/** There are many currencies around the world and many banks manipulate + * with more than one or two at the same time. As banks are usually the + * best paying clients, which is true even in case of your Convertor API, + * it is reasonable to listen to their requests. + *

+ * The quest for today is to enhance your existing convertor API to hold + * information about many currencies and allow conversions between any of them. + * Also, as conversion rates for diferent currencies usually arise from various + * bank departments, there is another important need. There is a need to + * compose two convertors into one by merging all the information about + * currencies they know about. + */ +public class Task2Test extends TestCase { + public Task2Test(String testName) { + super(testName); + } + + @Override + protected void setUp() throws Exception { + } + + @Override + protected void tearDown() throws Exception { + } + + // As in Task1Test, keep in mind, that there are three parts + // of the whole system: + // 1. there is someone who knows the current exchange rate + // 2. there is someone who wants to do the conversion + // 3. there is the API between 1. and 2. which allows them to communicate + // + // Please backward compatibly enhance your existing API to support following + // usecases: + // + + /** Create convertor that understands two currencies, CZK and + * SKK. Make 100 SKK == 75 CZK. This is method for the group of users that + * knows the exchange rate, and needs to use the API to create objects + * with the exchange rate. Anyone shall be ready to call this method without + * any other method being called previously. The API itself shall know + * nothing about any rates, before this method is called. + */ + public static Convertor createTripleConvertor() { + // Rates: 1USD = 15CZK + // Rates: 1USD = 20SKK + // Rates: 75CZK = 100SKK + CurrencyRate usdCzk = CurrencyRateFactory.getInstance().createCurrencyRate("USD", "CZK", 1, 15); + CurrencyRate usdSkk = CurrencyRateFactory.getInstance().createCurrencyRate("USD", "SKK", 1, 20); + CurrencyRate czkSkk = CurrencyRateFactory.getInstance().createCurrencyRate("CZK", "SKK", 75, 100); + return ConvertorFactory.newInstance().createConvertor(usdCzk, usdSkk, czkSkk); + } + + /** Define convertor that understands three currencies. Use it. + */ + public void testConvertorForUSDandCZKandSKK() throws Exception { + Convertor c = createTripleConvertor(); + + // convert $5 to CZK using c: + // assertEquals("Result is 75 CZK"); + assertEquals("Result is 75 CZK", 75.0, c.convert("USD", "CZK", 5)); + + // convert $5 to SKK using c: + // assertEquals("Result is 100 SKK"); + assertEquals("Result is 100 SKK", 100.0, c.convert("USD", "SKK", 5)); + + // convert 200SKK to CZK using c: + // assertEquals("Result is 150 CZK"); + assertEquals("Result is 150 CZK", 150.0, c.convert("SKK", "CZK", 200)); + + // convert 200SKK to USD using c: + // assertEquals("Result is 10 USD"); + assertEquals("Result is 10 USD", 10.0, c.convert("SKK", "USD", 200)); + } + + /** Merge all currency rates of convertor 1 with convertor 2. + * Implement this using your API, preferably this method just delegates + * into some API method which does the actual work, without requiring + * API clients to code anything complex. + */ + public static Convertor merge(Convertor one, Convertor two) { + return ConvertorFactory.newInstance().mergeConvertorsIgnoreEqualCurrencies(one,two); + } + + /** Join the convertors from previous task, Task1Test and show that it + * can be used to do reasonable conversions. + */ + public void testConvertorComposition() throws Exception { + Convertor c = merge( + Task1Test.createCZKtoUSD(), + Task1Test.createSKKtoCZK() + ); + + // convert $5 to CZK using c: + // assertEquals("Result is 85 CZK"); + assertEquals("Result is 85 CZK", 85.0, c.convert("USD", "CZK", 5)); + + // convert $8 to CZK using c: + // assertEquals("Result is 136 CZK"); + assertEquals("Result is 136 CZK", 136.0, c.convert("USD", "CZK", 8)); + + // convert 1003CZK to USD using c: + // assertEquals("Result is 59 USD"); + assertEquals("Result is 59 USD", 59.0, c.convert("CZK", "USD", 1003)); + + // convert 16CZK using c: + // assertEquals("Result is 20 SKK"); + assertEquals("Result is 20 SKK", 20.0, c.convert("CZK", "SKK", 16)); + + // convert 500SKK to CZK using c: + // assertEquals("Result is 400 CZK"); + assertEquals("Result is 400 CZK", 400.0, c.convert("SKK", "CZK", 500)); + + //test exceptions + Convertor one = Task1Test.createCZKtoUSD(); + Convertor two = Task1Test.createSKKtoCZK(); + Convertor three = Task1Test.createSKKtoCZK(); + try { + ConvertorFactory.newInstance().mergeConvertors(one,two,three); + fail(); + } catch (IllegalArgumentException e) { + //ok + } + + //test exceptions + try { + ConvertorFactory.newInstance().mergeConvertors(c, two); + fail(); + } catch (IllegalArgumentException e) { + //ok + } + + //try convertors from version 1 + Convertor v1one = ConvertorFactory.newInstance().createConvertor("CZE", "CZE", 1, 2); + assertEquals("CZE->CZE 1:2 10 expects 20", 20.0, v1one.convert("CZE", "CZE", 10)); + try { + ConvertorFactory.newInstance().mergeConvertors(v1one, two); + fail(); + } catch (IllegalArgumentException e) { + //ok + } + + Convertor v1two = ConvertorFactory.newInstance().createConvertor("EUR", "", 1, 2); + assertEquals("EUR->'' 1:2 10 expects 20", 20.0, v1two.convert("EUR", "", 10)); + try { + ConvertorFactory.newInstance().mergeConvertors(v1two, two); + fail(); + } catch (IllegalArgumentException e) { + //ok + } + + Convertor v1three = ConvertorFactory.newInstance().createConvertor("EUR", "", 1, 2); + assertEquals("''->EUR 1:2 10 expects 5", 5.0, v1three.convert("", "EUR", 10)); + try { + ConvertorFactory.newInstance().mergeConvertors(v1three, two); + fail(); + } catch (IllegalArgumentException e) { + //ok + } + + } +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution14/test/org/apidesign/apifest08/test/Task3Test.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution14/test/org/apidesign/apifest08/test/Task3Test.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,135 @@ +package org.apidesign.apifest08.test; + +import junit.framework.TestCase; +import org.apidesign.apifest08.currency.Convertor; +import org.apidesign.apifest08.currency.ConvertorFactory; +import org.apidesign.apifest08.currency.CurrencyRate; +import org.apidesign.apifest08.currency.Rate; + +/** The exchange rates are not always the same. They are changing. Day by day, + * hour by hour, minute by minute. For every bank it is important to always + * have the actual exchange rate available in the system. That is why let's + * create a pluggable convertor that will always have up to date value of its + * exchange rate. + *

+ * The quest for today is to allow 3rd party developer to write a convertor + * that adjusts its exchange rate everytime it is queried. This convertor is + * written by independent vendor, the vendor knows only your Convertor API, + * he does not know how the whole system looks and how the convertor is supposed + * to be used. + */ +public class Task3Test extends TestCase { + public Task3Test(String testName) { + super(testName); + } + + @Override + protected void setUp() throws Exception { + } + + @Override + protected void tearDown() throws Exception { + } + + // Backward compatibly enhance your existing API to support following + // usecases: + // + + + /** Without knowing anything about the surrounding system, write an + * implementation of convertor that will return different rates everytime + * it is queried. Convert USD to CZK and vice versa. Start with the rate of + * 1USD = 16CZK and adjust it in favor of CZK by 0.01 CZK with every query. + * As soon as you reach 1USD = 15CZK adjust it by 0.01 CZK in favor of USD + * until you reach 1USD = 16CZK + * + * @return new instance of "online" USD and CZK convertor starting with rate 1USD = 16CZK + */ + public static Convertor createOnlineCZKUSDConvertor() { + // initial rate: 1USD = 16CZK + // 2nd query 1USD = 15.99CZK + // 3rd query 1USD = 15.98CZK + // until 1USD = 15.00CZK + // then 1USD = 15.01CZK + // then 1USD = 15.02CZK + // and so on and on up to 1USD = 16CZK + // and then another round to 15, etc. + CurrencyRate onlineCurrencyRate = new CurrencyRate() { + private int usdAmount = 100; + private int czkAmount = 1600; + private boolean up = false; + public String getCurrency1() { + return "USD"; + } + + public String getCurrency2() { + return "CZK"; + } + + public Rate getRate() { //return Rate according to online status + Rate rate = new Rate(usdAmount, czkAmount); + if (up) { + if (czkAmount < 1600) { + czkAmount++; + } else { + up = false; + czkAmount--; + } + } else { //down + if (czkAmount > 1500) { + czkAmount--; + } else { + up = true; + czkAmount++; + } + } + return rate; + } + }; + + return ConvertorFactory.newInstance().createConvertor(onlineCurrencyRate); + } + + public void testFewQueriesForOnlineConvertor() { + Convertor c = createOnlineCZKUSDConvertor(); + doFewQueriesForOnlineConvertor(c); + } + + static void doFewQueriesForOnlineConvertor(Convertor c) { + // convert $5 to CZK using c: + //assertEquals("Result is 80 CZK"); + assertEquals("Result is 80 CZK", 80.0, c.convert("USD", "CZK", 5), 0.001); + + // convert $8 to CZK using c: + //assertEquals("Result is 127.92 CZK"); + assertEquals("Result is 127.92 CZK", 127.92, c.convert("USD", "CZK", 8), 0.001); + + // convert $1 to CZK using c: + //assertEquals("Result is 15.98 CZK"); + assertEquals("Result is 15.98 CZK", 15.98, c.convert("USD", "CZK", 1), 0.001); + + // convert 15.97CZK to USD using c: + //assertEquals("Result is 1$"); + assertEquals("Result is 1$", 1.0, c.convert("CZK", "USD", 15.97), 0.001); + + } + + /** Join the convertors and show they behave sane. + */ + public void testOnlineConvertorComposition() throws Exception { + Convertor c = Task2Test.merge( + createOnlineCZKUSDConvertor(), + Task1Test.createSKKtoCZK() + ); + + // convert 16CZK to SKK using c: + // assertEquals("Result is 20 SKK"); + assertEquals("Result is 20 SKK", 20.0, c.convert("CZK", "SKK", 16), 0.001); + + // convert 500SKK to CZK using c: + // assertEquals("Result is 400 CZK"); + assertEquals("Result is 400 CZK", 400.0, c.convert("SKK", "CZK", 500), 0.001); + + doFewQueriesForOnlineConvertor(c); + } +} diff -r 0c910349ba67 -r 067f86d76ac7 task4/solution14/test/org/apidesign/apifest08/test/Task4Test.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution14/test/org/apidesign/apifest08/test/Task4Test.java Sat Oct 18 07:47:34 2008 +0200 @@ -0,0 +1,167 @@ +package org.apidesign.apifest08.test; + +import java.util.Date; +import java.util.GregorianCalendar; +import junit.framework.TestCase; +import org.apidesign.apifest08.currency.Convertor; +import org.apidesign.apifest08.currency.ConvertorFactory; + +/** The exchange rates are not always the same. They are changing. However + * as in order to predict the future, one needs to understand own past. That is + * why it is important to know the exchange rate as it was at any time during + * the past. + *

+ * Today's quest is to enhance the convertor API to deal with dates. + * One shall be able to convert a currency at any date. Each currencies rate shall + * be associated with a range between two Date objects. In order + * to keep compatibility with old API that knew nothing about dates, the + * rates associated then are applicable "for eternity". Any use of existing + * convert methods that do not accept a Date argument, uses the current + * System.currentTimeMillis() as default date. + */ +public class Task4Test extends TestCase { + public Task4Test(String testName) { + super(testName); + } + + @Override + protected void setUp() throws Exception { + } + + @Override + protected void tearDown() throws Exception { + } + + // Backward compatibly enhance your existing API to support following + // usecases: + // + + /** Takes a convertor with any rates associated and creates new convertor + * that returns the same values as the old one for time between from to till. + * Otherwise it returns no results. This is just a helper method that + * shall call some real one in the API. + * + * @param old existing convertor + * @param from initial date (inclusive) + * @param till final date (exclusive) + * @return new convertor + */ + public static Convertor limitTo(Convertor old, Date from, Date till) { + return ConvertorFactory.newInstance().limitConvertor(old, from, till); + } + + + public void testCompositionOfLimitedConvertors() throws Exception { + Date d1 = (new GregorianCalendar(2008, 9, 1, 0, 0)).getTime(); // 2008-10-01 0:00 GMT + Date d2 = (new GregorianCalendar(2008, 9, 2, 0, 0)).getTime(); // 2008-10-02 0:00 GMT + Date d3 = (new GregorianCalendar(2008, 9, 3, 0, 0)).getTime(); // 2008-10-03 0:00 GMT + + Convertor c = Task2Test.merge( + limitTo(Task1Test.createCZKtoUSD(), d1, d2), + limitTo(Task1Test.createSKKtoCZK(), d2, d3) + ); + + // convert $5 to CZK using c: + // cannot convert as no rate is applicable to current date + try { + c.convert("USD", "CZK", 5); + fail(); + } catch (IllegalArgumentException e) { + //ok + } + + // convert $8 to CZK using c: + // cannot convert as no rate is applicable to current date + try { + c.convert("USD", "CZK", 8); + fail(); + } catch (IllegalArgumentException e) { + //ok + } + + // convert 1003CZK to USD using c: + // cannot convert as no rate is applicable to current date + try { + c.convert("CZK", "USD", 1003); + fail(); + } catch (IllegalArgumentException e) { + //ok + } + + // convert 16CZK using c: + // cannot convert as no rate is applicable to current date + try { + c.convert("CZK", "USD", 16); + fail(); + } catch (IllegalArgumentException e) { + //ok + } + + // convert 500SKK to CZK using c: + // cannot convert as no rate is applicable to current date + try { + c.convert("SKK", "CZK", 500); + fail(); + } catch (IllegalArgumentException e) { + //ok + } + + // convert $5 to CZK using c at 2008-10-01 6:00 GMT: + // assertEquals("Result is 85 CZK"); + assertEquals("Result is 85 CZK", 85.0, c.convert("USD", "CZK", 5, (new GregorianCalendar(2008,9,1,6,0)).getTime())); + + // convert $8 to CZK using c at 2008-10-01 6:00 GMT: + // assertEquals("Result is 136 CZK"); + assertEquals("Result is 136 CZK", 136.0, c.convert("USD", "CZK", 8, (new GregorianCalendar(2008,9,1,6,0)).getTime())); + + // convert 1003CZK to USD using c at 2008-10-01 6:00 GMT: + // assertEquals("Result is 59 USD"); + assertEquals("Result is 59 USD", 59.0, c.convert("CZK", "USD", 1003.0, (new GregorianCalendar(2008, 9, 1, 6, 0)).getTime())); + + // convert 16CZK using c at 2008-10-02 9:00 GMT: + // assertEquals("Result is 20 SKK"); + assertEquals("Result is 20 SKK", 20.0, c.convert("CZK", "SKK", 16.0, (new GregorianCalendar(2008, 9, 2, 9, 0)).getTime())); + + // convert 500SKK to CZK using c at 2008-10-02 9:00 GMT: + // assertEquals("Result is 400 CZK"); + assertEquals("Result is 400 CZK", 400.0, c.convert("SKK", "CZK", 500.0, (new GregorianCalendar(2008, 9, 2, 9, 0)).getTime())); + + // convert 500SKK to CZK using c at 2008-10-01 6:00 GMT: + // cannot convert as no rate is applicable to current date + try { + c.convert("SKK", "CZK", 500.0, (new GregorianCalendar(2008, 9, 1, 6, 0)).getTime()); + fail(); + } catch (IllegalArgumentException e) { + //ok + } + } + + /** Create convertor that understands two currencies, CZK and + * SKK. Make 100 SKK == 90 CZK. + * + * @return prepared convertor ready for converting SKK to CZK and CZK to SKK + */ + public static Convertor createSKKtoCZK2() { + return ConvertorFactory.newInstance().createConvertor("SKK", "CZK", 100, 90); + } + + public void testDateConvetorWithTwoDifferentRates() throws Exception { + Date d1 = (new GregorianCalendar(2008,9,1,0,0)).getTime(); // 2008-10-01 0:00 GMT + Date d2 = (new GregorianCalendar(2008,9,2,0,0)).getTime(); // 2008-10-02 0:00 GMT + Date d3 = (new GregorianCalendar(2008,9,6,0,0)).getTime(); // 2008-10-03 0:00 GMT + + Convertor c = Task2Test.merge( + limitTo(createSKKtoCZK2(), d1, d2), + limitTo(Task1Test.createSKKtoCZK(), d2, d3) + ); + + // convert 500SKK to CZK using c at 2008-10-02 9:00 GMT: + // assertEquals("Result is 400 CZK"); + assertEquals("Result is 400 CZK", 400.0, c.convert("SKK", "CZK", 500.0, (new GregorianCalendar(2008, 9, 2, 9, 0)).getTime())); + + // convert 500SKK to CZK using c at 2008-10-01 6:00 GMT: + // assertEquals("Result is 450 CZK"); + assertEquals("Result is 450 CZK", 450.0, c.convert("SKK", "CZK", 500.0, (new GregorianCalendar(2008, 9, 1, 6, 0)).getTime())); + } + +}