# HG changeset patch # User Jaroslav Tulach # Date 1223370334 -7200 # Node ID 251d0ed461fb6f89e8694eedc9490ef1e02b4b03 # Parent 6a500cd1e4679bb412526f5b1da731a1a77534ff Copying all solution that advanced into round #3 into task3 directory diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution02/build.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution02/build.xml Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,69 @@ + + + + + + Builds, tests, and runs the project. + + + diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution02/nbproject/build-impl.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution02/nbproject/build-impl.xml Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,642 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set src.dir + Must set test.src.dir + Must set build.dir + Must set dist.dir + Must set build.classes.dir + Must set dist.javadoc.dir + Must set build.test.classes.dir + Must set build.test.results.dir + Must set build.classes.excludes + Must set dist.jar + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + + + + + + java -cp "${run.classpath.with.dist.jar}" ${main.class} + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + java -jar "${dist.jar.resolved}" + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set run.class + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set debug.class + + + + + Must set fix.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + Some tests failed; see details above. + + + + + + + + + Must select some files in the IDE or set test.includes + + + + Some tests failed; see details above. + + + + + Must select one file in the IDE or set test.class + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + + + + + + + + + + + diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution02/nbproject/genfiles.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution02/nbproject/genfiles.properties Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,8 @@ +build.xml.data.CRC32=2ab820eb +build.xml.script.CRC32=58a52595 +build.xml.stylesheet.CRC32=be360661 +# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. +# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. +nbproject/build-impl.xml.data.CRC32=848e6267 +nbproject/build-impl.xml.script.CRC32=6be86987 +nbproject/build-impl.xml.stylesheet.CRC32=e55b27f5 diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution02/nbproject/project.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution02/nbproject/project.properties Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,68 @@ +application.title=currency +application.vendor=apidesign.org +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.tab-size=8 +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.text-limit-width=80 +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.usedProfile=default +build.classes.dir=${build.dir}/classes +build.classes.excludes=**/*.java,**/*.form +# This directory is removed when the project is cleaned: +build.dir=build +build.generated.dir=${build.dir}/generated +# Only compile against the classpath explicitly listed here: +build.sysclasspath=ignore +build.test.classes.dir=${build.dir}/test/classes +build.test.results.dir=${build.dir}/test/results +debug.classpath=\ + ${run.classpath} +debug.test.classpath=\ + ${run.test.classpath} +# This directory is removed when the project is cleaned: +dist.dir=dist +dist.jar=${dist.dir}/currency.jar +dist.javadoc.dir=${dist.dir}/javadoc +excludes= +file.reference.junit-4.4.jar=../../libs/junit-4.4.jar +file.reference.src-apifest08=.. +includes=** +jar.compress=false +javac.classpath= +# Space-separated list of extra javac options +javac.compilerargs= +javac.deprecation=false +javac.source=1.5 +javac.target=1.5 +javac.test.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir}:\ + ${file.reference.junit-4.4.jar} +javadoc.additionalparam= +javadoc.author=false +javadoc.encoding= +javadoc.noindex=false +javadoc.nonavbar=false +javadoc.notree=false +javadoc.private=false +javadoc.splitindex=true +javadoc.use=true +javadoc.version=false +javadoc.windowtitle= +jnlp.codebase.type=local +jnlp.codebase.url=file:/home/jarda/src/apifest08/currency/dist +jnlp.descriptor=application +jnlp.enabled=false +jnlp.offline-allowed=false +jnlp.signed=false +meta.inf.dir=${src.dir}/META-INF +platform.active=default_platform +run.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +# Space-separated list of JVM arguments used when running the project +# (you may also define separate properties like run-sys-prop.name=value instead of -Dname=value +# or test-sys-prop.name=value to set system properties for unit tests): +run.jvmargs= +run.test.classpath=\ + ${javac.test.classpath}:\ + ${build.test.classes.dir} +src.dir=src +test.src.dir=test diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution02/nbproject/project.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution02/nbproject/project.xml Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,16 @@ + + + org.netbeans.modules.java.j2seproject + + + Currency Convertor Solution 02 + 1.6.5 + + + + + + + + + diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution02/src/org/apidesign/apifest08/currency/CompositeConvertor.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution02/src/org/apidesign/apifest08/currency/CompositeConvertor.java Tue Oct 07 11:05:34 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 6a500cd1e467 -r 251d0ed461fb task3/solution02/src/org/apidesign/apifest08/currency/Convertor.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution02/src/org/apidesign/apifest08/currency/Convertor.java Tue Oct 07 11:05:34 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 6a500cd1e467 -r 251d0ed461fb task3/solution02/src/org/apidesign/apifest08/currency/ConvertorFactory.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution02/src/org/apidesign/apifest08/currency/ConvertorFactory.java Tue Oct 07 11:05:34 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. + * @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. + * @param convertors + * @return + */ + public static final ExtendedConvertor mergeConvertors(ExtendedConvertor... convertors) + { + return new CompositeConvertor(convertors); + } + + +} diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution02/src/org/apidesign/apifest08/currency/DefaultConvertor.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution02/src/org/apidesign/apifest08/currency/DefaultConvertor.java Tue Oct 07 11:05:34 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 6a500cd1e467 -r 251d0ed461fb task3/solution02/src/org/apidesign/apifest08/currency/ExtendedConvertor.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution02/src/org/apidesign/apifest08/currency/ExtendedConvertor.java Tue Oct 07 11:05:34 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 6a500cd1e467 -r 251d0ed461fb task3/solution02/src/org/apidesign/apifest08/currency/Money.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution02/src/org/apidesign/apifest08/currency/Money.java Tue Oct 07 11:05:34 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 6a500cd1e467 -r 251d0ed461fb task3/solution02/src/org/apidesign/apifest08/currency/MoneyImpl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution02/src/org/apidesign/apifest08/currency/MoneyImpl.java Tue Oct 07 11:05:34 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 6a500cd1e467 -r 251d0ed461fb task3/solution02/test/org/apidesign/apifest08/currency/CompositeConvertorTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution02/test/org/apidesign/apifest08/currency/CompositeConvertorTest.java Tue Oct 07 11:05:34 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 6a500cd1e467 -r 251d0ed461fb task3/solution02/test/org/apidesign/apifest08/test/ConvertorFactoryTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution02/test/org/apidesign/apifest08/test/ConvertorFactoryTest.java Tue Oct 07 11:05:34 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 6a500cd1e467 -r 251d0ed461fb task3/solution02/test/org/apidesign/apifest08/test/ConvertorTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution02/test/org/apidesign/apifest08/test/ConvertorTest.java Tue Oct 07 11:05:34 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 6a500cd1e467 -r 251d0ed461fb task3/solution02/test/org/apidesign/apifest08/test/MoneyTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution02/test/org/apidesign/apifest08/test/MoneyTest.java Tue Oct 07 11:05:34 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 6a500cd1e467 -r 251d0ed461fb task3/solution02/test/org/apidesign/apifest08/test/Task1Test.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution02/test/org/apidesign/apifest08/test/Task1Test.java Tue Oct 07 11:05:34 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 6a500cd1e467 -r 251d0ed461fb task3/solution02/test/org/apidesign/apifest08/test/Task2Test.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution02/test/org/apidesign/apifest08/test/Task2Test.java Tue Oct 07 11:05:34 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 6a500cd1e467 -r 251d0ed461fb task3/solution04/build.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution04/build.xml Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,69 @@ + + + + + + Builds, tests, and runs the project. + + + diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution04/nbproject/build-impl.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution04/nbproject/build-impl.xml Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,642 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set src.dir + Must set test.src.dir + Must set build.dir + Must set dist.dir + Must set build.classes.dir + Must set dist.javadoc.dir + Must set build.test.classes.dir + Must set build.test.results.dir + Must set build.classes.excludes + Must set dist.jar + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + + + + + + java -cp "${run.classpath.with.dist.jar}" ${main.class} + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + java -jar "${dist.jar.resolved}" + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set run.class + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set debug.class + + + + + Must set fix.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + Some tests failed; see details above. + + + + + + + + + Must select some files in the IDE or set test.includes + + + + Some tests failed; see details above. + + + + + Must select one file in the IDE or set test.class + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + + + + + + + + + + + diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution04/nbproject/genfiles.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution04/nbproject/genfiles.properties Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,8 @@ +build.xml.data.CRC32=2ab820eb +build.xml.script.CRC32=58a52595 +build.xml.stylesheet.CRC32=be360661 +# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. +# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. +nbproject/build-impl.xml.data.CRC32=2fbfa6ce +nbproject/build-impl.xml.script.CRC32=c521eea7 +nbproject/build-impl.xml.stylesheet.CRC32=e55b27f5 diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution04/nbproject/project.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution04/nbproject/project.properties Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,68 @@ +application.title=currency +application.vendor=apidesign.org +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.tab-size=8 +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.text-limit-width=80 +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.usedProfile=default +build.classes.dir=${build.dir}/classes +build.classes.excludes=**/*.java,**/*.form +# This directory is removed when the project is cleaned: +build.dir=build +build.generated.dir=${build.dir}/generated +# Only compile against the classpath explicitly listed here: +build.sysclasspath=ignore +build.test.classes.dir=${build.dir}/test/classes +build.test.results.dir=${build.dir}/test/results +debug.classpath=\ + ${run.classpath} +debug.test.classpath=\ + ${run.test.classpath} +# This directory is removed when the project is cleaned: +dist.dir=dist +dist.jar=${dist.dir}/currency.jar +dist.javadoc.dir=${dist.dir}/javadoc +excludes= +file.reference.junit-4.4.jar=../../libs/junit-4.4.jar +file.reference.src-apifest08=.. +includes=** +jar.compress=false +javac.classpath= +# Space-separated list of extra javac options +javac.compilerargs= +javac.deprecation=false +javac.source=1.5 +javac.target=1.5 +javac.test.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir}:\ + ${file.reference.junit-4.4.jar} +javadoc.additionalparam= +javadoc.author=false +javadoc.encoding= +javadoc.noindex=false +javadoc.nonavbar=false +javadoc.notree=false +javadoc.private=false +javadoc.splitindex=true +javadoc.use=true +javadoc.version=false +javadoc.windowtitle= +jnlp.codebase.type=local +jnlp.codebase.url=file:/home/jarda/src/apifest08/currency/dist +jnlp.descriptor=application +jnlp.enabled=false +jnlp.offline-allowed=false +jnlp.signed=false +meta.inf.dir=${src.dir}/META-INF +platform.active=default_platform +run.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +# Space-separated list of JVM arguments used when running the project +# (you may also define separate properties like run-sys-prop.name=value instead of -Dname=value +# or test-sys-prop.name=value to set system properties for unit tests): +run.jvmargs= +run.test.classpath=\ + ${javac.test.classpath}:\ + ${build.test.classes.dir} +src.dir=src +test.src.dir=test diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution04/nbproject/project.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution04/nbproject/project.xml Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,16 @@ + + + org.netbeans.modules.java.j2seproject + + + Currency Convertor Solution 04 + 1.6.5 + + + + + + + + + diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution04/src/org/apidesign/apifest08/currency/CompositeConvertorImpl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution04/src/org/apidesign/apifest08/currency/CompositeConvertorImpl.java Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,314 @@ +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.0 + */ +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)); + } + + /** + * 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; + + 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"); + } + + result = amount.multiply(getConversionRate(from, to)); + + 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 6a500cd1e467 -r 251d0ed461fb task3/solution04/src/org/apidesign/apifest08/currency/ConverterImpl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution04/src/org/apidesign/apifest08/currency/ConverterImpl.java Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,282 @@ +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 cvonvert from. + */ + private final Currency currencyA; + + /** + * The currency to cvonvert from. + */ + 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. + */ + public boolean canConvert(final Currency from, final Currency to) + { + 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. + */ + public BigDecimal getConversionRate(final Currency from, + final Currency to) + throws InvalidConversionException + { + final BigDecimal rate; + + 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 6a500cd1e467 -r 251d0ed461fb task3/solution04/src/org/apidesign/apifest08/currency/Convertor.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution04/src/org/apidesign/apifest08/currency/Convertor.java Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,59 @@ +package org.apidesign.apifest08.currency; + + +import java.math.BigDecimal; +import java.util.Currency; +import java.util.Set; + + +/** + * Convert between two currencies. + * + * @author D'Arcy Smith + * @version 1.0 + */ +public interface Convertor +{ + /** + * Convert an amount from one currency to another. + * + * @param from the currency to convert from. + * @param to the currency to convert to. + * @param amount the amount to convert. + * @return the converted amount. + * @throws IllegalArgumentException if any of the arguments are null. + * @throws InvalidConversionException if either from or to are not valid for the convertor. + */ + BigDecimal convert(Currency from, + Currency to, + BigDecimal amount) + throws InvalidConversionException; + + /** + * Check to see if converting between the two currencies is possible. + * + * @param from the currency to convert from. + * @param to the currency to convert to. + * @return true if the conversion is possible. + */ + boolean canConvert(Currency from, Currency to); + + /** + * Get the currencies that the convertor supports. Just because a currency is + * supported does not mean that canConvert will return true. + * + * @return the supported currencies. + */ + Set getCurrencies(); + + /** + * Get the conversion rate between two currencies. + * + * @param from the currency to convert from. + * @param to the currency to convert to. + * @return the conversion rate between the two currencies. + * @throws InvalidConversionException if canConvert would return false. + */ + BigDecimal getConversionRate(final Currency from, final Currency to) + throws InvalidConversionException; +} diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution04/src/org/apidesign/apifest08/currency/ConvertorFactory.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution04/src/org/apidesign/apifest08/currency/ConvertorFactory.java Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,172 @@ +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); + } + + 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 6a500cd1e467 -r 251d0ed461fb task3/solution04/src/org/apidesign/apifest08/currency/InvalidConversionException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution04/src/org/apidesign/apifest08/currency/InvalidConversionException.java Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,95 @@ +package org.apidesign.apifest08.currency; + + +import java.util.Currency; + + +/** + * Thrown when a currency is invalid for a given Convertor. + * + * @author D'Arcy Smith + * @version 1.0 + */ +public class InvalidConversionException + extends Exception +{ + /** + * The currency that was tried. + */ + private final Currency badCurrency; + + /** + * A currency that is valid for the Convertor. + */ + private final Currency currencyA; + + /** + * A currency that is valid for the Convertor. + */ + private final Currency currencyB; + + + /** + * Construct a new InvalidConversionException with the specified message. + * + * @param msg the message for getMessage. + * @param bad the currency that is not valid. + */ + public InvalidConversionException(final String msg, + final Currency bad) + { + this(msg, bad, null, null); + } + + /** + * Construct a new InvalidConversionException with the specified message. + * + * @param msg the message for getMessage. + * @param bad the currency that is not valid. + * @param a a valid currency. + * @param b a valid currency. + */ + public InvalidConversionException(final String msg, + final Currency bad, + final Currency a, + final Currency b) + { + super(msg); + + badCurrency = bad; + currencyA = a; + currencyB = b; + } + + /** + * Get the currency that is not valid. + * + * @return the badCurrency + */ + public Currency getBadCurrency() + { + return (badCurrency); + } + + /** + * Get a currency that is valid. + * + * @return the currencyA passed to the constructor. + */ + public Currency getCurrencyA() + { + return (currencyA); + } + + /** + * Get a currency that is valid. + * + * @return the currencyB passed to the constructor. + */ + public Currency getCurrencyB() + { + return (currencyB); + } + + +} \ No newline at end of file diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution04/test/org/apidesign/apifest08/test/Task1Test.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution04/test/org/apidesign/apifest08/test/Task1Test.java Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,223 @@ +package org.apidesign.apifest08.test; + + +import java.math.BigDecimal; +import java.util.Currency; +import java.util.Set; +import junit.framework.TestCase; +import org.apidesign.apifest08.currency.Convertor; +import org.apidesign.apifest08.currency.ConvertorFactory; +import org.apidesign.apifest08.currency.InvalidConversionException; + + +/** Finish the Convertor API, and then write bodies of methods inside + * of this class to match the given tasks. To fullfil your task, use the + * API define in the org.apidesign.apifest08.currency package. + * Do not you reflection, or other hacks as your code + * shall run without any runtime permissions. + */ +public class Task1Test extends TestCase { + + 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 6a500cd1e467 -r 251d0ed461fb task3/solution04/test/org/apidesign/apifest08/test/Task2Test.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution04/test/org/apidesign/apifest08/test/Task2Test.java Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,179 @@ +package org.apidesign.apifest08.test; + +import java.math.BigDecimal; +import java.util.Currency; +import java.util.Set; +import junit.framework.TestCase; +import org.apidesign.apifest08.currency.Convertor; +import org.apidesign.apifest08.currency.ConvertorFactory; +import org.apidesign.apifest08.currency.InvalidConversionException; + + +/** There are many currencies around the world and many banks manipulate + * with more than one or two at the same time. As banks are usually the + * best paying clients, which is true even in case of your Convertor API, + * it is reasonable to listen to their requests. + *

+ * The quest for today is to enhance your existing convertor API to hold + * information about many currencies and allow conversions between any of them. + * Also, as conversion rates for diferent currencies usually arise from various + * bank departments, there is another important need. There is a need to + * compose two convertors into one by merging all the information about + * currencies they know about. + */ +public class Task2Test extends TestCase +{ + private final static Currency CZK; + private final static Currency SKK; + private final static Currency USD; + + static + { + CZK = Currency.getInstance("CZK"); + SKK = Currency.getInstance("SKK"); + USD = Currency.getInstance("USD"); + } + + public Task2Test(String testName) + { + super(testName); + } + + @Override + protected void setUp() + throws Exception + { + } + + @Override + protected void tearDown() + throws Exception + { + } + + // As in Task1Test, keep in mind, that there are three parts + // of the whole system: + // 1. there is someone who knows the current exchange rate + // 2. there is someone who wants to do the conversion + // 3. there is the API between 1. and 2. which allows them to communicate + // + // Please backward compatibly enhance your existing API to support following + // usecases: + // + + /** Create convertor that understands two currencies, CZK and + * SKK. Make 100 SKK == 75 CZK. This is method for the group of users that + * knows the exchange rate, and needs to use the API to create objects + * with the exchange rate. Anyone shall be ready to call this method without + * any other method being called previously. The API itself shall know + * nothing about any rates, before this method is called. + */ + public static Convertor createTripleConvertor() { + // Rates: 1USD = 15CZK + // Rates: 1USD = 20SKK + // Rates: 75CZK = 100SKK + Convertor c = ConvertorFactory.mergeConvertors( + ConvertorFactory.getConvertor(USD, BigDecimal.ONE, CZK, BigDecimal.valueOf(15.00)), + ConvertorFactory.getConvertor(USD, BigDecimal.ONE, SKK, BigDecimal.valueOf(20.00)) + ); + + return c; + } + + /** Define convertor that understands three currencies. Use it. + */ + public void testConvertorForUSDandCZKandSKK() throws Exception { + Convertor c = createTripleConvertor(); + + // convert $5 to CZK using c: + // assertEquals("Result is 75 CZK"); + assertEquals(new BigDecimal("75.00"), c.convert(USD, CZK, BigDecimal.valueOf(5.00))); + + // convert $5 to SKK using c: + // assertEquals("Result is 100 SKK"); + assertEquals(new BigDecimal("100.00"), c.convert(USD, SKK, BigDecimal.valueOf(5.00))); + + // convert 200SKK to CZK using c: + // assertEquals("Result is 150 CZK"); + assertEquals(new BigDecimal("150.00"), c.convert(SKK, CZK, BigDecimal.valueOf(200.00))); + + // convert 200SKK to USK using c: + // assertEquals("Result is 10 USD"); + assertEquals(new BigDecimal("10.00"), c.convert(SKK, USD, BigDecimal.valueOf(200.00))); + } + + /** Merge all currency rates of convertor 1 with convertor 2. + * Implement this using your API, preferably this method just delegates + * into some API method which does the actual work, without requiring + * API clients to code anything complex. + */ + public static Convertor merge(Convertor one, Convertor two) { + return ConvertorFactory.mergeConvertors(one, two); + } + + /** Join the convertors from previous task, Task1Test and show that it + * can be used to do reasonable conversions. + */ + public void testConvertorComposition() throws Exception { + Convertor c = merge( + Task1Test.createCZKtoUSD(), + Task1Test.createSKKtoCZK() + ); + + // convert $5 to CZK using c: + // assertEquals("Result is 85 CZK"); + assertEquals(new BigDecimal("85.00"), c.convert(USD, CZK, BigDecimal.valueOf(5.00))); + + // convert $8 to CZK using c: + // assertEquals("Result is 136 CZK"); + assertEquals(new BigDecimal("136.00"), c.convert(USD, CZK, BigDecimal.valueOf(8.00))); + + // convert 1003CZK to USD using c: + // assertEquals("Result is 59 USD"); + assertEquals(new BigDecimal("59.00"), c.convert(CZK, USD, BigDecimal.valueOf(1003.00))); + + // convert 16CZK using c: + // assertEquals("Result is 20 SKK"); + assertEquals(new BigDecimal("20.00"), c.convert(CZK, SKK, BigDecimal.valueOf(16.00))); + + // convert 500SKK to CZK using c: + // assertEquals("Result is 400 CZK"); + assertEquals(new BigDecimal("400.00"), c.convert(SKK, CZK, BigDecimal.valueOf(500.00))); + } + + public void testGetCurrencies() + { + Convertor c = merge( + Task1Test.createCZKtoUSD(), + Task1Test.createSKKtoCZK() + ); + Set currencies; + + currencies = c.getCurrencies(); + assertEquals(3, currencies.size()); + assertTrue(currencies.contains(Currency.getInstance("SKK"))); + assertTrue(currencies.contains(Currency.getInstance("CZK"))); + assertTrue(currencies.contains(Currency.getInstance("USD"))); + } + + public void testGetConverstionRate() + throws InvalidConversionException + { + Convertor c = merge( + Task1Test.createCZKtoUSD(), + Task1Test.createSKKtoCZK() + ); + + assertEquals(1.0, c.getConversionRate(USD, USD).doubleValue(), 0.0000000000000001); + assertEquals(17.0, c.getConversionRate(USD, CZK).doubleValue(), 0.0000000000000001); + assertEquals(21.25, c.getConversionRate(USD, SKK).doubleValue(), 0.0000000000000001); + + assertEquals(1.0 / 17.0, c.getConversionRate(CZK, USD).doubleValue(), 0.0000000000000001); + assertEquals(1.0, c.getConversionRate(CZK, CZK).doubleValue(), 0.0000000000000001); + assertEquals(1.25, c.getConversionRate(CZK, SKK).doubleValue(), 0.0000000000000001); + + assertEquals(0.04705882352941176, c.getConversionRate(SKK, USD).doubleValue(), 0.0000000000000001); + assertEquals(0.8, c.getConversionRate(SKK, CZK).doubleValue(), 0.0000000000000001); + assertEquals(1.0, c.getConversionRate(SKK, SKK).doubleValue(), 0.0000000000000001); + } +} diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution06/build.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution06/build.xml Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,69 @@ + + + + + + Builds, tests, and runs the project. + + + diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution06/nbproject/build-impl.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution06/nbproject/build-impl.xml Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,642 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set src.dir + Must set test.src.dir + Must set build.dir + Must set dist.dir + Must set build.classes.dir + Must set dist.javadoc.dir + Must set build.test.classes.dir + Must set build.test.results.dir + Must set build.classes.excludes + Must set dist.jar + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + + + + + + java -cp "${run.classpath.with.dist.jar}" ${main.class} + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + java -jar "${dist.jar.resolved}" + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set run.class + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set debug.class + + + + + Must set fix.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + Some tests failed; see details above. + + + + + + + + + Must select some files in the IDE or set test.includes + + + + Some tests failed; see details above. + + + + + Must select one file in the IDE or set test.class + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + + + + + + + + + + + diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution06/nbproject/genfiles.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution06/nbproject/genfiles.properties Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,8 @@ +build.xml.data.CRC32=2ab820eb +build.xml.script.CRC32=58a52595 +build.xml.stylesheet.CRC32=be360661 +# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. +# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. +nbproject/build-impl.xml.data.CRC32=ff801896 +nbproject/build-impl.xml.script.CRC32=a0996c47 +nbproject/build-impl.xml.stylesheet.CRC32=e55b27f5 diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution06/nbproject/project.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution06/nbproject/project.properties Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,68 @@ +application.title=currency +application.vendor=apidesign.org +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.tab-size=8 +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.text-limit-width=80 +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.usedProfile=default +build.classes.dir=${build.dir}/classes +build.classes.excludes=**/*.java,**/*.form +# This directory is removed when the project is cleaned: +build.dir=build +build.generated.dir=${build.dir}/generated +# Only compile against the classpath explicitly listed here: +build.sysclasspath=ignore +build.test.classes.dir=${build.dir}/test/classes +build.test.results.dir=${build.dir}/test/results +debug.classpath=\ + ${run.classpath} +debug.test.classpath=\ + ${run.test.classpath} +# This directory is removed when the project is cleaned: +dist.dir=dist +dist.jar=${dist.dir}/currency.jar +dist.javadoc.dir=${dist.dir}/javadoc +excludes= +file.reference.junit-4.4.jar=../../libs/junit-4.4.jar +file.reference.src-apifest08=.. +includes=** +jar.compress=false +javac.classpath= +# Space-separated list of extra javac options +javac.compilerargs= +javac.deprecation=false +javac.source=1.5 +javac.target=1.5 +javac.test.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir}:\ + ${file.reference.junit-4.4.jar} +javadoc.additionalparam= +javadoc.author=false +javadoc.encoding= +javadoc.noindex=false +javadoc.nonavbar=false +javadoc.notree=false +javadoc.private=false +javadoc.splitindex=true +javadoc.use=true +javadoc.version=false +javadoc.windowtitle= +jnlp.codebase.type=local +jnlp.codebase.url=file:/home/jarda/src/apifest08/currency/dist +jnlp.descriptor=application +jnlp.enabled=false +jnlp.offline-allowed=false +jnlp.signed=false +meta.inf.dir=${src.dir}/META-INF +platform.active=default_platform +run.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +# Space-separated list of JVM arguments used when running the project +# (you may also define separate properties like run-sys-prop.name=value instead of -Dname=value +# or test-sys-prop.name=value to set system properties for unit tests): +run.jvmargs= +run.test.classpath=\ + ${javac.test.classpath}:\ + ${build.test.classes.dir} +src.dir=src +test.src.dir=test diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution06/nbproject/project.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution06/nbproject/project.xml Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,16 @@ + + + org.netbeans.modules.java.j2seproject + + + Currency Convertor Solution 06 + 1.6.5 + + + + + + + + + diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution06/src/org/apidesign/apifest08/currency/Amount.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution06/src/org/apidesign/apifest08/currency/Amount.java Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,81 @@ +package org.apidesign.apifest08.currency; + +import static org.apidesign.apifest08.currency.Assert.notNull; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.Currency; + +/** + * An amount representation. Amount is represented as composition of a value and + * a currency. + */ +public final class Amount { + + private final BigDecimal value; + private final Currency currency; + private final int scale; + private final RoundingMode roundingMode; + + public static final RoundingMode DEFAULT_ROUNDING = RoundingMode.HALF_EVEN; + + public Amount(final BigDecimal value, final Currency currency) { + notNull(value, "value"); + notNull(currency, "currency"); + this.value = value; + this.currency = currency; + this.scale = currency.getDefaultFractionDigits(); + this.roundingMode = DEFAULT_ROUNDING; + } + + public Amount(final BigDecimal value, final Currency currency, final RoundingMode roundingMode) { + notNull(value, "value"); + notNull(currency, "currency"); + notNull(roundingMode, "roundingMode"); + + this.value = value; + this.currency = currency; + this.scale = currency.getDefaultFractionDigits(); + this.roundingMode = roundingMode; + } + + public Amount(final long value, final Currency currency) { + this(BigDecimal.valueOf(value), currency); + } + + public Amount(final String value, final Currency currency) { + this(new BigDecimal(value), currency); + } + + /** + * @return the value with scale of the associated currency and rounded by + * the rounding mode. + */ + public BigDecimal getValue() { + return value.setScale(scale, roundingMode); + } + + /** + * @return the raw (no explicit scale, no explicit rounding) value + */ + public BigDecimal getRawValue() { + return value; + } + + public Currency getCurrency() { + return currency; + } + + public int getScale() { + return scale; + } + + public RoundingMode getRoundingMode() { + return roundingMode; + } + + @Override + public String toString() { + return value + ",- " + currency.toString(); + } +} diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution06/src/org/apidesign/apifest08/currency/Assert.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution06/src/org/apidesign/apifest08/currency/Assert.java Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,11 @@ +package org.apidesign.apifest08.currency; + +public final class Assert { + static void notNull(Object value, String argumentName) { + if(value == null) { + throw new IllegalArgumentException("The argument '" + argumentName + "' connot not be null"); + } + } +} + + diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution06/src/org/apidesign/apifest08/currency/ConversionException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution06/src/org/apidesign/apifest08/currency/ConversionException.java Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,26 @@ +package org.apidesign.apifest08.currency; + +/** + * Indicates that a desired conversion cannot be performed. + */ +public class ConversionException extends CurrencyException { + + private static final long serialVersionUID = 1L; + + public ConversionException() { + super(); + } + + public ConversionException(String message, Throwable cause) { + super(message, cause); + } + + public ConversionException(String message) { + super(message); + } + + public ConversionException(Throwable cause) { + super(cause); + } + +} diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution06/src/org/apidesign/apifest08/currency/Convertor.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution06/src/org/apidesign/apifest08/currency/Convertor.java Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,124 @@ +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; + +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(rateValue, 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 BigDecimal rateValue; // a rate between the first currency and the second currency + public static final BigDecimal one = new BigDecimal(1); + + private ConvertorDelegate(BigDecimal rateValue, Currency currencyFirst, Currency currencySecond) { + this.rateValue = rateValue; + 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) { + retVal = rateValue; + } else { + //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)); + } + } +} diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution06/src/org/apidesign/apifest08/currency/CurrencyException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution06/src/org/apidesign/apifest08/currency/CurrencyException.java Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,25 @@ +package org.apidesign.apifest08.currency; + +/** + * Top level runtime exception for 'currency' API. + */ +public class CurrencyException extends RuntimeException{ + + private static final long serialVersionUID = 1L; + + public CurrencyException() { + super(); + } + + public CurrencyException(String message, Throwable cause) { + super(message, cause); + } + + public CurrencyException(String message) { + super(message); + } + + public CurrencyException(Throwable cause) { + super(cause); + } +} diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution06/src/org/apidesign/apifest08/currency/UnsupportedConversionException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution06/src/org/apidesign/apifest08/currency/UnsupportedConversionException.java Tue Oct 07 11:05:34 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 6a500cd1e467 -r 251d0ed461fb task3/solution06/test/org/apidesign/apifest08/test/Currencies.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution06/test/org/apidesign/apifest08/test/Currencies.java Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,9 @@ +package org.apidesign.apifest08.test; + +import java.util.Currency; + +public class Currencies { + public static final Currency CZK = Currency.getInstance("CZK"); + public static final Currency SKK = Currency.getInstance("SKK"); + public static final Currency USD = Currency.getInstance("USD"); +} diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution06/test/org/apidesign/apifest08/test/Task1Test.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution06/test/org/apidesign/apifest08/test/Task1Test.java Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,136 @@ +package org.apidesign.apifest08.test; + +import static org.apidesign.apifest08.test.Currencies.CZK; +import static org.apidesign.apifest08.test.Currencies.SKK; +import static org.apidesign.apifest08.test.Currencies.USD; + +import java.math.BigDecimal; + +import junit.framework.TestCase; + +import org.apidesign.apifest08.currency.Amount; +import org.apidesign.apifest08.currency.ConversionException; +import org.apidesign.apifest08.currency.Convertor; +import org.apidesign.apifest08.currency.UnsupportedConversionException; + +/** Finish the Convertor API, and then write bodies of methods inside + * of this class to match the given tasks. To fullfil your task, use the + * API define in the org.apidesign.apifest08.currency package. + * Do not you reflection, or other hacks as your code + * shall run without any runtime permissions. + */ +public class Task1Test extends TestCase { + public Task1Test(String testName) { + super(testName); + } + + @Override + protected void setUp() throws Exception { + } + + @Override + protected void tearDown() throws Exception { + } + + /** Create convertor that understands two currencies, CZK and + * USD. Make 1 USD == 17 CZK. + * + * Creation of the convertor shall not require subclassing of any class + * or interface on the client side. + * + * @return prepared convertor ready for converting USD to CZK and CZK to USD + */ + public static Convertor createCZKtoUSD() { + return new Convertor(new BigDecimal(17), USD, CZK); + } + + /** Create convertor that understands two currencies, CZK and + * SKK. Make 100 SKK == 80 CZK. + * + * Creation of the convertor shall not require subclassing of any class + * or interface on the client side. + * + * @return prepared convertor ready for converting SKK to CZK and CZK to SKK + */ + public static Convertor createSKKtoCZK() { + return new Convertor(new BigDecimal("0.8"), SKK, CZK); + } + + /** Use the convertor from createCZKtoUSD method and do few conversions + * with it. + */ + public void testCurrencyCZKUSD() throws Exception { + Convertor c = createCZKtoUSD(); + // convert $5 to CZK using c: + Amount result = c.convert(new BigDecimal(5), USD, CZK); + assertEquals("Result is 85 CZK", 85, result.getValue().intValue()); + + // convert $8 to CZK + result = c.convert(new BigDecimal(8), USD, CZK); + assertEquals("Result is 136 CZK", 136, result.getValue().intValue()); + + // convert 1003CZK to USD + result = c.convert(new BigDecimal(1003), CZK, USD); + assertEquals("Result is 59 USD", 59, result.getValue().intValue()); + } + + /** Use the convertor from createSKKtoCZK method and do few conversions + * with it. + */ + public void testCurrencySKKCZK() throws Exception { + Convertor c = createSKKtoCZK(); + // convert 16CZK using c: + Amount result = c.convert(new BigDecimal(16), CZK, SKK); + assertEquals("Result is 20 SKK", 20, result.getValue().intValue()); + + // convert 500SKK to CZK + result = c.convert(new BigDecimal(500), SKK, CZK); + assertEquals("Result is 400 CZK", 400, result.getValue().intValue()); + } + + + /** + * Verify that the CZK to USD convertor knows nothing about SKK. + */ + public void testCannotConvertToSKKwithCZKUSDConvertor() throws Exception { + Convertor c = createCZKtoUSD(); + // convert $5 to SKK, the API shall say this is not possible + try { + c.convert(new BigDecimal(5), USD, SKK); + fail("convert $5 to SKK, the API shall say this is not possible"); + } catch (ConversionException e) { + //expected + } + + // convert 500 SKK to CZK, the API shall say this is not possible + + try { + c.convert(new BigDecimal("500"), SKK, CZK); + fail("convert 500 SKK to CZK, the API shall say this is not possible"); + } catch (ConversionException e) { + //expected + } + } + + /** + * Verify that the CZK to SKK convertor knows nothing about USD. + */ + public void testCannotConvertToSKKwithCZKSKKConvertor() throws Exception { + Convertor c = createSKKtoCZK(); + // convert $5 to SKK, the API shall say this is not possible + try { + c.convert(new BigDecimal(5), USD, SKK); + fail("convert $5 to SKK, the API shall say this is not possible"); + } catch(ConversionException e) { + //expected + } + + try { + c.convert(new BigDecimal(500), CZK, USD); + fail("convert 500 CZK to USD, the API shall say this is not possible"); + } catch(ConversionException e) { + //expected + } + } +} + diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution06/test/org/apidesign/apifest08/test/Task2Test.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution06/test/org/apidesign/apifest08/test/Task2Test.java Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,117 @@ +package org.apidesign.apifest08.test; + +import static org.apidesign.apifest08.test.Currencies.CZK; +import static org.apidesign.apifest08.test.Currencies.USD; +import static org.apidesign.apifest08.test.Currencies.SKK; + +import java.math.BigDecimal; + +import junit.framework.TestCase; +import org.apidesign.apifest08.currency.Convertor; +import org.apidesign.apifest08.test.Task1Test; + +/** There are many currencies around the world and many banks manipulate + * with more than one or two at the same time. As banks are usually the + * best paying clients, which is true even in case of your Convertor API, + * it is reasonable to listen to their requests. + *

+ * The quest for today is to enhance your existing convertor API to hold + * information about many currencies and allow conversions between any of them. + * Also, as conversion rates for diferent currencies usually arise from various + * bank departments, there is another important need. There is a need to + * compose two convertors into one by merging all the information about + * currencies they know about. + */ +public class Task2Test extends TestCase { + public Task2Test(String testName) { + super(testName); + } + + @Override + protected void setUp() throws Exception { + } + + @Override + protected void tearDown() throws Exception { + } + + // As in Task1Test, keep in mind, that there are three parts + // of the whole system: + // 1. there is someone who knows the current exchange rate + // 2. there is someone who wants to do the conversion + // 3. there is the API between 1. and 2. which allows them to communicate + // + // Please backward compatibly enhance your existing API to support following + // usecases: + // + + /** Create convertor that understands two currencies, CZK and + * SKK. Make 100 SKK == 75 CZK. This is method for the group of users that + * knows the exchange rate, and needs to use the API to create objects + * with the exchange rate. Anyone shall be ready to call this method without + * any other method being called previously. The API itself shall know + * nothing about any rates, before this method is called. + */ + public static Convertor createTripleConvertor() { + // Rates: 1USD = 15CZK + // Rates: 1USD = 20SKK + // Rates: 75CZK = 100SKK + Convertor usdCzk = new Convertor(new BigDecimal(15), USD, CZK); + Convertor usdSkk = new Convertor(new BigDecimal(20), USD, SKK); + Convertor skkCzk = new Convertor(new BigDecimal("0.75"), SKK, CZK); + return new Convertor(new Convertor[]{usdCzk, usdSkk, skkCzk}); + } + + /** Define convertor that understands three currencies. Use it. + */ + public void testConvertorForUSDandCZKandSKK() throws Exception { + Convertor c = createTripleConvertor(); + + // convert $5 to CZK using c: + assertEquals("Result is 75 CZK", 75 ,c.convert(new BigDecimal(5), USD, CZK).getValue().intValue()); + + // convert $5 to SKK using c: + assertEquals("Result is 100 SKK", 100, c.convert(new BigDecimal(5), USD, SKK).getValue().intValue()); + + // convert 200SKK to CZK using c: + assertEquals("Result is 150 CZK", 150, c.convert(new BigDecimal(200), SKK, CZK).getValue().intValue()); + + // convert 200SKK to USK using c: + assertEquals("Result is 10 USD", 10, c.convert(new BigDecimal(200), SKK, USD).getValue().intValue()); + } + + /** Merge all currency rates of convertor 1 with convertor 2. + * Implement this using your API, preferably this method just delegates + * into some API method which does the actual work, without requiring + * API clients to code anything complex. + */ + public static Convertor merge(Convertor one, Convertor two) { + return new Convertor(new Convertor[]{one, two}); + } + + /** Join the convertors from previous task, Task1Test and show that it + * can be used to do reasonable conversions. + */ + public void testConvertorComposition() throws Exception { + Convertor c = merge( + Task1Test.createCZKtoUSD(), + Task1Test.createSKKtoCZK() + ); + + // convert $5 to CZK using c: + assertEquals("Result is 85 CZK", 85, c.convert(new BigDecimal(5), USD, CZK).getValue().intValue()); + + // convert $8 to CZK using c: + assertEquals("Result is 136 CZK", 136, c.convert(new BigDecimal(8), USD, CZK).getValue().intValue()); + + // convert 1003CZK to USD using c: + assertEquals("Result is 59 USD", 59, c.convert(new BigDecimal(1003), CZK, USD).getValue().intValue()); + + // convert 16CZK using c: + assertEquals("Result is 20 SKK", 20, c.convert(new BigDecimal(16), CZK, SKK).getValue().intValue()); + + // convert 500SKK to CZK using c: + assertEquals("Result is 400 CZK", 400, c.convert(new BigDecimal(500), SKK, CZK).getValue().intValue()); + + } +} diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution07/build.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution07/build.xml Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,69 @@ + + + + + + Builds, tests, and runs the project. + + + diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution07/nbproject/build-impl.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution07/nbproject/build-impl.xml Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,642 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set src.dir + Must set test.src.dir + Must set build.dir + Must set dist.dir + Must set build.classes.dir + Must set dist.javadoc.dir + Must set build.test.classes.dir + Must set build.test.results.dir + Must set build.classes.excludes + Must set dist.jar + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + + + + + + java -cp "${run.classpath.with.dist.jar}" ${main.class} + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + java -jar "${dist.jar.resolved}" + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set run.class + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set debug.class + + + + + Must set fix.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + Some tests failed; see details above. + + + + + + + + + Must select some files in the IDE or set test.includes + + + + Some tests failed; see details above. + + + + + Must select one file in the IDE or set test.class + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + + + + + + + + + + + diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution07/nbproject/genfiles.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution07/nbproject/genfiles.properties Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,8 @@ +build.xml.data.CRC32=2ab820eb +build.xml.script.CRC32=58a52595 +build.xml.stylesheet.CRC32=be360661 +# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. +# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. +nbproject/build-impl.xml.data.CRC32=979fc7ba +nbproject/build-impl.xml.script.CRC32=92452d37 +nbproject/build-impl.xml.stylesheet.CRC32=e55b27f5 diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution07/nbproject/project.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution07/nbproject/project.properties Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,68 @@ +application.title=currency +application.vendor=apidesign.org +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.tab-size=8 +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.text-limit-width=80 +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.usedProfile=default +build.classes.dir=${build.dir}/classes +build.classes.excludes=**/*.java,**/*.form +# This directory is removed when the project is cleaned: +build.dir=build +build.generated.dir=${build.dir}/generated +# Only compile against the classpath explicitly listed here: +build.sysclasspath=ignore +build.test.classes.dir=${build.dir}/test/classes +build.test.results.dir=${build.dir}/test/results +debug.classpath=\ + ${run.classpath} +debug.test.classpath=\ + ${run.test.classpath} +# This directory is removed when the project is cleaned: +dist.dir=dist +dist.jar=${dist.dir}/currency.jar +dist.javadoc.dir=${dist.dir}/javadoc +excludes= +file.reference.junit-4.4.jar=../../libs/junit-4.4.jar +file.reference.src-apifest08=.. +includes=** +jar.compress=false +javac.classpath= +# Space-separated list of extra javac options +javac.compilerargs= +javac.deprecation=false +javac.source=1.5 +javac.target=1.5 +javac.test.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir}:\ + ${file.reference.junit-4.4.jar} +javadoc.additionalparam= +javadoc.author=false +javadoc.encoding= +javadoc.noindex=false +javadoc.nonavbar=false +javadoc.notree=false +javadoc.private=false +javadoc.splitindex=true +javadoc.use=true +javadoc.version=false +javadoc.windowtitle= +jnlp.codebase.type=local +jnlp.codebase.url=file:/home/jarda/src/apifest08/currency/dist +jnlp.descriptor=application +jnlp.enabled=false +jnlp.offline-allowed=false +jnlp.signed=false +meta.inf.dir=${src.dir}/META-INF +platform.active=default_platform +run.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +# Space-separated list of JVM arguments used when running the project +# (you may also define separate properties like run-sys-prop.name=value instead of -Dname=value +# or test-sys-prop.name=value to set system properties for unit tests): +run.jvmargs= +run.test.classpath=\ + ${javac.test.classpath}:\ + ${build.test.classes.dir} +src.dir=src +test.src.dir=test diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution07/nbproject/project.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution07/nbproject/project.xml Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,16 @@ + + + org.netbeans.modules.java.j2seproject + + + Currency Convertor Solution 07 + 1.6.5 + + + + + + + + + diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution07/src/org/apidesign/apifest08/currency/ConversionRate.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution07/src/org/apidesign/apifest08/currency/ConversionRate.java Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,91 @@ +package org.apidesign.apifest08.currency; + +import java.math.BigDecimal; +import java.math.RoundingMode; + +/** + * A rate of conversion from one currency to another. + * @author jdvorak + */ +public class ConversionRate { + + private final MonetaryAmount srcUnitAmount; + private final MonetaryAmount tgtUnitAmount; + private final int tgtScale; + private final RoundingMode roundingMode; + + /** + * A new conversion rate that gives tgtUnitAmount per every srcUnitAmount. + * @param srcUnitAmount the amount of source currency + * @param tgtUnitAmount the corresponding amount of target currency + * @param tgtScale the scale of the target amounts + * @param roundingMode the rounding mode to use when producing the target amounts + */ + public ConversionRate( final MonetaryAmount srcUnitAmount, final MonetaryAmount tgtUnitAmount, final int targetScale, final RoundingMode roundingMode ) { + this.srcUnitAmount = srcUnitAmount; + this.tgtUnitAmount = tgtUnitAmount; + this.tgtScale = targetScale; + this.roundingMode = roundingMode; + } + + /** + * A new conversion rate that gives tgtUnitAmount per every srcUnitAmount, default number of fraction digits and the given rounding mode. + * @param srcUnitAmount the amount of source currency + * @param tgtUnitAmount the corresponding amount of target currency + * @param roundingMode the rounding mode to use + */ + public ConversionRate( final MonetaryAmount srcUnitAmount, final MonetaryAmount tgtUnitAmount, final RoundingMode roundingMode ) { + this( srcUnitAmount, tgtUnitAmount, tgtUnitAmount.getCurrency().getDefaultFractionDigits(), roundingMode ); + } + + /** + * A new conversion rate that gives tgtUnitAmount per every srcUnitAmount, default number of fraction digits and {@link RoundingMode#HALF_EVEN}. + * @param srcUnitAmount the amount of source currency + * @param tgtUnitAmount the corresponding amount of target currency + */ + public ConversionRate( final MonetaryAmount srcUnitAmount, final MonetaryAmount tgtUnitAmount ) { + this( srcUnitAmount, tgtUnitAmount, RoundingMode.HALF_EVEN ); + } + + public RoundingMode getRoundingMode() { + return roundingMode; + } + + public MonetaryAmount getSrcUnitAmount() { + return srcUnitAmount; + } + + public int getTgtScale() { + return tgtScale; + } + + public MonetaryAmount getTgtUnitAmount() { + return tgtUnitAmount; + } + + /** + * Multiplies the given amount with the given rate. + * @param srcAmount + * @return + */ + public BigDecimal convert( final BigDecimal srcAmount ) { + return srcAmount + .multiply( tgtUnitAmount.getAmount() ) + .divide( srcUnitAmount.getAmount(), tgtScale, roundingMode ); + } + + /** + * Creates a monetary amount that corresponds to the given source amount multiplied by the rate. + * @param srcAmount the source amount + * @return the monetary amount in the target currency + * @throws IllegalArgumentException if the currency of srcAmount is not equal to the source currency of this rate + */ + public MonetaryAmount convert( final MonetaryAmount srcAmount ) { + if ( srcUnitAmount.getCurrency().equals( srcAmount.getCurrency() ) ) { + return new MonetaryAmount( convert( srcAmount.getAmount() ), tgtUnitAmount.getCurrency() ); + } else { + throw new IllegalArgumentException( "This rate converts from " + srcUnitAmount.getCurrency() + ", but a conversion from " + srcAmount.getCurrency() + " is attempted" ); + } + } + +} diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution07/src/org/apidesign/apifest08/currency/Convertor.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution07/src/org/apidesign/apifest08/currency/Convertor.java Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,109 @@ +package org.apidesign.apifest08.currency; + +import java.util.Currency; + +/** This is the skeleton class for your API. You need to make it public, so + * it is accessible to your client code (currently in Task1Test.java) file. + *

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

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

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

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

+ * The quest for today is to enhance your existing convertor API to hold + * information about many currencies and allow conversions between any of them. + * Also, as conversion rates for diferent currencies usually arise from various + * bank departments, there is another important need. There is a need to + * compose two convertors into one by merging all the information about + * currencies they know about. + */ +public class Task2Test extends TestCase { + public Task2Test(String testName) { + super(testName); + } + + @Override + protected void setUp() throws Exception { + } + + @Override + protected void tearDown() throws Exception { + } + + protected static final Currency CZK = Currency.getInstance( "CZK" ); + protected static final Currency SKK = Currency.getInstance( "SKK" ); + protected static final Currency USD = Currency.getInstance( "USD" ); + + // As in Task1Test, keep in mind, that there are three parts + // of the whole system: + // 1. there is someone who knows the current exchange rate + // 2. there is someone who wants to do the conversion + // 3. there is the API between 1. and 2. which allows them to communicate + // + // Please backward compatibly enhance your existing API to support following + // usecases: + // + + /** Create convertor that understands two currencies, CZK and + * SKK. Make 100 SKK == 75 CZK. This is method for the group of users that + * knows the exchange rate, and needs to use the API to create objects + * with the exchange rate. Anyone shall be ready to call this method without + * any other method being called previously. The API itself shall know + * nothing about any rates, before this method is called. + */ + public static Convertor createTripleConvertor() { + // Rates: 1USD = 15CZK + // Rates: 1USD = 20SKK + // Rates: 75CZK = 100SKK + final TableConvertor convertor = new TableConvertor(); + final MonetaryAmount amountInUSD = new MonetaryAmount( 1, USD ); + final MonetaryAmount amountInCZK = new MonetaryAmount( 15, CZK ); + final MonetaryAmount amountInSKK = new MonetaryAmount( 20, SKK ); + convertor.putIntoTable( new ConversionRate( amountInCZK, amountInUSD ) ); + convertor.putIntoTable( new ConversionRate( amountInUSD, amountInCZK ) ); + convertor.putIntoTable( new ConversionRate( amountInSKK, amountInUSD ) ); + convertor.putIntoTable( new ConversionRate( amountInUSD, amountInSKK ) ); + convertor.putIntoTable( new ConversionRate( amountInSKK, amountInCZK ) ); + convertor.putIntoTable( new ConversionRate( amountInCZK, amountInSKK ) ); + return new ContractImposingDelegatingConvertor( convertor ).test(); + } + + /** Define convertor that understands three currencies. Use it. + */ + public void testConvertorForUSDandCZKandSKK() throws Exception { + final Convertor c = createTripleConvertor(); + + // convert $5 to CZK using c: + final Convertor.ConversionResult r1 = c.convert( new Convertor.ConversionRequest( new MonetaryAmount( 5, USD ), CZK ) ); + final MonetaryAmount a1 = r1.getNetAmount(); + // assertEquals("Result is 75 CZK"); + assertNotNull( a1 ); + assertEquals( 75.0, a1.getAmount().doubleValue() ); + assertEquals( CZK, a1.getCurrency() ); + + // convert $5 to SKK using c: + final Convertor.ConversionResult r2 = c.convert( new Convertor.ConversionRequest( new MonetaryAmount( 5, USD ), SKK ) ); + final MonetaryAmount a2 = r2.getNetAmount(); + // assertEquals("Result is 100 SKK"); + assertNotNull( a2 ); + assertEquals( 100.0, a2.getAmount().doubleValue() ); + assertEquals( SKK, a2.getCurrency() ); + + // convert 200SKK to CZK using c: + final Convertor.ConversionResult r3 = c.convert( new Convertor.ConversionRequest( new MonetaryAmount( 200, SKK ), CZK ) ); + final MonetaryAmount a3 = r3.getNetAmount(); + // assertEquals("Result is 150 CZK"); + assertNotNull( a3 ); + assertEquals( 150.0, a3.getAmount().doubleValue() ); + assertEquals( CZK, a3.getCurrency() ); + + // convert 200SKK to USK using c: + final Convertor.ConversionResult r4 = c.convert( new Convertor.ConversionRequest( new MonetaryAmount( 200, SKK ), USD ) ); + final MonetaryAmount a4 = r4.getNetAmount(); + // assertEquals("Result is 10 USD"); + assertNotNull( a4 ); + assertEquals( 10.0, a4.getAmount().doubleValue() ); + assertEquals( USD, a4.getCurrency() ); + } + + /** Merge all currency rates of convertor 1 with convertor 2. + * Implement this using your API, preferably this method just delegates + * into some API method which does the actual work, without requiring + * API clients to code anything complex. + */ + public static Convertor merge( final Convertor one, final Convertor two ) { + return new Convertor() { + + public ConversionResult convert( ConversionRequest req ) throws IllegalRequestSubtypeException { + final ConversionResult res1 = one.convert( req ); + final ConversionResult res2 = two.convert( req ); + if ( res1.getNetAmount() != null ) { + if ( res2.getNetAmount() != null ) { + // TODO check if they arrive at the same thing + return res1; + } else { + return res1; + } + } else { + if ( res2.getNetAmount() != null ) { + return res2; + } else { + // neither converts + return new ConversionResult( null ); + } + } + } + + }; + } + + /** Join the convertors from previous task, Task1Test and show that it + * can be used to do reasonable conversions. + */ + public void testConvertorComposition() throws Exception { + final Convertor c = merge( + Task1Test.createCZKtoUSD(), + Task1Test.createSKKtoCZK() + ); + + // convert $5 to CZK using c: + final Convertor.ConversionResult r1 = c.convert( new Convertor.ConversionRequest( new MonetaryAmount( 5, USD ), CZK ) ); + final MonetaryAmount a1 = r1.getNetAmount(); + // assertEquals("Result is 85 CZK"); + assertNotNull( a1 ); + assertEquals( 85.0, a1.getAmount().doubleValue() ); + assertEquals( CZK, a1.getCurrency() ); + + // convert $8 to CZK + final Convertor.ConversionResult r2 = c.convert( new Convertor.ConversionRequest( new MonetaryAmount( 8, USD ), CZK ) ); + final MonetaryAmount a2 = r2.getNetAmount(); + // assertEquals("Result is 136 CZK"); + assertNotNull( a2 ); + assertEquals( 136.0, a2.getAmount().doubleValue() ); + assertEquals( CZK, a2.getCurrency() ); + + // convert 1003CZK to USD + final Convertor.ConversionResult r3 = c.convert( new Convertor.ConversionRequest( new MonetaryAmount( 1003, CZK ), USD ) ); + final MonetaryAmount a3 = r3.getNetAmount(); + // assertEquals("Result is 59 USD"); + assertNotNull( a3 ); + assertEquals( 59.0, a3.getAmount().doubleValue() ); + assertEquals( USD, a3.getCurrency() ); + + // convert 16CZK using c: + final Convertor.ConversionResult r4 = c.convert( new Convertor.ConversionRequest( new MonetaryAmount( 16, CZK ), SKK ) ); + final MonetaryAmount a4 = r4.getNetAmount(); + // assertEquals("Result is 20 SKK"); + assertNotNull( a4 ); + assertEquals( 20.0, a4.getAmount().doubleValue() ); + assertEquals( SKK, a4.getCurrency() ); + + // convert 500SKK to CZK using c: + final Convertor.ConversionResult r5 = c.convert( new Convertor.ConversionRequest( new MonetaryAmount( 500, SKK ), CZK ) ); + final MonetaryAmount a5 = r5.getNetAmount(); + // assertEquals("Result is 400 CZK"); + assertNotNull( a5 ); + assertEquals( 400.0, a5.getAmount().doubleValue() ); + assertEquals( CZK, a5.getCurrency() ); + } +} diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution11/build.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution11/build.xml Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,69 @@ + + + + + + Builds, tests, and runs the project. + + + diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution11/nbproject/build-impl.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution11/nbproject/build-impl.xml Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,629 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set src.dir + Must set test.src.dir + Must set build.dir + Must set dist.dir + Must set build.classes.dir + Must set dist.javadoc.dir + Must set build.test.classes.dir + Must set build.test.results.dir + Must set build.classes.excludes + Must set dist.jar + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + + + + + + java -cp "${run.classpath.with.dist.jar}" ${main.class} + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + java -jar "${dist.jar.resolved}" + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set run.class + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set debug.class + + + + + Must set fix.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + Some tests failed; see details above. + + + + + + + + + Must select some files in the IDE or set test.includes + + + + Some tests failed; see details above. + + + + + Must select one file in the IDE or set test.class + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + + + + + + + + + + + diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution11/nbproject/genfiles.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution11/nbproject/genfiles.properties Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,8 @@ +build.xml.data.CRC32=2ab820eb +build.xml.script.CRC32=58a52595 +build.xml.stylesheet.CRC32=be360661 +# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. +# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. +nbproject/build-impl.xml.data.CRC32=0e1e702f +nbproject/build-impl.xml.script.CRC32=c899f2cf +nbproject/build-impl.xml.stylesheet.CRC32=487672f9 diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution11/nbproject/project.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution11/nbproject/project.properties Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,68 @@ +application.title=currency +application.vendor=apidesign.org +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.tab-size=8 +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.text-limit-width=80 +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.usedProfile=default +build.classes.dir=${build.dir}/classes +build.classes.excludes=**/*.java,**/*.form +# This directory is removed when the project is cleaned: +build.dir=build +build.generated.dir=${build.dir}/generated +# Only compile against the classpath explicitly listed here: +build.sysclasspath=ignore +build.test.classes.dir=${build.dir}/test/classes +build.test.results.dir=${build.dir}/test/results +debug.classpath=\ + ${run.classpath} +debug.test.classpath=\ + ${run.test.classpath} +# This directory is removed when the project is cleaned: +dist.dir=dist +dist.jar=${dist.dir}/currency.jar +dist.javadoc.dir=${dist.dir}/javadoc +excludes= +file.reference.junit-4.4.jar=../../libs/junit-4.4.jar +file.reference.src-apifest08=.. +includes=** +jar.compress=false +javac.classpath= +# Space-separated list of extra javac options +javac.compilerargs=-Xlint:unchecked +javac.deprecation=false +javac.source=1.5 +javac.target=1.5 +javac.test.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir}:\ + ${file.reference.junit-4.4.jar} +javadoc.additionalparam= +javadoc.author=false +javadoc.encoding= +javadoc.noindex=false +javadoc.nonavbar=false +javadoc.notree=false +javadoc.private=false +javadoc.splitindex=true +javadoc.use=true +javadoc.version=false +javadoc.windowtitle= +jnlp.codebase.type=local +jnlp.codebase.url=file:/home/jarda/src/apifest08/currency/dist +jnlp.descriptor=application +jnlp.enabled=false +jnlp.offline-allowed=false +jnlp.signed=false +meta.inf.dir=${src.dir}/META-INF +platform.active=default_platform +run.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +# Space-separated list of JVM arguments used when running the project +# (you may also define separate properties like run-sys-prop.name=value instead of -Dname=value +# or test-sys-prop.name=value to set system properties for unit tests): +run.jvmargs= +run.test.classpath=\ + ${javac.test.classpath}:\ + ${build.test.classes.dir} +src.dir=src +test.src.dir=test diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution11/nbproject/project.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution11/nbproject/project.xml Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,16 @@ + + + org.netbeans.modules.java.j2seproject + + + Currency Convertor Solution 11 + 1.6.5 + + + + + + + + + diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution11/src/org/apidesign/apifest08/currency/Computer.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution11/src/org/apidesign/apifest08/currency/Computer.java Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,65 @@ +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 { + + ComputerResponse compute(ComputerRequest request); + + /** + * + * @param + */ + 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 6a500cd1e467 -r 251d0ed461fb task3/solution11/src/org/apidesign/apifest08/currency/Convertor.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution11/src/org/apidesign/apifest08/currency/Convertor.java Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,228 @@ +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. + * + * @author ked + */ +public final class Convertor { + + Computer computer; + List> exchangeRates = new ArrayList>(); + + Convertor( + Computer computer, + Collection> exchangeRates) { + this.computer = computer; + + for (ExchangeRateValue exchangeRate : exchangeRates) { + if (findExchangeRate( + this.exchangeRates, + exchangeRate.getCurrencyA().getIdentifier(), + exchangeRate.getCurrencyB().getIdentifier()) != null) { + throw new IllegalArgumentException("Duplicate exchange rate!"); + } + this.exchangeRates.add(exchangeRate); + } + } + + private ExchangeRateValue findExchangeRate( + Collection> exchangeRates, + 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; + } + } + return null; + } + + /** + * 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(exchangeRates, 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 = computer.compute(computerRequest); + return CurrencyValue.getCurrencyValue( + computerResponse.getResult(), + targetCurrencyRef); + } + + // --- + // MERGING + // --- + static Convertor mergeConvertors( + Computer computer, + Collection> convertors) { + Set> exchangeRatesSet = new HashSet>(); + for (Convertor convertor : convertors) { + exchangeRatesSet.addAll(convertor.exchangeRates); + } + return getConvertor(computer, exchangeRatesSet); + } + + 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) { + return new Convertor(computer, exchangeRates); + } + + static Convertor getConvertor( + Computer computer, ExchangeRateValue exchangeRate) { + Collection> exchangeRates = + new ArrayList>(); + exchangeRates.add(exchangeRate); + return getConvertor(computer, exchangeRates); + } + + public static Convertor getConvertorDoubleString( + Collection> exchangeRates) { + return getConvertor(DoubleComputer, exchangeRates); + } + + public static Convertor getConvertorDoubleString( + ExchangeRateValue exchangeRate) { + return getConvertor(DoubleComputer, exchangeRate); + } + + public static Convertor getConvertorIntegerString( + Collection> exchangeRates) { + return getConvertor(IntegerComputer, exchangeRates); + } + + public static Convertor getConvertorIntegerString( + ExchangeRateValue exchangeRate) { + return getConvertor(IntegerComputer, exchangeRate); + } + + // --- + // 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 ComputerResponse compute(ComputerRequest request) { + ComputerResponse response = new ComputerResponse(); + response.setResult(request.getInput() * request.getOutputCurrencyRatio() / request.getInputCurrencyRatio()); + return response; + } + }; + static final Computer IntegerComputer = new Computer() { + + public ComputerResponse compute(ComputerRequest request) { + ComputerResponse response = new ComputerResponse(); + response.setResult(request.getInput() * request.getOutputCurrencyRatio() / request.getInputCurrencyRatio()); + return response; + } + }; +} diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution11/src/org/apidesign/apifest08/currency/CurrencyValue.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution11/src/org/apidesign/apifest08/currency/CurrencyValue.java Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,72 @@ +package org.apidesign.apifest08.currency; + +import java.io.Serializable; + +/** + * Value class, holding an amount of the currency & an identifier of the currency. + * Designed to be an immutable. + * + * Because of a vague definition of types of the both fields, + * the class has generic types, used as types of the fields. + * These types should be immutable classes, too. + * + * @author ked + */ +public final class CurrencyValue implements Serializable { + + private final AmountType amount; + private final IdentifierType identifier; + + private CurrencyValue(AmountType amount, IdentifierType identifier) { + this.amount = amount; + this.identifier = identifier; + } + + public AmountType getAmount() { + return amount; + } + + public IdentifierType getIdentifier() { + return identifier; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final CurrencyValue other = (CurrencyValue) obj; + if (this.amount != other.amount && (this.amount == null || !this.amount.equals(other.amount))) { + return false; + } + if (this.identifier != other.identifier && (this.identifier == null || !this.identifier.equals(other.identifier))) { + return false; + } + return true; + } + + @Override + public int hashCode() { + int hash = 7; + hash = 97 * hash + (this.amount != null ? this.amount.hashCode() : 0); + hash = 97 * hash + (this.identifier != null ? this.identifier.hashCode() : 0); + return hash; + } + + /** + * Creates new instance. + * Generic types of the new instance are derived from types of the parameters. + * + * @param type of the currency amount + * @param type of the currency identifier + * @param amount currency amount + * @param identifier currency identifier + * @return new instance + */ + public static CurrencyValue getCurrencyValue(AmountType amount, IdentifierType identifier) { + return new CurrencyValue(amount, identifier); + } +} diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution11/src/org/apidesign/apifest08/currency/ExchangeRateValue.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution11/src/org/apidesign/apifest08/currency/ExchangeRateValue.java Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,78 @@ +package org.apidesign.apifest08.currency; + +import java.io.Serializable; + +/** + * Value class, holding an exchange rate between two currencies. + * Designed to be an immutable. + * + * @author ked + */ +public final class ExchangeRateValue implements Serializable { + + private final CurrencyValue currencyA; + private final CurrencyValue currencyB; + + private ExchangeRateValue( + CurrencyValue currencyA, + CurrencyValue currencyB) { + if (currencyA.getIdentifier() == null || + currencyB.getIdentifier() == null || + currencyA.getIdentifier().equals(currencyB)) { + throw new IllegalArgumentException("Inappropriate exchange rates' identifiers!"); + } + + this.currencyA = currencyA; + this.currencyB = currencyB; + } + + public CurrencyValue getCurrencyA() { + return currencyA; + } + + public CurrencyValue getCurrencyB() { + return currencyB; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final ExchangeRateValue other = (ExchangeRateValue) obj; + if (this.currencyA != other.currencyA && (this.currencyA == null || !this.currencyA.equals(other.currencyA))) { + return false; + } + if (this.currencyB != other.currencyB && (this.currencyB == null || !this.currencyB.equals(other.currencyB))) { + return false; + } + return true; + } + + @Override + public int hashCode() { + int hash = 3; + hash = 71 * hash + (this.currencyA != null ? this.currencyA.hashCode() : 0); + hash = 71 * hash + (this.currencyB != null ? this.currencyB.hashCode() : 0); + return hash; + } + + /** + * Creates new instance. + * Generic types of the new instance are derived from types of the parameters. + * + * @param type of the currency amount + * @param type of the currency identifier + * @param currencyA one currency of the exchange rate + * @param currencyB another currency of the exchange rate + * @return new instance + */ + public static ExchangeRateValue getExchangeRate( + CurrencyValue currencyA, + CurrencyValue currencyB) { + return new ExchangeRateValue(currencyA, currencyB); + } +} diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution11/test/org/apidesign/apifest08/test/Task1Test.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution11/test/org/apidesign/apifest08/test/Task1Test.java Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,161 @@ +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.getConvertorIntegerString( + CurrencyValue.getCurrencyValue(1, "USD"), + CurrencyValue.getCurrencyValue(17, "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.getConvertorIntegerString( + CurrencyValue.getCurrencyValue(100, "SKK"), + CurrencyValue.getCurrencyValue(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(); + + CurrencyValue result; + + // convert $5 to CZK using c: + // assertEquals("Result is 85 CZK"); + result = c.convert("CZK", CurrencyValue.getCurrencyValue(5, "USD")); + assertEquals(CurrencyValue.getCurrencyValue(85, "CZK"), result); + + // convert $8 to CZK + // assertEquals("Result is 136 CZK"); + result = c.convert("CZK", CurrencyValue.getCurrencyValue(8, "USD")); + assertEquals(CurrencyValue.getCurrencyValue(136, "CZK"), result); + + // convert 1003CZK to USD + // assertEquals("Result is 59 USD"); + result = c.convert("USD", CurrencyValue.getCurrencyValue(1003, "CZK")); + assertEquals(CurrencyValue.getCurrencyValue(59, "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(16, "CZK")); + assertEquals(CurrencyValue.getCurrencyValue(20, "SKK"), result); + + // convert 500SKK to CZK + // assertEquals("Result is 400 CZK"); + result = c.convert("CZK", CurrencyValue.getCurrencyValue(500, "SKK")); + assertEquals(CurrencyValue.getCurrencyValue(400, "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(16, "CZK")); + assertTrue("Should not convert", false); + } catch (Exception e) { + assertTrue(true); + } + try { + // convert 500 SKK to CZK, the API shall say this is not possible + c.convert("CZK", CurrencyValue.getCurrencyValue(500, "SKK")); + assertTrue("Should not convert", false); + } catch (Exception e) { + assertTrue(true); + } + + } + + /** 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(5, "USD")); + assertTrue("Should not convert", false); + } catch (Exception e) { + assertTrue(true); + } + try { + // convert 500 CZK to USD, the API shall say this is not possible + c.convert("USD", CurrencyValue.getCurrencyValue(500, "CZK")); + assertTrue("Should not convert", false); + } catch (Exception e) { + assertTrue(true); + } + } +} diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution11/test/org/apidesign/apifest08/test/Task2Test.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution11/test/org/apidesign/apifest08/test/Task2Test.java Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,140 @@ +package org.apidesign.apifest08.test; + +import java.util.ArrayList; +import java.util.Collection; +import junit.framework.TestCase; +import org.apidesign.apifest08.currency.Convertor; +import org.apidesign.apifest08.currency.CurrencyValue; +import org.apidesign.apifest08.currency.ExchangeRateValue; + +/** There are many currencies around the world and many banks manipulate + * with more than one or two at the same time. As banks are usually the + * best paying clients, which is true even in case of your Convertor API, + * it is reasonable to listen to their requests. + *

+ * The quest for today is to enhance your existing convertor API to hold + * information about many currencies and allow conversions between any of them. + * Also, as conversion rates for diferent currencies usually arise from various + * bank departments, there is another important need. There is a need to + * compose two convertors into one by merging all the information about + * currencies they know about. + */ +public class Task2Test extends TestCase { + + public Task2Test(String testName) { + super(testName); + } + + @Override + protected void setUp() throws Exception { + } + + @Override + protected void tearDown() throws Exception { + } + + // As in Task1Test, keep in mind, that there are three parts + // of the whole system: + // 1. there is someone who knows the current exchange rate + // 2. there is someone who wants to do the conversion + // 3. there is the API between 1. and 2. which allows them to communicate + // + // Please backward compatibly enhance your existing API to support following + // usecases: + // + /** Create convertor that understands two currencies, CZK and + * SKK. Make 100 SKK == 75 CZK. This is method for the group of users that + * knows the exchange rate, and needs to use the API to create objects + * with the exchange rate. Anyone shall be ready to call this method without + * any other method being called previously. The API itself shall know + * nothing about any rates, before this method is called. + */ + public static Convertor createTripleConvertor() { + // Rates: 1USD = 15CZK + // Rates: 1USD = 20SKK + // Rates: 75CZK = 100SKK + Collection> exchangeRates = + new ArrayList>(); + exchangeRates.add(ExchangeRateValue.getExchangeRate( + CurrencyValue.getCurrencyValue(1, "USD"), + CurrencyValue.getCurrencyValue(15, "CZK"))); + exchangeRates.add(ExchangeRateValue.getExchangeRate( + CurrencyValue.getCurrencyValue(1, "USD"), + CurrencyValue.getCurrencyValue(20, "SKK"))); + exchangeRates.add(ExchangeRateValue.getExchangeRate( + CurrencyValue.getCurrencyValue(75, "CZK"), + CurrencyValue.getCurrencyValue(100, "SKK"))); + return Convertor.getConvertorIntegerString(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(5, "USD")); + assertEquals(CurrencyValue.getCurrencyValue(75, "CZK"), result); + + // convert $5 to SKK using c: + // assertEquals("Result is 100 SKK"); + result = c.convert("SKK", CurrencyValue.getCurrencyValue(5, "USD")); + assertEquals(CurrencyValue.getCurrencyValue(100, "SKK"), result); + + // convert 200SKK to CZK using c: + // assertEquals("Result is 150 CZK"); + result = c.convert("CZK", CurrencyValue.getCurrencyValue(200, "SKK")); + assertEquals(CurrencyValue.getCurrencyValue(150, "CZK"), result); + + // convert 200SKK to USK using c: + // assertEquals("Result is 10 USD"); + result = c.convert("USD", CurrencyValue.getCurrencyValue(200, "SKK")); + assertEquals(CurrencyValue.getCurrencyValue(10, "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.mergeConvertorsIntegerString(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(5, "USD")); + assertEquals(CurrencyValue.getCurrencyValue(85, "CZK"), result); + + // convert $8 to CZK using c: + // assertEquals("Result is 136 CZK"); + result = c.convert("CZK", CurrencyValue.getCurrencyValue(8, "USD")); + assertEquals(CurrencyValue.getCurrencyValue(136, "CZK"), result); + + // convert 1003CZK to USD using c: + // assertEquals("Result is 59 USD"); + result = c.convert("USD", CurrencyValue.getCurrencyValue(1003, "CZK")); + assertEquals(CurrencyValue.getCurrencyValue(59, "USD"), result); + + // convert 16CZK using c: + // assertEquals("Result is 20 SKK"); + result = c.convert("SKK", CurrencyValue.getCurrencyValue(16, "CZK")); + assertEquals(CurrencyValue.getCurrencyValue(20, "SKK"), result); + + // convert 500SKK to CZK using c: + // assertEquals("Result is 400 CZK"); + result = c.convert("CZK", CurrencyValue.getCurrencyValue(500, "SKK")); + assertEquals(CurrencyValue.getCurrencyValue(400, "CZK"), result); + } +} diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution12/build.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution12/build.xml Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,69 @@ + + + + + + Builds, tests, and runs the project. + + + diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution12/nbproject/build-impl.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution12/nbproject/build-impl.xml Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,642 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set src.dir + Must set test.src.dir + Must set build.dir + Must set dist.dir + Must set build.classes.dir + Must set dist.javadoc.dir + Must set build.test.classes.dir + Must set build.test.results.dir + Must set build.classes.excludes + Must set dist.jar + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + + + + + + java -cp "${run.classpath.with.dist.jar}" ${main.class} + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + java -jar "${dist.jar.resolved}" + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set run.class + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set debug.class + + + + + Must set fix.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + Some tests failed; see details above. + + + + + + + + + Must select some files in the IDE or set test.includes + + + + Some tests failed; see details above. + + + + + Must select one file in the IDE or set test.class + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + + + + + + + + + + + diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution12/nbproject/genfiles.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution12/nbproject/genfiles.properties Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,8 @@ +build.xml.data.CRC32=2ab820eb +build.xml.script.CRC32=58a52595 +build.xml.stylesheet.CRC32=be360661 +# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. +# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. +nbproject/build-impl.xml.data.CRC32=b63e115b +nbproject/build-impl.xml.script.CRC32=3bdfc4fa +nbproject/build-impl.xml.stylesheet.CRC32=e55b27f5 diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution12/nbproject/project.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution12/nbproject/project.properties Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,68 @@ +application.title=currency +application.vendor=apidesign.org +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.tab-size=8 +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.text-limit-width=80 +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.usedProfile=default +build.classes.dir=${build.dir}/classes +build.classes.excludes=**/*.java,**/*.form +# This directory is removed when the project is cleaned: +build.dir=build +build.generated.dir=${build.dir}/generated +# Only compile against the classpath explicitly listed here: +build.sysclasspath=ignore +build.test.classes.dir=${build.dir}/test/classes +build.test.results.dir=${build.dir}/test/results +debug.classpath=\ + ${run.classpath} +debug.test.classpath=\ + ${run.test.classpath} +# This directory is removed when the project is cleaned: +dist.dir=dist +dist.jar=${dist.dir}/currency.jar +dist.javadoc.dir=${dist.dir}/javadoc +excludes= +file.reference.junit-4.4.jar=../../libs/junit-4.4.jar +file.reference.src-apifest08=.. +includes=** +jar.compress=false +javac.classpath= +# Space-separated list of extra javac options +javac.compilerargs= +javac.deprecation=false +javac.source=1.5 +javac.target=1.5 +javac.test.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir}:\ + ${file.reference.junit-4.4.jar} +javadoc.additionalparam= +javadoc.author=false +javadoc.encoding= +javadoc.noindex=false +javadoc.nonavbar=false +javadoc.notree=false +javadoc.private=false +javadoc.splitindex=true +javadoc.use=true +javadoc.version=false +javadoc.windowtitle= +jnlp.codebase.type=local +jnlp.codebase.url=file:/home/jarda/src/apifest08/currency/dist +jnlp.descriptor=application +jnlp.enabled=false +jnlp.offline-allowed=false +jnlp.signed=false +meta.inf.dir=${src.dir}/META-INF +platform.active=default_platform +run.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +# Space-separated list of JVM arguments used when running the project +# (you may also define separate properties like run-sys-prop.name=value instead of -Dname=value +# or test-sys-prop.name=value to set system properties for unit tests): +run.jvmargs= +run.test.classpath=\ + ${javac.test.classpath}:\ + ${build.test.classes.dir} +src.dir=src +test.src.dir=test diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution12/nbproject/project.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution12/nbproject/project.xml Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,16 @@ + + + org.netbeans.modules.java.j2seproject + + + Currency Convertor Solution 12 + 1.6.5 + + + + + + + + + diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution12/src/org/apidesign/apifest08/currency/Convertor.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution12/src/org/apidesign/apifest08/currency/Convertor.java Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,184 @@ +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 Hashtable convertorInstanceExchangeRates; + + private Convertor(List currencies) throws UnknownConvertorException { + convertorInstanceExchangeRates = new Hashtable(); + for (Currency currency1 : currencies) { + for (Currency currency2 : currencies) { + if(!currency1.getCurrencyCode().equals(currency2.getCurrencyCode())) { + String key = currency1.getCurrencyCode() + currency2.getCurrencyCode(); + ExchangeRate exchangeRate = exchangeRates.get(key); + convertorInstanceExchangeRates.put(key, exchangeRate); + } + } + } + } + + /** + * 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) { + convertorInstanceExchangeRates.putAll(convertor.getInstanceExchangeRates()); + 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 { + List currencyList = new ArrayList(); + + if(currencies.length < 2) { + throw new ConvertorException("To get convertor instance, you have to select at least two currencies!!!"); + } + + 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 key12 = currency1.getCurrencyCode() + currency2.getCurrencyCode(); + String key21 = currency2.getCurrencyCode() + currency1.getCurrencyCode(); + if (!(exchangeRates.containsKey(key12) && exchangeRates.containsKey(key21))) { + throw new UnknownConvertorException("Selected convertor (" + currency1.getCurrencyCode() + "<->" + + currency2.getCurrencyCode() + ") has not defined exchange rates!!!"); + } + } + } + + currencyList.add(currency1); + } + + return new Convertor(currencyList); + } + + /** + * 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(convertorInstanceExchangeRates.containsKey(key)) { + actualyUsedExchangeRate = convertorInstanceExchangeRates.get(key); + } else { + throw new InvalidCurrencyException("This convertor could not be used for converting selected currencies (" + originalCurrency.getCurrencyCode() + "->" + + newCurrency.getCurrencyCode() + ") !!!"); + } + + return actualyUsedExchangeRate; + } + + /** + * Returns exchange rates for actual instance of convertor. + * @return exchange rates for actual instance of convertor + */ + Hashtable getInstanceExchangeRates() { + return convertorInstanceExchangeRates; + } + +} diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution12/src/org/apidesign/apifest08/currency/ExchangeRate.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution12/src/org/apidesign/apifest08/currency/ExchangeRate.java Tue Oct 07 11:05:34 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 6a500cd1e467 -r 251d0ed461fb task3/solution12/src/org/apidesign/apifest08/currency/exceptions/ConvertorException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution12/src/org/apidesign/apifest08/currency/exceptions/ConvertorException.java Tue Oct 07 11:05:34 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 6a500cd1e467 -r 251d0ed461fb task3/solution12/src/org/apidesign/apifest08/currency/exceptions/InvalidCurrencyException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution12/src/org/apidesign/apifest08/currency/exceptions/InvalidCurrencyException.java Tue Oct 07 11:05:34 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 6a500cd1e467 -r 251d0ed461fb task3/solution12/src/org/apidesign/apifest08/currency/exceptions/UnknownConvertorException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution12/src/org/apidesign/apifest08/currency/exceptions/UnknownConvertorException.java Tue Oct 07 11:05:34 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 6a500cd1e467 -r 251d0ed461fb task3/solution12/test/org/apidesign/apifest08/test/Task1Test.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution12/test/org/apidesign/apifest08/test/Task1Test.java Tue Oct 07 11:05:34 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 6a500cd1e467 -r 251d0ed461fb task3/solution12/test/org/apidesign/apifest08/test/Task2Test.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution12/test/org/apidesign/apifest08/test/Task2Test.java Tue Oct 07 11:05:34 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 6a500cd1e467 -r 251d0ed461fb task3/solution13/build.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution13/build.xml Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,69 @@ + + + + + + Builds, tests, and runs the project. + + + diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution13/nbproject/build-impl.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution13/nbproject/build-impl.xml Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,642 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set src.dir + Must set test.src.dir + Must set build.dir + Must set dist.dir + Must set build.classes.dir + Must set dist.javadoc.dir + Must set build.test.classes.dir + Must set build.test.results.dir + Must set build.classes.excludes + Must set dist.jar + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + + + + + + java -cp "${run.classpath.with.dist.jar}" ${main.class} + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + java -jar "${dist.jar.resolved}" + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set run.class + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set debug.class + + + + + Must set fix.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + Some tests failed; see details above. + + + + + + + + + Must select some files in the IDE or set test.includes + + + + Some tests failed; see details above. + + + + + Must select one file in the IDE or set test.class + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + + + + + + + + + + + diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution13/nbproject/genfiles.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution13/nbproject/genfiles.properties Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,8 @@ +build.xml.data.CRC32=2ab820eb +build.xml.script.CRC32=58a52595 +build.xml.stylesheet.CRC32=be360661 +# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. +# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. +nbproject/build-impl.xml.data.CRC32=de21ce77 +nbproject/build-impl.xml.script.CRC32=0903858a +nbproject/build-impl.xml.stylesheet.CRC32=e55b27f5 diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution13/nbproject/project.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution13/nbproject/project.properties Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,68 @@ +application.title=currency +application.vendor=apidesign.org +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.tab-size=8 +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.text-limit-width=80 +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.usedProfile=default +build.classes.dir=${build.dir}/classes +build.classes.excludes=**/*.java,**/*.form +# This directory is removed when the project is cleaned: +build.dir=build +build.generated.dir=${build.dir}/generated +# Only compile against the classpath explicitly listed here: +build.sysclasspath=ignore +build.test.classes.dir=${build.dir}/test/classes +build.test.results.dir=${build.dir}/test/results +debug.classpath=\ + ${run.classpath} +debug.test.classpath=\ + ${run.test.classpath} +# This directory is removed when the project is cleaned: +dist.dir=dist +dist.jar=${dist.dir}/currency.jar +dist.javadoc.dir=${dist.dir}/javadoc +excludes= +file.reference.junit-4.4.jar=../../libs/junit-4.4.jar +file.reference.src-apifest08=.. +includes=** +jar.compress=false +javac.classpath= +# Space-separated list of extra javac options +javac.compilerargs= +javac.deprecation=false +javac.source=1.5 +javac.target=1.5 +javac.test.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir}:\ + ${file.reference.junit-4.4.jar} +javadoc.additionalparam= +javadoc.author=false +javadoc.encoding= +javadoc.noindex=false +javadoc.nonavbar=false +javadoc.notree=false +javadoc.private=false +javadoc.splitindex=true +javadoc.use=true +javadoc.version=false +javadoc.windowtitle= +jnlp.codebase.type=local +jnlp.codebase.url=file:/home/jarda/src/apifest08/currency/dist +jnlp.descriptor=application +jnlp.enabled=false +jnlp.offline-allowed=false +jnlp.signed=false +meta.inf.dir=${src.dir}/META-INF +platform.active=default_platform +run.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +# Space-separated list of JVM arguments used when running the project +# (you may also define separate properties like run-sys-prop.name=value instead of -Dname=value +# or test-sys-prop.name=value to set system properties for unit tests): +run.jvmargs= +run.test.classpath=\ + ${javac.test.classpath}:\ + ${build.test.classes.dir} +src.dir=src +test.src.dir=test diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution13/nbproject/project.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution13/nbproject/project.xml Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,16 @@ + + + org.netbeans.modules.java.j2seproject + + + Currency Convertor Solution 13 + 1.6.5 + + + + + + + + + diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution13/src/org/apidesign/apifest08/currency/ConversionNotSupportedException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution13/src/org/apidesign/apifest08/currency/ConversionNotSupportedException.java Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,85 @@ +package org.apidesign.apifest08.currency; + +/** + * Conversion not suported exception. This expecption may optionaly describe which conversion was required and failed. + * Required conversion can be found in {@link #getFromCurrecyCode() } and {@link #getToCurrecyCode() }. + * + * @author arnostvalicek + * @since version2 + */ +public class ConversionNotSupportedException extends ConvertorException { + String from; + String to; + boolean reversed; + + public ConversionNotSupportedException() { + super(); + } + + public ConversionNotSupportedException(String message) { + super(message); + } + + public ConversionNotSupportedException(String message, Throwable cause) { + super(message, cause); + } + + public ConversionNotSupportedException(Throwable cause) { + super(cause); + } + + /** + * Create exception witd additional information about currencies which are not supported in coversion. + * @param from Code of source currency. + * @param to Code of target currency. + * @param twoWay Set to false if From->To is not supported. + * Set to true if both ways From->To and To->From conversions are not supported. + * + */ + public ConversionNotSupportedException(String from, String to, boolean twoWay) { + this.from = from; + this.to = to; + this.reversed = true; + } + + @Override + public String toString() { + if (from!=null && to !=null) { + if (reversed) { + return "Neither 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 of two way conversion is not supported. + * + * Value false means one way conversion is not supported. Value true means + * that two way conversio is not supported. + * + * @return Returs false for one way conversion, true for two way conversion. + */ + public boolean getTwoWayConversion() { + return reversed; + } + +} diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution13/src/org/apidesign/apifest08/currency/ConversionResult.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution13/src/org/apidesign/apifest08/currency/ConversionResult.java Tue Oct 07 11:05:34 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 6a500cd1e467 -r 251d0ed461fb task3/solution13/src/org/apidesign/apifest08/currency/Convertor.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution13/src/org/apidesign/apifest08/currency/Convertor.java Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,213 @@ +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(2); + + 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); + } + + final BigDecimal converted = division[0].movePointLeft(2); + 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 6a500cd1e467 -r 251d0ed461fb task3/solution13/src/org/apidesign/apifest08/currency/ConvertorCurrency.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution13/src/org/apidesign/apifest08/currency/ConvertorCurrency.java Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,63 @@ + +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 String toString() { + return "ConvertorCurrency[" + (currency != null ? currency.toString() : "NO-BASE-CURRENCY")+"]"; + } + + String getCurrencyCode() { + return currency.getCurrencyCode(); + } +} diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution13/src/org/apidesign/apifest08/currency/ConvertorException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution13/src/org/apidesign/apifest08/currency/ConvertorException.java Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,25 @@ +package org.apidesign.apifest08.currency; + +/** + * Common Convertor exception. + * + * @author arnostvalicek + */ +public class ConvertorException extends RuntimeException { + + public ConvertorException(Throwable cause) { + super(cause); + } + + public ConvertorException(String message, Throwable cause) { + super(message, cause); + } + + public ConvertorException(String message) { + super(message); + } + + public ConvertorException() { + } + +} diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution13/src/org/apidesign/apifest08/currency/ExchangeRate.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution13/src/org/apidesign/apifest08/currency/ExchangeRate.java Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,68 @@ + +package org.apidesign.apifest08.currency; + +import java.math.BigDecimal; + +/** + * Exchange rate value. Contains from and to value. + * + * @author arnostvalicek + */ +public class ExchangeRate { + private BigDecimal numberFor; + private BigDecimal numberGet; + + /** + * Constructor for new exchange rate holding two values - from value and to value + * @param fromValue Exchange rate from value + * @param toValue Exchange rate to value + */ + public ExchangeRate(BigDecimal fromValue, BigDecimal toValue) { + this.numberFor = fromValue; + this.numberGet = toValue; + } + + /** + * Create new instance of ExchangeRate based on provided exchange rate, but swapping its + * from and to value. + *

+ * Provided exchange rate is not chaged, this method returns different instance describing reverted exchange rate. + * + * @param rate Exchange rate which describes rate to be reverted. + * @return Instance of reverted rate. + */ + public static ExchangeRate createRevertedRate(ExchangeRate rate) { + ExchangeRate reverted = new ExchangeRate(rate.getToValue(), rate.getFromValue()); + return reverted; + } + + @Override + public String toString() { + return "for "+numberFor+" recieve "+numberGet+" @"+getClass().getName(); + } + + /** + * Return exchange rate from value stored in this object. + * @return Returns from value for this exchange rate. + */ + public BigDecimal getFromValue() { + return numberFor; + } + + /** + * Return exchange rate to value stored in this object. + * @return Returns to value for this exchange rate. + */ + public BigDecimal getToValue() { + return numberGet; + } + + +// public ExchangeRate createExchangeRate(BigDecimal forValue, BigDecimal getValue) { +// ExchangeRate rate = new ExchangeRate(forValue, getValue); +// return rate; +// } + + + +} diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution13/src/org/apidesign/apifest08/currency/ExchangeRateProvider.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution13/src/org/apidesign/apifest08/currency/ExchangeRateProvider.java Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,152 @@ + +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 fixed exchange rate which does not depend + * on date (method {@link #getExchangeRate()} ). + * + * Date dependend exchange rate to be implemented. + * + * @author arnostvalicek + */ +public class ExchangeRateProvider { + BigDecimal fromValue, toValue; + ConvertorCurrency fromCurrency, toCurrency; + + Map exchangeRateMap = new HashMap(); + + /** + * 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.fromValue = fromValue; + this.toValue = toValue; + this.fromCurrency = fromCurrency; + this.toCurrency = 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(); + return provider; + } + + /** + * Add new exchange rate to to this 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)); + *

+ * + * @param fromCurrency Source currency. + * @param fromValue Valye for from currency. + * @param toCurrency Target currency. + * @param toValue Value for target currency. + */ + 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); + } + + /** + * Get fixed exange rate for currencies (from->to). + * @return Returns exchange rate. + * @deprecated deprecated since task2. Use {@link #getExchangeRate(ConvertorCurrency, ConvertorCurrency) } + */ + public ExchangeRate getExchangeRate() { + return new ExchangeRate(fromValue, toValue); + } + + + /** + * 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) { + return new ExchangeRate(fromValue, toValue); + } + + + ConvertorCurrency getFromCurrency() { + return fromCurrency; + } + + ConvertorCurrency getToCurrency() { + return toCurrency; + } + + private ExchangeRate getExchangeRateImpl(ConvertorCurrency fromCurrency, ConvertorCurrency toCurrency) { + if (fromValue != null && toValue != null && fromCurrency.equals(this.fromCurrency) && toCurrency.equals(this.toCurrency)) { + return new ExchangeRate(fromValue, toValue); + } + //return new ExchangeRate(fromValue, toValue); + Map map2 = (Map) exchangeRateMap.get(fromCurrency); + if (map2 == null) { + return null; + } + ExchangeRate result = (ExchangeRate) map2.get(toCurrency); + return result; + } + + +} diff -r 6a500cd1e467 -r 251d0ed461fb task3/solution13/test/org/apidesign/apifest08/test/Task1Test.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution13/test/org/apidesign/apifest08/test/Task1Test.java Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,223 @@ +package org.apidesign.apifest08.test; + +import java.math.BigDecimal; +import junit.framework.TestCase; +import org.apidesign.apifest08.currency.ConversionResult; +import org.apidesign.apifest08.currency.Convertor; +import org.apidesign.apifest08.currency.ConvertorCurrency; +import org.apidesign.apifest08.currency.ExchangeRateProvider; +import org.apidesign.apifest08.currency.ConversionNotSupportedException; + +/** Finish the Convertor API, and then write bodies of methods inside + * of this class to match the given tasks. To fullfil your task, use the + * API define in the org.apidesign.apifest08.currency package. + * Do not you reflection, or other hacks as your code + * shall run without any runtime permissions. + */ +public class Task1Test extends TestCase { + public Task1Test(String testName) { + super(testName); + } + + @Override + protected void setUp() throws Exception { + } + + @Override + protected void tearDown() throws Exception { + } + + /** Create convertor that understands two currencies, CZK and + * USD. Make 1 USD == 17 CZK. + * + * Creation of the convertor shall not require subclassing of any class + * or interface on the client side. + * + * @return prepared convertor ready for converting USD to CZK and CZK to USD + */ + public static Convertor createCZKtoUSD() { + ConvertorCurrency fromCurrency = ConvertorCurrency.getInstance("CZK"); + ConvertorCurrency toCurrency = ConvertorCurrency.getInstance("USD"); + ExchangeRateProvider exchangeRateProvider = new ExchangeRateProvider(new BigDecimal(17), fromCurrency, new BigDecimal(1), toCurrency); + + return Convertor.createConvertor(exchangeRateProvider); + } + + /** Create convertor that understands two currencies, CZK and + * SKK. Make 100 SKK == 80 CZK. + * + * Creation of the convertor shall not require subclassing of any class + * or interface on the client side. + * + * @return prepared convertor ready for converting SKK to CZK and CZK to SKK + */ + public static Convertor createSKKtoCZK() { + ConvertorCurrency fromCurrency = ConvertorCurrency.getInstance("SKK"); + ConvertorCurrency toCurrency = ConvertorCurrency.getInstance("CZK"); + ExchangeRateProvider exchangeRateProvider = new ExchangeRateProvider(new BigDecimal(100), fromCurrency, new BigDecimal(80), toCurrency); + + return Convertor.createConvertor(exchangeRateProvider); + } + + + public static Convertor createCZKtoYEN() { + ConvertorCurrency fromCurrency = ConvertorCurrency.getInstance("CZK"); + ConvertorCurrency toCurrency = ConvertorCurrency.getInstance("JPY"); + ExchangeRateProvider exchangeRateProvider = new ExchangeRateProvider(new BigDecimal(1), fromCurrency, new BigDecimal(1), toCurrency); + + return Convertor.createConvertor(exchangeRateProvider); + } + + /** Use the convertor from createCZKtoUSD method and do few conversions + * with it. + */ + public void testCurrencyCZKUSD() throws Exception { + Convertor convertCzkUsd = createCZKtoUSD(); + + { + // convert $1 to CZK using c: + ConversionResult result = convertCzkUsd.convertBack(new BigDecimal(1)); + assertEquals("Result is 17 CZK", new BigDecimal("17.00"), result.getConverted()); + assertEquals("No Remainer", 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 6a500cd1e467 -r 251d0ed461fb task3/solution13/test/org/apidesign/apifest08/test/Task2Test.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task3/solution13/test/org/apidesign/apifest08/test/Task2Test.java Tue Oct 07 11:05:34 2008 +0200 @@ -0,0 +1,136 @@ +package org.apidesign.apifest08.test; + +import java.math.BigDecimal; +import junit.framework.TestCase; +import org.apidesign.apifest08.currency.Convertor; +import org.apidesign.apifest08.currency.ConvertorCurrency; +import org.apidesign.apifest08.currency.ExchangeRateProvider; + +/** There are many currencies around the world and many banks manipulate + * with more than one or two at the same time. As banks are usually the + * best paying clients, which is true even in case of your Convertor API, + * it is reasonable to listen to their requests. + *

+ * The quest for today is to enhance your existing convertor API to hold + * information about many currencies and allow conversions between any of them. + * Also, as conversion rates for diferent currencies usually arise from various + * bank departments, there is another important need. There is a need to + * compose two convertors into one by merging all the information about + * currencies they know about. + */ +public class Task2Test extends TestCase { + private static ConvertorCurrency currencyCZK = ConvertorCurrency.getInstance("CZK"); + private static ConvertorCurrency currencySKK = ConvertorCurrency.getInstance("SKK"); + private static ConvertorCurrency currencyUSD = ConvertorCurrency.getInstance("USD"); + + public Task2Test(String testName) { + super(testName); + } + + @Override + protected void setUp() throws Exception { + + } + + @Override + protected void tearDown() throws Exception { + } + + public static Convertor createUsdToSkkConvertor() { + ConvertorCurrency fromCurrency = currencyUSD; + ConvertorCurrency toCurrency = 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()); + + } +}