japod@6
|
1 |
package org.apidesign.apifest08.currency;
|
japod@6
|
2 |
|
japod@6
|
3 |
import java.util.Currency;
|
japod@6
|
4 |
import java.util.Hashtable;
|
japod@6
|
5 |
import java.util.Map;
|
japod@6
|
6 |
|
japod@6
|
7 |
/** This is the skeleton class for your API. You need to make it public, so
|
japod@6
|
8 |
* it is accessible to your client code (currently in Task1Test.java) file.
|
japod@6
|
9 |
* <p>
|
japod@6
|
10 |
* Feel free to create additional classes or rename this one, just keep all
|
japod@6
|
11 |
* the API and its implementation in this package. Do not spread it outside
|
japod@6
|
12 |
* to other packages.
|
japod@6
|
13 |
*/
|
japod@6
|
14 |
public class Convertor {
|
japod@6
|
15 |
|
japod@6
|
16 |
private static final Map<String, Float> EXCHANGE_RATES = new Hashtable<String, Float>() { {
|
japod@6
|
17 |
put("CZKUSD", 1/17F);
|
japod@6
|
18 |
put("USDCZK", 17F);
|
japod@6
|
19 |
put("SKKCZK", 100/80F);
|
japod@6
|
20 |
put("CZKSKK", 80/100F);
|
japod@6
|
21 |
}
|
japod@6
|
22 |
};
|
japod@6
|
23 |
|
japod@6
|
24 |
private Currency currencyFirst;
|
japod@6
|
25 |
private Currency currencySecond;
|
japod@6
|
26 |
|
japod@6
|
27 |
private Convertor(Currency currencyFirst, Currency currencySecond) {
|
japod@6
|
28 |
this.currencyFirst = currencyFirst;
|
japod@6
|
29 |
this.currencySecond = currencySecond;
|
japod@6
|
30 |
}
|
japod@6
|
31 |
|
japod@6
|
32 |
public static Convertor getInstanceFor(Currency currencyFirst, Currency currencySecond) {
|
japod@6
|
33 |
return new Convertor(currencyFirst, currencySecond);
|
japod@6
|
34 |
}
|
japod@6
|
35 |
|
japod@6
|
36 |
public float convert(float value, Currency toCurrency) {
|
japod@6
|
37 |
if (!toCurrency.equals(currencyFirst) && !toCurrency.equals(currencySecond)) {
|
japod@6
|
38 |
throw new IllegalArgumentException("Unsupported currency for this convertor!: " + toCurrency.getCurrencyCode());
|
japod@6
|
39 |
}
|
japod@6
|
40 |
|
japod@6
|
41 |
Float rate = null;
|
japod@6
|
42 |
if (toCurrency.equals(currencyFirst)) {
|
japod@6
|
43 |
rate = EXCHANGE_RATES.get(currencyFirst.getCurrencyCode() + currencySecond.getCurrencyCode());
|
japod@6
|
44 |
}
|
japod@6
|
45 |
if (toCurrency.equals(currencySecond)) {
|
japod@6
|
46 |
rate = EXCHANGE_RATES.get(currencySecond.getCurrencyCode() + currencyFirst.getCurrencyCode());
|
japod@6
|
47 |
}
|
japod@6
|
48 |
|
japod@6
|
49 |
if (rate == null) {
|
japod@6
|
50 |
throw new IllegalStateException("Undefinied conversion!");
|
japod@6
|
51 |
}
|
japod@6
|
52 |
|
japod@6
|
53 |
return rate*value;
|
japod@6
|
54 |
}
|
japod@6
|
55 |
}
|