# HG changeset patch # User Jaroslav Tulach # Date 1223761126 -7200 # Node ID 58ec6da75f6fc24f57d2c361fa3d287f4d6a9bef # Parent a92eff6b426fff2ac04aa3db67ba33511f210117 Copying structure for task4 diff -r a92eff6b426f -r 58ec6da75f6f task4/solution02/build.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution02/build.xml Sat Oct 11 23:38:46 2008 +0200 @@ -0,0 +1,69 @@ + + + + + + Builds, tests, and runs the project. + + + diff -r a92eff6b426f -r 58ec6da75f6f task4/solution02/nbproject/build-impl.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution02/nbproject/build-impl.xml Sat Oct 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f task4/solution02/nbproject/genfiles.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution02/nbproject/genfiles.properties Sat Oct 11 23:38:46 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=848e6267 +nbproject/build-impl.xml.script.CRC32=6be86987 +nbproject/build-impl.xml.stylesheet.CRC32=e55b27f5 diff -r a92eff6b426f -r 58ec6da75f6f task4/solution02/nbproject/project.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution02/nbproject/project.properties Sat Oct 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f task4/solution02/nbproject/project.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution02/nbproject/project.xml Sat Oct 11 23:38:46 2008 +0200 @@ -0,0 +1,16 @@ + + + org.netbeans.modules.java.j2seproject + + + Currency Convertor Solution 02 + 1.6.5 + + + + + + + + + diff -r a92eff6b426f -r 58ec6da75f6f task4/solution02/src/org/apidesign/apifest08/currency/CompositeConvertor.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution02/src/org/apidesign/apifest08/currency/CompositeConvertor.java Sat Oct 11 23:38:46 2008 +0200 @@ -0,0 +1,75 @@ +package org.apidesign.apifest08.currency; + +import java.io.Serializable; +import java.util.Arrays; +import java.util.Currency; + +/** + * Convertor that is composed from other convertors. + * @author lukas + * + */ +class CompositeConvertor implements ExtendedConvertor, Serializable { + + private static final long serialVersionUID = -2702026568249130055L; + + private final ExtendedConvertor[] convertors; + + + public CompositeConvertor(ExtendedConvertor... convertors) { + this.convertors = convertors.clone(); + for (ExtendedConvertor convertor: this.convertors) + { + if (convertor==null) + { + throw new NullPointerException("One of the convertors to be merged is null"); + } + } + } + + /** + * Returns true if the composite contains convertor that supports given conversion. + */ + public boolean isConversionSupported(Currency from, Currency to) { + return findConvertorFor(from, to)!=null; + } + + + /** + * If the composite contains convertor that supports given conversion, delegates to its convert method. + * Throws {@link IllegalArgumentException} convertor supporting given conversion is not found. + */ + public Money convert(Money amount, Currency destinationCurrency) throws IllegalArgumentException { + ExtendedConvertor convertor = findConvertorFor(amount.getCurrency(), destinationCurrency); + if (convertor!=null) + { + return convertor.convert(amount, destinationCurrency); + } + throw new IllegalArgumentException("Conversion not supported. Can not convert to "+destinationCurrency+"."); + } + + /** + * Finds convertor for given currencies. If not found, returns null. + * @param from + * @param to + * @return + */ + ExtendedConvertor findConvertorFor(Currency from, Currency to) { + //does linear search, in the future can cache the results. + for (ExtendedConvertor convertor:convertors) + { + if (convertor.isConversionSupported(from, to)) + { + return convertor; + } + } + return null; + } + + + @Override + public String toString() { + return getClass().getName()+" converts "+Arrays.toString(convertors); + } + +} diff -r a92eff6b426f -r 58ec6da75f6f task4/solution02/src/org/apidesign/apifest08/currency/Convertor.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution02/src/org/apidesign/apifest08/currency/Convertor.java Sat Oct 11 23:38:46 2008 +0200 @@ -0,0 +1,18 @@ +package org.apidesign.apifest08.currency; + +import java.util.Currency; + + +/** + * Converts currencies. To create an instance call {@link ConvertorFactory#createConvertor(Money, Money)}. + */ +public interface Convertor { + /** + * Converts amount to its equivalent in the destination currency. + * @param amount + * @param destinationCurrency + * @return + * @throws IllegalArgumentException if currency of the amount is not supported or if it is not possible to convert it to the destination currency. + */ + public Money convert(Money amount, Currency destinationCurrency) throws IllegalArgumentException; +} diff -r a92eff6b426f -r 58ec6da75f6f task4/solution02/src/org/apidesign/apifest08/currency/ConvertorFactory.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution02/src/org/apidesign/apifest08/currency/ConvertorFactory.java Sat Oct 11 23:38:46 2008 +0200 @@ -0,0 +1,46 @@ +package org.apidesign.apifest08.currency; + + + +/** + * Creates {@link Convertor} implementations. + * @author lukas + * + */ +public class ConvertorFactory { + private ConvertorFactory() + { + //nothing + } + + /** + * Creates {@link Convertor} that converts from sourceEquivalent.currency to destinationEquivalent.currency. + * Exchange rate is set as equivalents. It means if you want to create USD to CZK convertor where USD1 = CZK17 + * call createConvertor(new MoneyImpl(1, USD), new MoneyImpl(17, CZK)). Convertor created by this method + * rounds the result to two decimal places. Convertor created by this method is thread safe. + * @param sourceEquivalent + * @param destinationEquivalent + * @return + */ + public static final ExtendedConvertor createConvertor(Money sourceEquivalent, Money destinationEquivalent) + { + return mergeConvertors( + new DefaultConvertor(sourceEquivalent, destinationEquivalent), + new DefaultConvertor(destinationEquivalent ,sourceEquivalent) + ); + } + + /** + * Merges convertors. The resulting convertor has ability to do all conversions that its underlying + * convertors could do. No consistency validation is done, inconsistent input will result in a convertor with + * inconsistent behavior. Convertor created by this method is thread safe. + * @param convertors + * @return + */ + public static final ExtendedConvertor mergeConvertors(ExtendedConvertor... convertors) + { + return new CompositeConvertor(convertors); + } + + +} diff -r a92eff6b426f -r 58ec6da75f6f task4/solution02/src/org/apidesign/apifest08/currency/DefaultConvertor.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution02/src/org/apidesign/apifest08/currency/DefaultConvertor.java Sat Oct 11 23:38:46 2008 +0200 @@ -0,0 +1,95 @@ +package org.apidesign.apifest08.currency; + +import java.io.Serializable; +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.Currency; + +/** + * Default {@link Convertor} implementation. Exchange rate is stored as equivalents. It means if we have USD to CZK convertor and USD1 = CZK17 + * we store 1 in sourceEquivalent and 17 in destinationEquivalent. This class is immutable. + * @author lukas + * + */ +class DefaultConvertor implements ExtendedConvertor, Serializable { + + private static final long serialVersionUID = 6660014633685135034L; + + /** + * Equivalent in source currency. + */ + private final BigDecimal sourceEquivalent; + + /** + * Equivalent in destination currency. + */ + private final BigDecimal destinationEquivalent; + + private final Currency sourceCurrency; + + private final Currency destinationCurrency; + + public DefaultConvertor(Money sourceEquivalent, Money destinationEquivalent) { + super(); + if (BigDecimal.ZERO.compareTo(sourceEquivalent.getAmount())==0) + { + throw new IllegalArgumentException("Source equivalent amount can not be 0."); + } + if (BigDecimal.ZERO.compareTo(destinationEquivalent.getAmount())==0) + { + throw new IllegalArgumentException("Destination equivalent amount can not be 0."); + } + this.sourceEquivalent = sourceEquivalent.getAmount(); + this.destinationEquivalent = destinationEquivalent.getAmount(); + this.sourceCurrency = sourceEquivalent.getCurrency(); + this.destinationCurrency = destinationEquivalent.getCurrency(); + } + + public Money convert(Money amount, Currency destinationCurrency) { + if (amount==null) + { + throw new NullPointerException("Money is null"); + } + if (destinationCurrency==null) + { + throw new NullPointerException("destionationCurrency is null"); + } + if (!amount.getCurrency().equals(getSourceCurrency())) + { + throw new IllegalArgumentException("Can not convert from "+amount.getCurrency()+". Converts between "+getSourceCurrency()+" and "+getDestinationCurrency()); + } + if (!getDestinationCurrency().equals(destinationCurrency)) + { + throw new IllegalArgumentException("Can not convert to "+destinationCurrency+". Converts between "+getSourceCurrency()+" and "+getDestinationCurrency()); + } + BigDecimal sourceAmount = amount.getAmount(); + BigDecimal destinationAmount = sourceAmount.multiply(destinationEquivalent).divide(sourceEquivalent, 2, RoundingMode.HALF_UP); + return new MoneyImpl(destinationAmount, getDestinationCurrency()); + } + + public boolean isConversionSupported(Currency from, Currency to) { + return sourceCurrency.equals(from) && destinationCurrency.equals(to); + } + + public BigDecimal getSourceEquivalent() { + return sourceEquivalent; + } + + public BigDecimal getDestinationEquivalent() { + return destinationEquivalent; + } + + public Currency getSourceCurrency() { + return sourceCurrency; + } + + public Currency getDestinationCurrency() { + return destinationCurrency; + } + + @Override + public String toString() { + return getClass().getName()+" converts "+getSourceCurrency()+" to "+getDestinationCurrency()+" " + +getSourceCurrency()+getSourceEquivalent()+"="+getDestinationCurrency()+getDestinationEquivalent(); + } +} diff -r a92eff6b426f -r 58ec6da75f6f task4/solution02/src/org/apidesign/apifest08/currency/ExtendedConvertor.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution02/src/org/apidesign/apifest08/currency/ExtendedConvertor.java Sat Oct 11 23:38:46 2008 +0200 @@ -0,0 +1,18 @@ +package org.apidesign.apifest08.currency; + +import java.util.Currency; + +/** + * Extended convertor interface. + * @author lukas + * + */ +public interface ExtendedConvertor extends Convertor { + /** + * Returns true if given conversion is supported. + * @param from + * @param to + * @return + */ + public boolean isConversionSupported(Currency from, Currency to); +} diff -r a92eff6b426f -r 58ec6da75f6f task4/solution02/src/org/apidesign/apifest08/currency/Money.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution02/src/org/apidesign/apifest08/currency/Money.java Sat Oct 11 23:38:46 2008 +0200 @@ -0,0 +1,29 @@ +package org.apidesign.apifest08.currency; + +import java.math.BigDecimal; +import java.util.Currency; + +/** + * Money representation. Default implementation {@link MoneyImpl} is provided. This interface can + * be implemented by a DTO used in client application. + * @author lukas + * + */ +/* + * Whether we need such interface depends on the context. I can imagine than in a desktop application this interface + * would be useless, Money could be a class. In J2EE environment it can be useful. + */ +public interface Money { + + /** + * Returns amount. + * @return + */ + public BigDecimal getAmount(); + + /** + * Returns currency. + */ + public Currency getCurrency(); + +} \ No newline at end of file diff -r a92eff6b426f -r 58ec6da75f6f task4/solution02/src/org/apidesign/apifest08/currency/MoneyImpl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution02/src/org/apidesign/apifest08/currency/MoneyImpl.java Sat Oct 11 23:38:46 2008 +0200 @@ -0,0 +1,121 @@ +package org.apidesign.apifest08.currency; + +import java.io.Serializable; +import java.math.BigDecimal; +import java.util.Currency; + +/** + * Default implementation of {@link Money} interface. This class is immutable. + * @author lukas + * + */ +public final class MoneyImpl implements Serializable, Money{ + private static final long serialVersionUID = -6091808475616516136L; + + private final BigDecimal amount; + + private final Currency currency; + + public MoneyImpl(BigDecimal amount, Currency currency) { + if (amount==null) throw new NullPointerException("Amount is null"); + if (currency==null) throw new NullPointerException("Currency is null"+currency); + this.amount = amount; + this.currency = currency; + } + + + + public MoneyImpl(long amount, Currency currency) { + this(BigDecimal.valueOf(amount), currency); + } + + public MoneyImpl(double amount, Currency currency) { + this(BigDecimal.valueOf(amount), currency); + } + + /** + * Factory method. + * @param amount + * @param currency + * @return + */ + public static final Money money(BigDecimal amount, Currency currency) + { + return new MoneyImpl(amount, currency); + } + /** + * Factory method. + * @param amount + * @param currency + * @return + */ + public static final Money money(long amount, Currency currency) + { + return new MoneyImpl(amount, currency); + } + /** + * Factory method. + * @param amount + * @param currency + * @return + */ + public static final Money money(double amount, Currency currency) + { + return new MoneyImpl(amount, currency); + } + + /** + * Returns amount. + * @return + */ + public BigDecimal getAmount() { + return amount; + } + + /** + * Returns currency. + */ + public Currency getCurrency() { + return currency; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((amount == null) ? 0 : amount.hashCode()); + result = prime * result + + ((currency == null) ? 0 : currency.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (!(obj instanceof MoneyImpl)) + return false; + MoneyImpl other = (MoneyImpl) obj; + if (amount == null) { + if (other.amount != null) + return false; + } else if (amount.compareTo(other.amount)!=0) + return false; + if (currency == null) { + if (other.currency != null) + return false; + } else if (!currency.equals(other.currency)) + return false; + return true; + } + + @Override + public String toString() { + return getClass().getName()+"["+currency+amount+"]"; + } + + + +} diff -r a92eff6b426f -r 58ec6da75f6f task4/solution02/test/org/apidesign/apifest08/currency/CompositeConvertorTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution02/test/org/apidesign/apifest08/currency/CompositeConvertorTest.java Sat Oct 11 23:38:46 2008 +0200 @@ -0,0 +1,56 @@ +package org.apidesign.apifest08.currency; + +import static junit.framework.Assert.assertEquals; +import static junit.framework.Assert.assertFalse; +import static junit.framework.Assert.assertTrue; +import static junit.framework.Assert.fail; +import static org.apidesign.apifest08.test.Task1Test.CZK; +import static org.apidesign.apifest08.test.Task1Test.SKK; +import static org.apidesign.apifest08.test.Task1Test.USD; + +import org.junit.Test; + +public class CompositeConvertorTest { + private static final ExtendedConvertor USD_CZK_CONVERTOR = ConvertorFactory.createConvertor(new MoneyImpl(1,USD), new MoneyImpl(17,CZK)); + private static final ExtendedConvertor SKK_CZK_CONVERTOR = ConvertorFactory.createConvertor(new MoneyImpl(100,SKK), new MoneyImpl(80,CZK)); + + @Test + public void testCompose() + { + ExtendedConvertor convertor = new CompositeConvertor(USD_CZK_CONVERTOR, SKK_CZK_CONVERTOR); + assertTrue(convertor.isConversionSupported(CZK, SKK)); + assertTrue(convertor.isConversionSupported(CZK, USD)); + assertFalse(convertor.isConversionSupported(SKK, USD)); + assertEquals(new MoneyImpl(10,SKK), convertor.convert(new MoneyImpl(8,CZK), SKK)); + assertEquals(new MoneyImpl(2,USD), convertor.convert(new MoneyImpl(34,CZK), USD)); + try + { + convertor.convert(new MoneyImpl(34,SKK), USD); + fail("Exception expected"); + } + catch(IllegalArgumentException e) + { + assertTrue("Ok", true); + } + } + @Test + public void testEmpty() + { + ExtendedConvertor convertor = new CompositeConvertor(); + assertFalse(convertor.isConversionSupported(SKK, USD)); + try + { + convertor.convert(new MoneyImpl(34,SKK), USD); + fail("Exception expected"); + } + catch(IllegalArgumentException e) + { + assertTrue("Ok", true); + } + } + @Test(expected=NullPointerException.class) + public void testCreateNull() + { + new CompositeConvertor(USD_CZK_CONVERTOR, null); + } +} diff -r a92eff6b426f -r 58ec6da75f6f task4/solution02/test/org/apidesign/apifest08/test/ConvertorFactoryTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution02/test/org/apidesign/apifest08/test/ConvertorFactoryTest.java Sat Oct 11 23:38:46 2008 +0200 @@ -0,0 +1,52 @@ +package org.apidesign.apifest08.test; + +import static junit.framework.Assert.assertNotNull; +import static org.apidesign.apifest08.test.Task1Test.CZK; +import static org.apidesign.apifest08.test.Task1Test.USD; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import org.apidesign.apifest08.currency.Convertor; +import org.apidesign.apifest08.currency.ConvertorFactory; +import org.apidesign.apifest08.currency.MoneyImpl; +import org.junit.Test; + + +public class ConvertorFactoryTest { + @Test(expected=NullPointerException.class) + public void testNullSource() + { + ConvertorFactory.createConvertor(null, new MoneyImpl(1,USD)); + } + @Test(expected=NullPointerException.class) + public void testNullDestination() + { + ConvertorFactory.createConvertor(new MoneyImpl(17,CZK), null); + } + @Test + public void testOk() + { + assertNotNull(ConvertorFactory.createConvertor(new MoneyImpl(17,CZK), new MoneyImpl(1,USD))); + } + @Test + public void testOkDecimalRate() + { + Convertor c = ConvertorFactory.createConvertor(new MoneyImpl(1,CZK), new MoneyImpl(1d/17d,USD)); + assertNotNull(c); + assertEquals(new MoneyImpl(17,CZK),c.convert(new MoneyImpl(1,USD), CZK)); + } + @Test + public void testZeroEquivalentRate() + { + try + { + ConvertorFactory.createConvertor(new MoneyImpl(1,CZK), new MoneyImpl(0,USD)); + fail("Exception expected"); + } + catch(IllegalArgumentException e) + { + assertTrue("OK",true); + } + } +} diff -r a92eff6b426f -r 58ec6da75f6f task4/solution02/test/org/apidesign/apifest08/test/ConvertorTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution02/test/org/apidesign/apifest08/test/ConvertorTest.java Sat Oct 11 23:38:46 2008 +0200 @@ -0,0 +1,44 @@ +package org.apidesign.apifest08.test; + +import static junit.framework.Assert.assertEquals; +import static junit.framework.Assert.assertFalse; +import static junit.framework.Assert.assertTrue; +import static org.apidesign.apifest08.test.Task1Test.CZK; +import static org.apidesign.apifest08.test.Task1Test.SKK; +import static org.apidesign.apifest08.test.Task1Test.USD; + +import java.math.BigDecimal; + +import org.apidesign.apifest08.currency.ConvertorFactory; +import org.apidesign.apifest08.currency.ExtendedConvertor; +import org.apidesign.apifest08.currency.Money; +import org.apidesign.apifest08.currency.MoneyImpl; +import org.junit.Test; + + +public class ConvertorTest { + + private static final ExtendedConvertor CZK_TO_USD_CONVERTOR = ConvertorFactory.createConvertor(new MoneyImpl(17,CZK), new MoneyImpl(1,USD)); + @Test + public void testConvertSmall() + { + Money converted = CZK_TO_USD_CONVERTOR.convert(new MoneyImpl(0.17,CZK),USD); + assertEquals(new MoneyImpl(new BigDecimal("0.01"),USD),converted); + assertEquals(USD,converted.getCurrency()); + } + @Test + public void testConvertSmallReverse() + { + Money converted = CZK_TO_USD_CONVERTOR.convert(new MoneyImpl(0.01,USD),CZK); + assertEquals(new MoneyImpl(new BigDecimal("0.17"),CZK),converted); + } + @Test + public void testSupports() + { + assertTrue(CZK_TO_USD_CONVERTOR.isConversionSupported(USD,CZK)); + assertTrue(CZK_TO_USD_CONVERTOR.isConversionSupported(CZK,USD)); + assertFalse(CZK_TO_USD_CONVERTOR.isConversionSupported(CZK,CZK)); + assertFalse(CZK_TO_USD_CONVERTOR.isConversionSupported(CZK,SKK)); + + } +} diff -r a92eff6b426f -r 58ec6da75f6f task4/solution02/test/org/apidesign/apifest08/test/MoneyTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution02/test/org/apidesign/apifest08/test/MoneyTest.java Sat Oct 11 23:38:46 2008 +0200 @@ -0,0 +1,24 @@ +package org.apidesign.apifest08.test; + +import static junit.framework.Assert.assertEquals; +import static org.apidesign.apifest08.test.Task1Test.CZK; + +import java.math.BigDecimal; + +import org.apidesign.apifest08.currency.MoneyImpl; +import org.junit.Test; + +public class MoneyTest { + @Test(expected=NullPointerException.class) + public void testNullAmount(){ + new MoneyImpl(null,CZK); + } + @Test(expected=NullPointerException.class) + public void testNullCurrency(){ + new MoneyImpl(1,null); + } + @Test + public void testOk(){ + assertEquals(0,new MoneyImpl(123,CZK).getAmount().compareTo(new BigDecimal("123"))); + } +} diff -r a92eff6b426f -r 58ec6da75f6f task4/solution02/test/org/apidesign/apifest08/test/OnlineConvertor.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution02/test/org/apidesign/apifest08/test/OnlineConvertor.java Sat Oct 11 23:38:46 2008 +0200 @@ -0,0 +1,54 @@ +package org.apidesign.apifest08.test; + +import java.math.BigDecimal; +import java.util.Currency; + +import org.apidesign.apifest08.currency.ConvertorFactory; +import org.apidesign.apifest08.currency.ExtendedConvertor; +import org.apidesign.apifest08.currency.Money; +import org.apidesign.apifest08.currency.MoneyImpl; + +/** + * Third party implementation of the convertor. IT IS NOT THREAD SAFE. + * @author lukas + * + */ +class OnlineConvertor implements ExtendedConvertor { + + private static final BigDecimal LOWER_LIMIT = BigDecimal.valueOf(15); + private static final BigDecimal HIGHER_LIMIT = BigDecimal.valueOf(16); + + private static final Currency USD = Currency.getInstance("USD"); + private static final Currency CZK = Currency.getInstance("CZK"); + private static final MoneyImpl ONE_USD = new MoneyImpl(1,USD); + + private ExtendedConvertor wrappedConvertor = ConvertorFactory.createConvertor(ONE_USD, new MoneyImpl(16, CZK)); + + private BigDecimal increment = new BigDecimal("-0.01"); + + public boolean isConversionSupported(Currency from, Currency to) { + return wrappedConvertor.isConversionSupported(from, to); + } + + public Money convert(Money amount, Currency destinationCurrency) + throws IllegalArgumentException { + Money result = wrappedConvertor.convert(amount, destinationCurrency); + updateConvertor(); + return result; + } + + /** + * Prepares convertor for the next conversion. + */ + private void updateConvertor() { + BigDecimal currentRate = wrappedConvertor.convert(ONE_USD, CZK).getAmount(); + BigDecimal newRate = currentRate.add(increment); + + if (LOWER_LIMIT.compareTo(newRate)==0 || HIGHER_LIMIT.compareTo(newRate)==0) + { + increment = increment.negate(); + } + wrappedConvertor = ConvertorFactory.createConvertor(ONE_USD, new MoneyImpl(newRate, CZK)); + } + +} diff -r a92eff6b426f -r 58ec6da75f6f task4/solution02/test/org/apidesign/apifest08/test/OnlineConvertorTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution02/test/org/apidesign/apifest08/test/OnlineConvertorTest.java Sat Oct 11 23:38:46 2008 +0200 @@ -0,0 +1,44 @@ +package org.apidesign.apifest08.test; +import static junit.framework.Assert.assertEquals; +import static org.apidesign.apifest08.currency.MoneyImpl.money; +import static org.apidesign.apifest08.test.Task1Test.CZK; +import static org.apidesign.apifest08.test.Task1Test.USD; + +import java.math.BigDecimal; + +import org.apidesign.apifest08.currency.Convertor; +import org.apidesign.apifest08.currency.Money; +import org.junit.Test; + +public class OnlineConvertorTest { + private static final Money ONE_USD = money(1, USD); + + @Test + public void testBounce() + { + Convertor c = Task3Test.createOnlineCZKUSDConvertor(); + + doBounceTest(c); + doBounceTest(c); + + } + + private void doBounceTest(Convertor c) { + BigDecimal expectedRate = new BigDecimal(16); + BigDecimal increment = new BigDecimal("0.01"); + + for (int i=0;i<100;i++) + { + assertEquals(money(expectedRate,CZK), c.convert(ONE_USD, CZK)); + expectedRate = expectedRate.subtract(increment); + } + + assertEquals(money(15,CZK), c.convert(ONE_USD, CZK)); + + for (int i=0;i<99;i++) + { + expectedRate = expectedRate.add(increment); + assertEquals(money(expectedRate,CZK), c.convert(ONE_USD, CZK)); + } + } +} diff -r a92eff6b426f -r 58ec6da75f6f task4/solution02/test/org/apidesign/apifest08/test/Task1Test.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution02/test/org/apidesign/apifest08/test/Task1Test.java Sat Oct 11 23:38:46 2008 +0200 @@ -0,0 +1,160 @@ +package org.apidesign.apifest08.test; + +import java.util.Currency; + +import junit.framework.TestCase; + +import org.apidesign.apifest08.currency.Convertor; +import org.apidesign.apifest08.currency.ConvertorFactory; +import org.apidesign.apifest08.currency.MoneyImpl; + +/** 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 static final Currency USD = Currency.getInstance("USD"); + public static final Currency CZK = Currency.getInstance("CZK"); + public static final Currency SKK = Currency.getInstance("SKK"); + + 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.createConvertor(new MoneyImpl(17,CZK), new MoneyImpl(1,USD)); + } + + /** 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.createConvertor(new MoneyImpl(100,SKK), new MoneyImpl(80,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(); + // convert $5 to CZK using c: + assertEquals("Result is 85 CZK",new MoneyImpl(85,CZK), c.convert(new MoneyImpl(5,USD),CZK)); + + // convert $8 to CZK + assertEquals("Result is 136 CZK",new MoneyImpl(136,CZK), c.convert(new MoneyImpl(8,USD),CZK)); + + // convert 1003CZK to USD + assertEquals("Result is 59 USD", new MoneyImpl(59,USD), c.convert(new MoneyImpl(1003,CZK),USD)); + + } + + /** 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", new MoneyImpl(20,SKK), c.convert(new MoneyImpl(16,CZK),SKK)); + + // convert 500SKK to CZK + assertEquals("Result is 400 CZK", new MoneyImpl(400,CZK), c.convert(new MoneyImpl(500,SKK),CZK)); + } + + /** 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 MoneyImpl(5, USD), SKK); + fail("Exception expected"); + } + catch(IllegalArgumentException e) + { + assertTrue("Ok",true); + } + // convert 500 SKK to CZK, the API shall say this is not possible + try + { + c.convert(new MoneyImpl(500, SKK), CZK); + fail("Exception expected"); + } + catch(IllegalArgumentException e) + { + assertTrue("Ok",true); + } + } + + /** 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(new MoneyImpl(5, USD), SKK); + fail("Exception expected"); + } + catch(IllegalArgumentException e) + { + assertTrue("Ok",true); + } + // convert 500 CZK to USD, the API shall say this is not possible + try + { + c.convert(new MoneyImpl(500, CZK), USD); + fail("Exception expected"); + } + catch(IllegalArgumentException e) + { + assertTrue("Ok",true); + } + } +} diff -r a92eff6b426f -r 58ec6da75f6f task4/solution02/test/org/apidesign/apifest08/test/Task2Test.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution02/test/org/apidesign/apifest08/test/Task2Test.java Sat Oct 11 23:38:46 2008 +0200 @@ -0,0 +1,119 @@ +package org.apidesign.apifest08.test; + +import static org.apidesign.apifest08.currency.ConvertorFactory.createConvertor; +import static org.apidesign.apifest08.currency.ConvertorFactory.mergeConvertors; +import static org.apidesign.apifest08.currency.MoneyImpl.money; +import static org.apidesign.apifest08.test.Task1Test.CZK; +import static org.apidesign.apifest08.test.Task1Test.SKK; +import static org.apidesign.apifest08.test.Task1Test.USD; +import junit.framework.TestCase; + +import org.apidesign.apifest08.currency.Convertor; +import org.apidesign.apifest08.currency.ExtendedConvertor; + +/** 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 + return mergeConvertors( + createConvertor(money(1, USD), money(15, CZK)), + createConvertor(money(1, USD), money(20, SKK)), + createConvertor(money(75, CZK), money(100, SKK)) + ); + } + + /** 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", money(75, CZK),c.convert(money(5,USD), CZK)); + + // convert $5 to SKK using c: + assertEquals("Result is 100 SKK", money(100, SKK),c.convert(money(5,USD), SKK)); + + // convert 200SKK to CZK using c: + assertEquals("Result is 150 CZK", money(150, CZK),c.convert(money(200,SKK), CZK)); + + // convert 200SKK to USK using c: + assertEquals("Result is 10 USD", money(10, USD),c.convert(money(200,SKK), 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 mergeConvertors((ExtendedConvertor)one, (ExtendedConvertor)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", money(85, CZK),c.convert(money(5,USD), CZK)); + + // convert $8 to CZK using c: + assertEquals("Result is 136 CZK", money(136, CZK),c.convert(money(8,USD), CZK)); + + // convert 1003CZK to USD using c: + assertEquals("Result is 59 USD", money(59, USD),c.convert(money(1003,CZK), USD)); + + // convert 16CZK using c: + assertEquals("Result is 20 SKK", money(20, SKK),c.convert(money(16,CZK), SKK)); + + // convert 500SKK to CZK using c: + assertEquals("Result is 400 CZK", money(400, CZK),c.convert(money(500,SKK), CZK)); + + } +} diff -r a92eff6b426f -r 58ec6da75f6f task4/solution02/test/org/apidesign/apifest08/test/Task3Test.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution02/test/org/apidesign/apifest08/test/Task3Test.java Sat Oct 11 23:38:46 2008 +0200 @@ -0,0 +1,100 @@ +package org.apidesign.apifest08.test; + +import static org.apidesign.apifest08.currency.MoneyImpl.money; +import static org.apidesign.apifest08.test.Task1Test.CZK; +import static org.apidesign.apifest08.test.Task1Test.SKK; +import static org.apidesign.apifest08.test.Task1Test.USD; +import junit.framework.TestCase; + +import org.apidesign.apifest08.currency.Convertor; + +/** 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 new OnlineConvertor(); + } + + public void testFewQueriesForOnlineConvertor() { + Convertor c = createOnlineCZKUSDConvertor(); + doFewQueriesForOnlineConvertor(c); + } + + static void doFewQueriesForOnlineConvertor(Convertor c) { + // convert $5 to CZK using c: + assertEquals("Result is 80 CZK", money(80,CZK), c.convert(money(5,USD), CZK)); + + // convert $8 to CZK using c: + assertEquals("Result is 127.92 CZK", money(127.92,CZK), c.convert(money(8,USD), CZK)); + + // convert $1 to CZK using c: + assertEquals("Result is 15.98 CZK", money(15.98,CZK), c.convert(money(1,USD), CZK)); + + // convert 15.97CZK to USD using c: + assertEquals("Result is 1 USD", money(1,USD), c.convert(money(15.97,CZK), USD)); + //assertEquals("Result is 1$"); + + } + + /** 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", money(20,SKK), c.convert(money(16,CZK), SKK)); + + // convert 500SKK to CZK using c: + assertEquals("Result is 400 CZK", money(400,CZK), c.convert(money(500,SKK), CZK)); + + doFewQueriesForOnlineConvertor(c); + } +} diff -r a92eff6b426f -r 58ec6da75f6f task4/solution04/build.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution04/build.xml Sat Oct 11 23:38:46 2008 +0200 @@ -0,0 +1,69 @@ + + + + + + Builds, tests, and runs the project. + + + diff -r a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f task4/solution04/nbproject/genfiles.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution04/nbproject/genfiles.properties Sat Oct 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f task4/solution04/nbproject/project.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution04/nbproject/project.properties Sat Oct 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f task4/solution04/nbproject/project.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution04/nbproject/project.xml Sat Oct 11 23:38:46 2008 +0200 @@ -0,0 +1,16 @@ + + + org.netbeans.modules.java.j2seproject + + + Currency Convertor Solution 04 + 1.6.5 + + + + + + + + + diff -r a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 2008 +0200 @@ -0,0 +1,350 @@ +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.1 + */ +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 + 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 a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 2008 +0200 @@ -0,0 +1,304 @@ +package org.apidesign.apifest08.currency; + + +import java.math.BigDecimal; +import java.math.MathContext; +import java.math.RoundingMode; +import java.util.Collections; +import java.util.Currency; +import java.util.HashSet; +import java.util.Set; + + +/** + * Convert between two currencies. + * + * @author D'Arcy Smith + * @version 1.0 + */ +final class ConvertorImpl + implements Convertor +{ + /** + * The currency to convert from. + */ + private final Currency currencyA; + + /** + * The currency to convert to. + */ + private final Currency currencyB; + + /** + * The echange rate between a and b. + */ + private final BigDecimal currencyARate; + + /** + * The echange rate between b and a. + */ + private final BigDecimal currencyBRate; + + /** + * 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 Currency a, + final BigDecimal aRate, + final Currency b, + final BigDecimal bRate) + { + 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"); + } + + if(aRate.compareTo(BigDecimal.ZERO) <= 0) + { + throw new IllegalArgumentException("aRate must be > 0, was: " + aRate); + } + + if(bRate.compareTo(BigDecimal.ZERO) <= 0) + { + throw new IllegalArgumentException("bRate must be > 0, was: " + bRate); + } + + currencyA = a; + currencyB = b; + currencyARate = aRate; + currencyBRate = bRate; + } + + /** + * 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 + { + 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 + { + final BigDecimal rateX; + final BigDecimal rateY; + final BigDecimal temp; + + if(from.equals(currencyA)) + { + rateX = currencyARate; + rateY = currencyBRate; + } + else + { + rateX = currencyBRate; + rateY = currencyARate; + } + + temp = BigDecimal.ONE.divide(rateX, MathContext.DECIMAL64); + rate = temp.multiply(rateY); + } + + return (rate.setScale(20, RoundingMode.HALF_EVEN)); + } + + /** + * 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; + + // it would be nice if NetBeans could chck to see if the variable is final and guaranteed not to be null... but that + // would likely be tricky... but in a NetBeans engineer reads that see if you can do it :-) + 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.currencyARate != other.currencyARate && (this.currencyARate == null || !this.currencyARate.equals(other.currencyARate))) + { + return false; + } + + if (this.currencyBRate != other.currencyBRate && (this.currencyBRate == null || !this.currencyBRate.equals(other.currencyBRate))) + { + return false; + } + + return true; + } + + /** + * Get the hashCode of the Convertor. + * + * @return the hashCode of the convertor. + */ + @Override + public int hashCode() + { + int hash = 7; + hash = 37 * hash + (this.currencyA != null ? this.currencyA.hashCode() : 0); + hash = 37 * hash + (this.currencyB != null ? this.currencyB.hashCode() : 0); + hash = 37 * hash + (this.currencyARate != null ? this.currencyARate.hashCode() : 0); + hash = 37 * hash + (this.currencyBRate != null ? this.currencyBRate.hashCode() : 0); + return hash; + } + + /** + * Get the currencyCode of both currencies. + * + * @return the currency codes of both currencies. + */ + @Override + public String toString() + { + return (currencyA.getCurrencyCode() + " to " + currencyB.getCurrencyCode()); + } +} diff -r a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 2008 +0200 @@ -0,0 +1,177 @@ +package org.apidesign.apifest08.currency; + +import java.math.BigDecimal; +import java.util.Currency; + + +/** + * Create convertors using a flyweight to reduce the number of repetative creations of the same convertor. + * + * @author D'Arcy Smith + * @version 1.0 + */ +public final class ConvertorFactory +{ + /* + * flyweight so that only one vestion of each converter is created at a time. + private final static Map> convertors; + + static + { + convertors = new WeakHashMap>(); + } + */ + + /** + * 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) + { + // final String key; + Convertor convertor; + + 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"); + } + + /* + key = a.getCurrencyCode() + aRate + b.getCurrencyCode() + bRate; + + // make sure that we don't try to overwrite one + synchronized(convertors) + { + if(!(convertors.containsKey(key))) + { + convertor = new ConvertorImpl(a, aRate, b, bRate); + convertors.put(key, new WeakReference(convertor)); + } + + convertor = convertors.get(key).get(); + } + */ + + convertor = new ConvertorImpl(a, aRate, b, bRate); + + return (convertor); + } + + /** + * + * @param cs + * @return + */ + public static Convertor mergeConvertors(final Convertor ... cs) + { + Convertor convertor; + + /* + final String key; + + // ISSUE: only takes into account the names... not the rates... + key = getKey(cs); + + // make sure that we don't try to overwrite one + synchronized(convertors) + { + if(!(convertors.containsKey(key))) + { + convertor = new CompositeConvertorImpl(cs); + convertors.put(key, new WeakReference(convertor)); + } + + convertor = convertors.get(key).get(); + } + */ + + convertor = new CompositeConvertorImpl(cs); + + return (convertor); + } + + /* + private static String getKey(final Convertor ... cs) + { + final Set currencies; + final StringBuilder builder; + + currencies = new HashSet(); + + for(final Convertor convertor : cs) + { + final Set c; + + c = convertor.getCurrencies(); + currencies.addAll(c); + } + + builder = new StringBuilder(); + + for(final Currency currency : currencies) + { + builder.append(currency.getCurrencyCode()); + } + + return (builder.toString()); + } + */ +} diff -r a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 2008 +0200 @@ -0,0 +1,125 @@ +package org.apidesign.apifest08.currency; + + +import java.math.BigDecimal; +import java.util.Currency; + + +/** + * The exchange rate between two currencies. + * + * @author D'Arcy Smith + * @version 1.0 + */ +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; + } +} diff -r a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 { + + 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 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 a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f task4/solution06/build.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution06/build.xml Sat Oct 11 23:38:46 2008 +0200 @@ -0,0 +1,69 @@ + + + + + + Builds, tests, and runs the project. + + + diff -r a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f task4/solution06/nbproject/genfiles.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution06/nbproject/genfiles.properties Sat Oct 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f task4/solution06/nbproject/project.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution06/nbproject/project.properties Sat Oct 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f task4/solution06/nbproject/project.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution06/nbproject/project.xml Sat Oct 11 23:38:46 2008 +0200 @@ -0,0 +1,16 @@ + + + org.netbeans.modules.java.j2seproject + + + Currency Convertor Solution 06 + 1.6.5 + + + + + + + + + diff -r a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 2008 +0200 @@ -0,0 +1,176 @@ +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.Currency; +import java.util.List; + +/** + * 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)); + } + + /** + * 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)); + } + + /** + * 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) { + convertorDelegates.addAll(convertor.convertorDelegates); + } + } + } + + /** + * Converts an amount value between the two currencies of this converter. + * + * @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 { + notNull(amount, "amount"); + notNull(fromCurrency, "fromCurrency"); + notNull(toCurrency, "toCurrency"); + ConvertorDelegate appropriateDelegate = null; + + //try find an appropriate delegate for conversion + for(ConvertorDelegate delegate : convertorDelegates) { + if(delegate.isConversionSupported(fromCurrency, toCurrency)) { + appropriateDelegate = delegate; + break; + } + } + + if(appropriateDelegate == null) { + throw new UnsupportedConversionException(fromCurrency, toCurrency); + } + + return appropriateDelegate.convert(amount, fromCurrency, toCurrency); + } + + /** + * Internal delegate implements a logic for conversion between two currencies + * and vice versa. + * @see #isConversionSupported(Currency, Currency) + */ + private static class ConvertorDelegate { + private final Currency first; + private final Currency second; + private final RateProvider rateProvider; + public static final BigDecimal one = new BigDecimal(1); + + + private ConvertorDelegate(RateProvider rateProvider, Currency currencyFirst, Currency currencySecond) { + this.rateProvider = rateProvider; + this.first = currencyFirst; + this.second = currencySecond; + } + + 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)); + } + } + + /** + * 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 a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 2008 +0200 @@ -0,0 +1,27 @@ +package org.apidesign.apifest08.currency; + +import java.util.Currency; + +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 Currency getFrom() { + return from; + } + + public Currency getTo() { + return to; + } + + +} diff -r a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f task4/solution07/build.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution07/build.xml Sat Oct 11 23:38:46 2008 +0200 @@ -0,0 +1,69 @@ + + + + + + Builds, tests, and runs the project. + + + diff -r a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f task4/solution07/nbproject/genfiles.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution07/nbproject/genfiles.properties Sat Oct 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f task4/solution07/nbproject/project.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution07/nbproject/project.properties Sat Oct 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f task4/solution07/nbproject/project.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution07/nbproject/project.xml Sat Oct 11 23:38:46 2008 +0200 @@ -0,0 +1,16 @@ + + + org.netbeans.modules.java.j2seproject + + + Currency Convertor Solution 07 + 1.6.5 + + + + + + + + + diff -r a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f task4/solution11/build.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution11/build.xml Sat Oct 11 23:38:46 2008 +0200 @@ -0,0 +1,69 @@ + + + + + + Builds, tests, and runs the project. + + + diff -r a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f task4/solution11/nbproject/genfiles.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution11/nbproject/genfiles.properties Sat Oct 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f task4/solution11/nbproject/project.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution11/nbproject/project.properties Sat Oct 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f task4/solution11/nbproject/project.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution11/nbproject/project.xml Sat Oct 11 23:38:46 2008 +0200 @@ -0,0 +1,16 @@ + + + org.netbeans.modules.java.j2seproject + + + Currency Convertor Solution 11 + 1.6.5 + + + + + + + + + diff -r a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 2008 +0200 @@ -0,0 +1,311 @@ +package org.apidesign.apifest08.currency; + +import java.util.ArrayList; +import java.util.Collection; +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. + * + * @author ked + */ +public final class Convertor { + + Computer computer; + // each static exchange rate could be a special case of an exchange rate data source + List> exchangeRates = new ArrayList>(); + List> exchangeRateDataSources = new ArrayList>(); + + Convertor(Computer computer) { + this.computer = computer; + } + + void addExchangeRates(Collection> exchangeRates) { + for (ExchangeRateValue exchangeRate : exchangeRates) { + if (isExchangeRate( + exchangeRate.getCurrencyA().getIdentifier(), + exchangeRate.getCurrencyB().getIdentifier())) { + throw new IllegalArgumentException("Duplicate exchange rate!"); + } + this.exchangeRates.add(exchangeRate); + } + } + + void addExchangeRateDataSources(Collection> exchangeRateDataSources) { + for (ExchangeRateDataSource exchangeRateDataSource : exchangeRateDataSources) { + if (isExchangeRate( + exchangeRateDataSource.getCurrencyAIdentifier(), + exchangeRateDataSource.getCurrencyBIdentifier())) { + throw new IllegalArgumentException("Duplicate exchange rate!"); + } + this.exchangeRateDataSources.add(exchangeRateDataSource); + } + } + + ExchangeRateValue findExchangeRate( + IdentifierType currencyA, + IdentifierType currencyB) { + for (ExchangeRateValue exchangeRate : exchangeRates) { + if ((exchangeRate.getCurrencyA().getIdentifier().equals(currencyA) && exchangeRate.getCurrencyB().getIdentifier().equals(currencyB)) || + (exchangeRate.getCurrencyA().getIdentifier().equals(currencyB) && exchangeRate.getCurrencyB().getIdentifier().equals(currencyA))) { + return exchangeRate; + } + } + for (ExchangeRateDataSource exchangeRateDataSource : exchangeRateDataSources) { + if ((exchangeRateDataSource.getCurrencyAIdentifier().equals(currencyA) && exchangeRateDataSource.getCurrencyBIdentifier().equals(currencyB)) || + (exchangeRateDataSource.getCurrencyAIdentifier().equals(currencyB) && exchangeRateDataSource.getCurrencyBIdentifier().equals(currencyA))) { + return exchangeRateDataSource.getExchangeRate(); + } + } + return null; + } + + boolean isExchangeRate( + IdentifierType currencyA, + IdentifierType currencyB) { + for (ExchangeRateValue exchangeRate : exchangeRates) { + if ((exchangeRate.getCurrencyA().getIdentifier().equals(currencyA) && exchangeRate.getCurrencyB().getIdentifier().equals(currencyB)) || + (exchangeRate.getCurrencyA().getIdentifier().equals(currencyB) && exchangeRate.getCurrencyB().getIdentifier().equals(currencyA))) { + return true; + } + } + for (ExchangeRateDataSource exchangeRateDataSource : exchangeRateDataSources) { + if ((exchangeRateDataSource.getCurrencyAIdentifier().equals(currencyA) && exchangeRateDataSource.getCurrencyBIdentifier().equals(currencyB)) || + (exchangeRateDataSource.getCurrencyAIdentifier().equals(currencyB) && exchangeRateDataSource.getCurrencyBIdentifier().equals(currencyA))) { + 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) { + ExchangeRateValue exchangeRate = + findExchangeRate(currencyValue.getIdentifier(), targetCurrency); + 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); + } + + // --- + // MERGING + // --- + static Convertor mergeConvertors( + Computer computer, + Collection> convertors) { + Set> exchangeRatesSet = new HashSet>(); + Set> exchangeRateDataSourcesSet = new HashSet>(); + for (Convertor convertor : convertors) { + exchangeRatesSet.addAll(convertor.exchangeRates); + } + for (Convertor convertor : convertors) { + exchangeRateDataSourcesSet.addAll(convertor.exchangeRateDataSources); + } + + Convertor c = new Convertor(computer); + c.addExchangeRates(exchangeRatesSet); + c.addExchangeRateDataSources(exchangeRateDataSourcesSet); + 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); + c.addExchangeRates(exchangeRates); + return c; + } + + static Convertor getConvertorDataSource( + Computer computer, Collection> exchangeRateDataSources) { + Convertor c = new Convertor(computer); + c.addExchangeRateDataSources(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 a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 2008 +0200 @@ -0,0 +1,103 @@ +package org.apidesign.apifest08.currency; + +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 ExchangeRateDataSource( + IdentifierType currencyAIdentifier, + IdentifierType currencyBIdentifier, + ExchangeRateProvider exchangeRateProvider) { + if (currencyAIdentifier == null || + currencyBIdentifier == null || + currencyAIdentifier.equals(currencyBIdentifier)) { + throw new IllegalArgumentException("Inappropriate exchange rates' identifiers!"); + } + this.currencyAIdentifier = currencyAIdentifier; + this.currencyBIdentifier = currencyBIdentifier; + this.exchangeRateProvider = exchangeRateProvider; + } + + public IdentifierType getCurrencyAIdentifier() { + return currencyAIdentifier; + } + + public IdentifierType getCurrencyBIdentifier() { + return currencyBIdentifier; + } + + public ExchangeRateValue getExchangeRate() { + ExchangeRateRequest request = + new ExchangeRateRequest(); + ExchangeRateResponse response = + new ExchangeRateResponse(); + + request.setCurrencyAIdentifier(currencyAIdentifier); + request.setCurrencyBIdentifier(currencyBIdentifier); + + exchangeRateProvider.getExchangeRate(request, response); + + if (response.getExchangeRate().getCurrencyA().getIdentifier().equals(currencyAIdentifier) && + response.getExchangeRate().getCurrencyB().getIdentifier().equals(currencyBIdentifier)) { + return response.getExchangeRate(); + } else { + throw new IllegalStateException("Data source's provider returned inappropriate exchange rate!"); + } + } + + public static ExchangeRateDataSource getExchangeRateDataSource( + IdentifierType currencyAIdentifier, + IdentifierType currencyBIdentifier, + ExchangeRateProvider exchangeRateProvider) { + return new ExchangeRateDataSource( + currencyAIdentifier, + currencyBIdentifier, + exchangeRateProvider); + } + + @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; + } + 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 a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 2008 +0200 @@ -0,0 +1,55 @@ +package org.apidesign.apifest08.currency; + +/** + * 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; + + 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 final class ExchangeRateResponse { + + private ExchangeRateValue exchangeRate; + + ExchangeRateResponse() { + } + + ExchangeRateValue getExchangeRate() { + return exchangeRate; + } + + public void setExchangeRate(ExchangeRateValue exchangeRate) { + this.exchangeRate = exchangeRate; + } + } +} diff -r a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f task4/solution12/build.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution12/build.xml Sat Oct 11 23:38:46 2008 +0200 @@ -0,0 +1,69 @@ + + + + + + Builds, tests, and runs the project. + + + diff -r a92eff6b426f -r 58ec6da75f6f task4/solution12/nbproject/build-impl.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution12/nbproject/build-impl.xml Sat Oct 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f task4/solution12/nbproject/genfiles.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution12/nbproject/genfiles.properties Sat Oct 11 23:38:46 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=b63e115b +nbproject/build-impl.xml.script.CRC32=3bdfc4fa +nbproject/build-impl.xml.stylesheet.CRC32=e55b27f5 diff -r a92eff6b426f -r 58ec6da75f6f task4/solution12/nbproject/project.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution12/nbproject/project.properties Sat Oct 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f task4/solution12/nbproject/project.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution12/nbproject/project.xml Sat Oct 11 23:38:46 2008 +0200 @@ -0,0 +1,16 @@ + + + org.netbeans.modules.java.j2seproject + + + Currency Convertor Solution 12 + 1.6.5 + + + + + + + + + diff -r a92eff6b426f -r 58ec6da75f6f task4/solution12/src/org/apidesign/apifest08/currency/Convertor.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution12/src/org/apidesign/apifest08/currency/Convertor.java Sat Oct 11 23:38:46 2008 +0200 @@ -0,0 +1,183 @@ +package org.apidesign.apifest08.currency; + +import java.util.ArrayList; +import java.util.Currency; +import java.util.Hashtable; +import java.util.List; + +import org.apidesign.apifest08.currency.exceptions.ConvertorException; +import org.apidesign.apifest08.currency.exceptions.InvalidCurrencyException; +import org.apidesign.apifest08.currency.exceptions.UnknownConvertorException; + +/** + * 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 class Convertor { + + private static Hashtable exchangeRates; + + private List currencyConvertors; + + /** + * Constructor. Checks if all selected currencies are not null and has defined exchange rates for both + * directions. + * @param currencies currencies for new instance of convertor + * @throws UnknownConvertorException if there are not defined exchange rates for both directions for each + * pair of currencies + */ + private Convertor(Currency[] currencies) throws UnknownConvertorException { + currencyConvertors = new ArrayList(); + + for (Currency currency1 : currencies) { + for (Currency currency2 : currencies) { + if(currency1 == null || currency2 == null) { + throw new ConvertorException("None of the currencies should be null!!!"); + } + + if(!currency1.getCurrencyCode().equals(currency2.getCurrencyCode())) { + String key = currency1.getCurrencyCode() + currency2.getCurrencyCode(); + if (!exchangeRates.containsKey(key)) { + throw new UnknownConvertorException("Selected convertor (" + currency1.getCurrencyCode() + "->" + + currency2.getCurrencyCode() + ") has not defined exchange rates!!!"); + } + + currencyConvertors.add(key); + } + } + } + } + + /** + * Sets convertor rate for selected currencies. + * @param currency1 + * one of the currencies we want to convert to/from + * @param currency2 + * the other currency + * @param rate + * exchange rate from currency1 to currency2 + * @param unit + * unit of exchangeRate (USD->CZK - unit=1, you exchange one dollar, SKK->CZK unit=100, exchange rate is for + * 100SKK) + */ + public static void setConvertorRates(Currency currency1, Currency currency2, double rate, double unit) { + if (currency1 == null || currency2 == null) { + throw new ConvertorException("None of the currencies should be null!!!"); + } + + if (rate <= 0 || unit <= 0) { + throw new ConvertorException("Rate(" + rate + ") and unit(" + unit + ") has to be grater then zero!!!"); + } + + if (exchangeRates == null) { + exchangeRates = new Hashtable(); + } + + String key12 = currency1.getCurrencyCode() + currency2.getCurrencyCode(); + String key21 = currency2.getCurrencyCode() + currency1.getCurrencyCode(); + double recountedRate = (unit / rate) * unit; + + exchangeRates.put(key12, new ExchangeRate(currency1, currency2, rate, unit)); + exchangeRates.put(key21, new ExchangeRate(currency2, currency1, recountedRate, unit)); + + } + + /** + * Merge exchange rates of actual convertor with exchange rates from selected + * convertor. If there are same currencies in both convertors, these from selected + * convertor rewrites these in actual convertor. + * @param convertor convertor to merge with actual one + * @return convertor with merged exchange rates + */ + public Convertor merge(Convertor convertor) { + if(convertor == null) { + throw new ConvertorException("It's impossible to merge with null convertor!!!"); + } + + currencyConvertors.addAll(convertor.getCurrencyConvertors()); + return this; + } + + /** + * Creates new instance of convertor. + * @param currency1 + * one of the currencies we want to convert to/from + * @param currency2 + * the other currency + * @return new instance of convertor + * @throws UnknownConvertorException + * thrown if convertor for selected currencies has not been defined + */ + public static Convertor getConvertorInstance(Currency... currencies) throws UnknownConvertorException { + if(currencies.length < 2) { + throw new ConvertorException("To get convertor instance, you have to select at least two currencies!!!"); + } + + return new Convertor(currencies); + } + + /** + * Converts selected amout of selected currency to other currency of this convertor instance. + * @param amount + * amount to convert + * @param originalCurrency + * currency of this amount + * @param newCurrency + * currency to which we want convert + * @return converted amount + * @throws InvalidCurrencyException + * while one or both currencies doesn't fit for this convertor + */ + public double convert(double amount, Currency originalCurrency, Currency newCurrency) throws InvalidCurrencyException { + ExchangeRate actualyUsedExchangeRate = null; + + if (originalCurrency == null) { + throw new ConvertorException("Original currency is null!!!"); + } + + if (newCurrency == null) { + throw new ConvertorException("Destination currency is null!!!"); + } + + actualyUsedExchangeRate = getExchangeRate(originalCurrency, newCurrency); + + return countResult(actualyUsedExchangeRate, amount); + } + + private double countResult(ExchangeRate actualyUsedExchangeRate, double amount) { + return amount * actualyUsedExchangeRate.getRate() / actualyUsedExchangeRate.getUnit(); + } + + /** + * Decides the direction of conversion and returns instance of actual exchange rate. + * @param actualCurrency + * actual currency we want to convert + * @return actual exchange rate of this convertor for selected currency + */ + private ExchangeRate getExchangeRate(Currency originalCurrency, Currency newCurrency) throws InvalidCurrencyException { + ExchangeRate actualyUsedExchangeRate = null; + + String key = originalCurrency.getCurrencyCode() + newCurrency.getCurrencyCode(); + + if(currencyConvertors.contains(key)) { + actualyUsedExchangeRate = exchangeRates.get(key); + } else { + throw new InvalidCurrencyException("This convertor could not be used for converting selected currencies (" + originalCurrency.getCurrencyCode() + "->" + + newCurrency.getCurrencyCode() + ") !!!"); + } + + return actualyUsedExchangeRate; + } + + /** + * Returns currency convertors for actual instance of convertor. + * @return currency convertors for actual instance of convertor + */ + List getCurrencyConvertors() { + return currencyConvertors; + } + +} diff -r a92eff6b426f -r 58ec6da75f6f task4/solution12/src/org/apidesign/apifest08/currency/ExchangeRate.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution12/src/org/apidesign/apifest08/currency/ExchangeRate.java Sat Oct 11 23:38:46 2008 +0200 @@ -0,0 +1,35 @@ +package org.apidesign.apifest08.currency; + +import java.util.Currency; + +public class ExchangeRate { + + private Currency originalCurrency; + private Currency newCurrency; + private double unit; + private double rate; + + public ExchangeRate(Currency originalCurrency, Currency newCurrency, double rate, double unit) { + this.newCurrency = newCurrency; + this.originalCurrency = originalCurrency; + this.rate = rate; + this.unit = unit; + } + + public Currency getOriginalCurrency() { + return originalCurrency; + } + + public Currency getNewCurrency() { + return newCurrency; + } + + public double getUnit() { + return unit; + } + + public double getRate() { + return rate; + } + +} diff -r a92eff6b426f -r 58ec6da75f6f task4/solution12/src/org/apidesign/apifest08/currency/exceptions/ConvertorException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution12/src/org/apidesign/apifest08/currency/exceptions/ConvertorException.java Sat Oct 11 23:38:46 2008 +0200 @@ -0,0 +1,20 @@ +package org.apidesign.apifest08.currency.exceptions; + +public class ConvertorException extends RuntimeException { + + public ConvertorException() { + } + + public ConvertorException(String message) { + super(message); + } + + public ConvertorException(Throwable cause) { + super(cause); + } + + public ConvertorException(String message, Throwable cause) { + super(message, cause); + } + +} diff -r a92eff6b426f -r 58ec6da75f6f task4/solution12/src/org/apidesign/apifest08/currency/exceptions/InvalidCurrencyException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution12/src/org/apidesign/apifest08/currency/exceptions/InvalidCurrencyException.java Sat Oct 11 23:38:46 2008 +0200 @@ -0,0 +1,20 @@ +package org.apidesign.apifest08.currency.exceptions; + +public class InvalidCurrencyException extends Exception { + + public InvalidCurrencyException() { + } + + public InvalidCurrencyException(String message) { + super(message); + } + + public InvalidCurrencyException(Throwable cause) { + super(cause); + } + + public InvalidCurrencyException(String message, Throwable cause) { + super(message, cause); + } + +} diff -r a92eff6b426f -r 58ec6da75f6f task4/solution12/src/org/apidesign/apifest08/currency/exceptions/UnknownConvertorException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution12/src/org/apidesign/apifest08/currency/exceptions/UnknownConvertorException.java Sat Oct 11 23:38:46 2008 +0200 @@ -0,0 +1,20 @@ +package org.apidesign.apifest08.currency.exceptions; + +public class UnknownConvertorException extends Exception { + + public UnknownConvertorException() { + } + + public UnknownConvertorException(String message) { + super(message); + } + + public UnknownConvertorException(Throwable cause) { + super(cause); + } + + public UnknownConvertorException(String message, Throwable cause) { + super(message, cause); + } + +} diff -r a92eff6b426f -r 58ec6da75f6f task4/solution12/test/org/apidesign/apifest08/test/Task1Test.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution12/test/org/apidesign/apifest08/test/Task1Test.java Sat Oct 11 23:38:46 2008 +0200 @@ -0,0 +1,174 @@ +package org.apidesign.apifest08.test; + +import java.util.Currency; + +import junit.framework.TestCase; + +import org.apidesign.apifest08.currency.Convertor; +import org.apidesign.apifest08.currency.exceptions.InvalidCurrencyException; +import org.apidesign.apifest08.currency.exceptions.UnknownConvertorException; + +/** + * 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() { + // set exchange rates + Convertor.setConvertorRates(Currency.getInstance("USD"), Currency.getInstance("CZK"), 17d, 1d); + + // create new instance + Convertor convertor = null; + try { + convertor = Convertor.getConvertorInstance(Currency.getInstance("USD"), Currency.getInstance("CZK")); + } catch (UnknownConvertorException e) { + e.printStackTrace(); + } + + return convertor; + } + + /** + * 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() { + // set exchange rates + Convertor.setConvertorRates(Currency.getInstance("SKK"), Currency.getInstance("CZK"), 80d, 100d); + + // create new instance + Convertor convertor = null; + try { + convertor = Convertor.getConvertorInstance(Currency.getInstance("SKK"), Currency.getInstance("CZK")); + } catch (UnknownConvertorException e) { + e.printStackTrace(); + } + + return convertor; + } + + // + // 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: + double result = c.convert(5, Currency.getInstance("USD"), Currency.getInstance("CZK")); + assertEquals("Result is not 85 CZK", 85.0, result); + + // convert $8 to CZK + result = c.convert(8, Currency.getInstance("USD"), Currency.getInstance("CZK")); + assertEquals("Result is not 136 CZK", 136.0, result); + + // convert 1003CZK to USD + result = c.convert(1003, Currency.getInstance("CZK"), Currency.getInstance("USD")); + assertEquals("Result is not 59 USD", 59.0, result); + } + + /** + * Use the convertor from createSKKtoCZK method and do few conversions with it. + */ + public void testCurrencySKKCZK() throws Exception { + Convertor c = createSKKtoCZK(); + + // convert 16CZK using c: + double result = c.convert(16, Currency.getInstance("CZK"), Currency.getInstance("SKK")); + assertEquals("Result is not 20 SKK", 20.0, result); + + // convert 500SKK to CZK + result = c.convert(500, Currency.getInstance("SKK"), Currency.getInstance("CZK")); + assertEquals("Result is not 400 CZK", 400.0, result); + } + + /** + * Verify that the CZK to USD convertor knows nothing about SKK. + */ + public void testCannotConvertToSKKwithCZKUSDConvertor() throws Exception { + Convertor c = createCZKtoUSD(); + boolean exceptionThrown = false; + + // convert $5 to SKK, the API shall say this is not possible + try { + c.convert(5, Currency.getInstance("USD"), Currency.getInstance("SKK")); + exceptionThrown = false; + } catch (InvalidCurrencyException e) { + exceptionThrown = true; + } + assertEquals("It should be impossible to convert to SKK with USD->CZK convertor", true, exceptionThrown); + + // convert 500 SKK to CZK, the API shall say this is not possible + try { + c.convert(500, Currency.getInstance("SKK"), Currency.getInstance("CZK")); + exceptionThrown = false; + } catch (InvalidCurrencyException e) { + exceptionThrown = true; + } + assertEquals("It should be impossible to convert from SKK with USD->CZK convertor", true, exceptionThrown); + + } + + /** + * Verify that the CZK to SKK convertor knows nothing about USD. + */ + public void testCannotConvertToSKKwithSKKCZKConvertor() throws Exception { + Convertor c = createSKKtoCZK(); + boolean exceptionThrown = false; + + // convert $5 to SKK, the API shall say this is not possible + try { + c.convert(5, Currency.getInstance("USD"), Currency.getInstance("SKK")); + exceptionThrown = false; + } catch (InvalidCurrencyException e) { + exceptionThrown = true; + } + assertEquals("It should be impossible to convert form USD with SKK->CZK convertor", true, exceptionThrown); + + // convert 500 CZK to USD, the API shall say this is not possible + try { + c.convert(500, Currency.getInstance("CZK"), Currency.getInstance("USD")); + exceptionThrown = false; + } catch (InvalidCurrencyException e) { + exceptionThrown = true; + } + assertEquals("It should be impossible to convert to USD with SKK->CZK convertor", true, exceptionThrown); + } +} diff -r a92eff6b426f -r 58ec6da75f6f task4/solution12/test/org/apidesign/apifest08/test/Task2Test.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution12/test/org/apidesign/apifest08/test/Task2Test.java Sat Oct 11 23:38:46 2008 +0200 @@ -0,0 +1,132 @@ +package org.apidesign.apifest08.test; + +import java.util.Currency; + +import junit.framework.TestCase; + +import org.apidesign.apifest08.currency.Convertor; +import org.apidesign.apifest08.currency.exceptions.UnknownConvertorException; + +/** 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 + // set exchange rates + Convertor.setConvertorRates(Currency.getInstance("USD"), Currency.getInstance("CZK"), 15, 1); + Convertor.setConvertorRates(Currency.getInstance("USD"), Currency.getInstance("SKK"), 20, 1); + Convertor.setConvertorRates(Currency.getInstance("SKK"), Currency.getInstance("CZK"), 75, 100); + + // create new instance + Convertor convertor = null; + try { + convertor = Convertor.getConvertorInstance(Currency.getInstance("USD"), Currency.getInstance("SKK"), Currency.getInstance("CZK")); + } catch (UnknownConvertorException e) { + e.printStackTrace(); + } + return convertor; + } + + /** Define convertor that understands three currencies. Use it. + */ + public void testConvertorForUSDandCZKandSKK() throws Exception { + Convertor c = createTripleConvertor(); + + // convert $5 to CZK using c: + double result = c.convert(5d, Currency.getInstance("USD"), Currency.getInstance("CZK")); + assertEquals("Result is not 75 CZK", 75.0, result); + + // convert $5 to SKK using c: + result = c.convert(5d, Currency.getInstance("USD"), Currency.getInstance("SKK")); + assertEquals("Result is not 100 SKK", 100.0, result); + + // convert 200SKK to CZK using c: + result = c.convert(200d, Currency.getInstance("SKK"), Currency.getInstance("CZK")); + assertEquals("Result is not 150 CZK", 150.0, result); + + // convert 200SKK to USK using c: + result = c.convert(200d, Currency.getInstance("SKK"), Currency.getInstance("USD")); + assertEquals("Result is not 10 USD", 10.0, 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 one.merge(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: + double result = c.convert(5d, Currency.getInstance("USD"), Currency.getInstance("CZK")); + assertEquals("Result is not 85 CZK", 85.0, result); + + // convert $8 to CZK using c: + result = c.convert(8d, Currency.getInstance("USD"), Currency.getInstance("CZK")); + assertEquals("Result is not 136 CZK", 136.0, result); + + // convert 1003CZK to USD using c: + result = c.convert(1003d, Currency.getInstance("CZK"), Currency.getInstance("USD")); + assertEquals("Result is not 59 USD", 59.0, result); + + // convert 16CZK using c: + result = c.convert(16d, Currency.getInstance("CZK"), Currency.getInstance("SKK")); + assertEquals("Result is not 20 SKK", 20.0, result); + + // convert 500SKK to CZK using c: + result = c.convert(500d, Currency.getInstance("SKK"), Currency.getInstance("CZK")); + assertEquals("Result is not 400 CZK", 400.0, result); + + } +} diff -r a92eff6b426f -r 58ec6da75f6f task4/solution12/test/org/apidesign/apifest08/test/Task3Test.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution12/test/org/apidesign/apifest08/test/Task3Test.java Sat Oct 11 23:38:46 2008 +0200 @@ -0,0 +1,145 @@ +package org.apidesign.apifest08.test; + +import java.util.Currency; + +import junit.framework.TestCase; +import org.apidesign.apifest08.currency.Convertor; +import org.apidesign.apifest08.currency.exceptions.UnknownConvertorException; + +/** 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 double actualRate; + private static boolean increasing; + + private static final double EXCHANGE_RATE_MAX = 16.0; + private static final double EXCHANGE_RATE_MIN = 15.0; + + 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() { + actualRate = 16.01; + increasing = false; + + // sets actual exchange rates + setRates(); + + // create new instance + Convertor convertor = null; + try { + convertor = Convertor.getConvertorInstance(Currency.getInstance("USD"), Currency.getInstance("CZK")); + } catch (UnknownConvertorException e) { + e.printStackTrace(); + } + + return convertor; + } + + public void testFewQueriesForOnlineConvertor() throws Exception { + Convertor c = createOnlineCZKUSDConvertor(); + doFewQueriesForOnlineConvertor(c); + } + + static void doFewQueriesForOnlineConvertor(Convertor c) throws Exception { + // convert $5 to CZK using c: + double result = c.convert(5d, Currency.getInstance("USD"), Currency.getInstance("CZK")); + double expectedResult = actualRate * 5; + assertEquals("Result is not " + expectedResult + " CZK", expectedResult, result); + + // change exchange rates + setRates(); + + // convert $8 to CZK using c: + result = c.convert(8d, Currency.getInstance("USD"), Currency.getInstance("CZK")); + expectedResult = actualRate * 8; + assertEquals("Result is not " + expectedResult + " CZK", expectedResult, result); + + // change exchange rates + setRates(); + + // convert $1 to CZK using c: + result = c.convert(1d, Currency.getInstance("USD"), Currency.getInstance("CZK")); + expectedResult = actualRate * 1; + assertEquals("Result is not " + expectedResult + " CZK", expectedResult, result); + + // change exchange rates + setRates(); + + // convert 15.97CZK to USD using c: + result = c.convert(15.97d, Currency.getInstance("CZK"), Currency.getInstance("USD")); + expectedResult = 15.97 / actualRate ; + assertEquals("Result is not " + expectedResult + " USD", expectedResult, result); + } + + /** 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: + double result = c.convert(16d, Currency.getInstance("CZK"), Currency.getInstance("SKK")); + assertEquals("Result is not 20 SKK", 20d, result); + + // convert 500SKK to CZK using c: + result = c.convert(500d, Currency.getInstance("SKK"), Currency.getInstance("CZK")); + assertEquals("Result is not 400 CZK", 400d, result); + + doFewQueriesForOnlineConvertor(c); + } + + private static void setRates() { + // logic for change of actual exchange rate + if(increasing) { + actualRate += 0.01; + if(actualRate == EXCHANGE_RATE_MAX){ + increasing = false; + } + } else { + actualRate -= 0.01; + if(actualRate == EXCHANGE_RATE_MIN){ + increasing = true; + } + } + + // set exchange rates + Convertor.setConvertorRates(Currency.getInstance("USD"), Currency.getInstance("CZK"), actualRate, 1d); + } +} diff -r a92eff6b426f -r 58ec6da75f6f task4/solution13/build.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution13/build.xml Sat Oct 11 23:38:46 2008 +0200 @@ -0,0 +1,69 @@ + + + + + + Builds, tests, and runs the project. + + + diff -r a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f task4/solution13/nbproject/genfiles.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution13/nbproject/genfiles.properties Sat Oct 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f task4/solution13/nbproject/project.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution13/nbproject/project.properties Sat Oct 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f task4/solution13/nbproject/project.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution13/nbproject/project.xml Sat Oct 11 23:38:46 2008 +0200 @@ -0,0 +1,16 @@ + + + org.netbeans.modules.java.j2seproject + + + Currency Convertor Solution 13 + 1.6.5 + + + + + + + + + diff -r a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 onversion nor reverted conversion from " + from + " to " + to + " is not 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 a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 2008 +0200 @@ -0,0 +1,49 @@ + +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; + } + +} diff -r a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 2008 +0200 @@ -0,0 +1,218 @@ +package org.apidesign.apifest08.currency; + +import java.math.BigDecimal; +import java.math.MathContext; +import java.math.RoundingMode; + +/** 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; + + /** 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) { + return new Convertor(convertors); + } + + boolean remainderAllowed = true; //if false, remained is not allowed (should be true ideally, but can't handle it now) + ExchangeRateProvider exchangeRateProvider; + + /** Create simle convertor. + */ + private Convertor() { + this.convertors=new Convertor[0]; + } + + /** Create merge convertor. + */ + private Convertor(Convertor[] convertors) { + this.convertors = convertors; + } + + /** + * Create new Convertor 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); + } + + /** + * 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); + } + + private ConversionResult convertUsingSimpleConvertor(ConvertorCurrency fromCurrency, ConvertorCurrency toCurrency, boolean reversibleExRate, BigDecimal amount, boolean convertBack) throws ConversionNotSupportedException, RuntimeException { + ConversionResult result = new ConversionResult(); + + //ExchangeRate rate = exchangeRateProvider.getExchangeRate(); + ExchangeRate rate; + if (reversibleExRate) { + rate = exchangeRateProvider.getReversibleExchangeRate(fromCurrency, toCurrency); + } else { + rate = exchangeRateProvider.getExchangeRate(fromCurrency, toCurrency); + } + if (rate == null) { + return null; + } + + int fromFranctionDigits = fromCurrency.getDefaultFractionDigits(); + int toFractionDigits = toCurrency.getDefaultFractionDigits(); + + if (toFractionDigits != 2) { + throw new ConvertorException("Can't process currency with defaultFractionDigits!=2, " + exchangeRateProvider.getToCurrency() + " has " + toFractionDigits + " defaultFractionDigits"); + } + if (fromFranctionDigits != 2) { + throw new ConvertorException("Can't process currency with defaultFractionDigits!=2, " + exchangeRateProvider.getFromCurrency() + " 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(toFractionDigits); + + 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); + } + + BigDecimal converted = division[0].movePointLeft(toFractionDigits); + converted = converted.setScale(toFractionDigits); //XXX ugly + result.setConverted(converted); + //result.setRemainder(...); + return result; + } + + + private ConversionResult convertValue(ConvertorCurrency fromCurrency, ConvertorCurrency toCurrency,BigDecimal amount, boolean convertBack,boolean reversibleExRate) throws RuntimeException { + //result.setRemainder(...); + if (convertors.length==0) { + return convertUsingSimpleConvertor(fromCurrency, toCurrency, reversibleExRate, amount, convertBack); + } 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. + * + * @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) { + ConversionResult result = convertValue(fromCurrency, toCurrency, value, false,false); + if (result==null) { + //throw new ConversionNotSupportedException("Conversion from " + fromCurrency + " to " + toCurrency + " is not supported"); + 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. + * + * @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) { + ConversionResult result = convertValue(fromCurrency, toCurrency, value, false,true); + 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; + } + +} diff -r a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 2008 +0200 @@ -0,0 +1,70 @@ + +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 Currency currency; + + private void setJavaCurrency(Currency javaCurrency) { + this.currency = javaCurrency; + } + + /** + * Static method providing instance of ConvertorCurrency base of currency code. + * + * @param currencyCode Code of required currency. + * @return Returns required ConvertorCurrency + */ + public static ConvertorCurrency getInstance(String currencyCode) { + ConvertorCurrency convertorCurrency = new ConvertorCurrency(); + convertorCurrency.setJavaCurrency(Currency.getInstance(currencyCode)); + 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 currency.getDefaultFractionDigits(); + } + + @Override + public boolean equals(Object obj) { + boolean result; + if (obj instanceof ConvertorCurrency) { + ConvertorCurrency that = (ConvertorCurrency) obj; + result = currency.equals(that.currency); + } else { + result = false; + } + return result; + } + + @Override + public int hashCode() { + return currency==null ? 47/*??*/ : currency.hashCode(); + } + + + + + @Override + public String toString() { + return "ConvertorCurrency[" + (currency != null ? currency.toString() : "NO-BASE-CURRENCY")+"]"; + } + + String getCurrencyCode() { + return currency.getCurrencyCode(); + } +} diff -r a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 2008 +0200 @@ -0,0 +1,267 @@ +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; + + /** + * 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; + } + + /** + * 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). + * @return Returns exchange rate or null if exchange rate not found. + */ + public ExchangeRate getExchangeRate(ConvertorCurrency fromCurrency, ConvertorCurrency toCurrency) { + return getExchangeRateImpl(fromCurrency, toCurrency); + } + + /** + * Get fixed exange rate for currencies (from->to) or reversed exchange rate (to->from). + * @return Returns exchange rate or null if exchange rate not found. + */ + public ExchangeRate getReversibleExchangeRate(ConvertorCurrency fromCurrency, ConvertorCurrency toCurrency) { + ExchangeRate rate = getExchangeRateImpl(fromCurrency, toCurrency); + if (rate == null) { + ExchangeRate revertedRate = getExchangeRateImpl(toCurrency, fromCurrency); + if (revertedRate != null) { + rate = ExchangeRate.createRevertedRate(revertedRate); + } + } + return rate; + } + + /** + * 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 getExchangeRateImpl(ConvertorCurrency fromCurrency, ConvertorCurrency toCurrency) { + ExchangeRate result = exrateEngine.getExchangeRate(fromCurrency, toCurrency); + 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 = (Map) exchangeRateMap.get(fromCurrency); + if (map2 == null) { + return null; + } + ExchangeRate result = (ExchangeRate) map2.get(toCurrency); + return result; + } + + @SuppressWarnings("unchecked") + 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 = (Map) 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 a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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", BigDecimal.ZERO, 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", BigDecimal.ZERO, 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, 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, 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, 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, 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, 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 a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 = currencyUSD; + 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 a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f task4/solution14/build.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution14/build.xml Sat Oct 11 23:38:46 2008 +0200 @@ -0,0 +1,69 @@ + + + + + + Builds, tests, and runs the project. + + + diff -r a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f task4/solution14/nbproject/genfiles.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution14/nbproject/genfiles.properties Sat Oct 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f task4/solution14/nbproject/project.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution14/nbproject/project.properties Sat Oct 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f task4/solution14/nbproject/project.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution14/nbproject/project.xml Sat Oct 11 23:38:46 2008 +0200 @@ -0,0 +1,16 @@ + + + org.netbeans.modules.java.j2seproject + + + Currency Convertor Solution 14 + 1.6.5 + + + + + + + + + diff -r a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 2008 +0200 @@ -0,0 +1,201 @@ +package org.apidesign.apifest08.currency; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +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++) { + 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); + + curRates.add(curRat); + } + this.currencyRates = Collections.unmodifiableList(curRates); + } + + public double convert(String fromCurrency, String toCurrency, int amount) { + 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 (CurrencyRate curRate : currencyRates) { + if ((curRate.getCurrency1().equals(fromCurrency))&& + (curRate.getCurrency2().equals(toCurrency))) + { + return curRate.getRate().convertAtoB(amount); + } + } + //suitable convertor not found, try to find inverse convertor + for (CurrencyRate curRate : currencyRates) { + if ((curRate.getCurrency2().equals(fromCurrency))&& + (curRate.getCurrency1().equals(toCurrency))) + { + 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) { + 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 (CurrencyRate curRate : currencyRates) { + if ((curRate.getCurrency1().equals(fromCurrency))&& + (curRate.getCurrency2().equals(toCurrency))) + { + return curRate.getRate().convertAtoB(amount); + } + } + //suitable convertor not found, try to find inverse convertor + for (CurrencyRate curRate : currencyRates) { + if ((curRate.getCurrency2().equals(fromCurrency))&& + (curRate.getCurrency1().equals(toCurrency))) + { + 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 + return currencyRates; + } + } + + @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 a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 2008 +0200 @@ -0,0 +1,66 @@ + +package org.apidesign.apifest08.currency; + +import java.util.ArrayList; +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])); + } + +} diff -r a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 2008 +0200 @@ -0,0 +1,25 @@ +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)); + } + +} diff -r a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 2008 +0200 @@ -0,0 +1,37 @@ + +package org.apidesign.apifest08.currency; + +public final class CurrencyRateImpl implements CurrencyRate { + private String currency1; + private String currency2; + private Rate rate; + + 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; + } + + public String getCurrency1() { + return currency1; + } + + public String getCurrency2() { + return currency2; + } + + public Rate getRate(){ + return rate; + } + +} diff -r a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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 a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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().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("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 a92eff6b426f -r 58ec6da75f6f 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 11 23:38:46 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); + } +}