1
19
20 package com.liferay.portlet.currencyconverter.util;
21
22 import com.liferay.portal.kernel.util.GetterUtil;
23 import com.liferay.portal.kernel.util.HttpUtil;
24 import com.liferay.portal.kernel.util.StringPool;
25 import com.liferay.portal.kernel.util.Time;
26 import com.liferay.portal.kernel.webcache.WebCacheException;
27 import com.liferay.portal.kernel.webcache.WebCacheItem;
28 import com.liferay.portlet.currencyconverter.model.Currency;
29
30 import java.util.StringTokenizer;
31
32
38 public class CurrencyWebCacheItem implements WebCacheItem {
39
40 public CurrencyWebCacheItem(String symbol) {
41 _symbol = symbol;
42 }
43
44 public Object convert(String key) throws WebCacheException {
45 String symbol = _symbol;
46 double rate = 0.0;
47
48 try {
49 if (symbol.length() == 6) {
50 String fromSymbol = symbol.substring(0, 3);
51 String toSymbol = symbol.substring(3, 6);
52
53 if (!CurrencyUtil.isCurrency(fromSymbol) ||
54 !CurrencyUtil.isCurrency(toSymbol)) {
55
56 throw new WebCacheException(symbol);
57 }
58 }
59 else if (symbol.length() == 3) {
60 if (!CurrencyUtil.isCurrency(symbol)) {
61 throw new WebCacheException(symbol);
62 }
63 }
64 else {
65 throw new WebCacheException(symbol);
66 }
67
68 String text = HttpUtil.URLtoString(
69 "http://finance.yahoo.com/d/quotes.csv?s=" +
70 symbol + "=X&f=sl1d1t1c1ohgv&e=.csv");
71
72 StringTokenizer st = new StringTokenizer(text, StringPool.COMMA);
73
74
76 st.nextToken();
77
78 rate = GetterUtil.getDouble(
79 st.nextToken().replace('"', ' ').trim());
80 }
81 catch (Exception e) {
82 throw new WebCacheException(e);
83 }
84
85 return new Currency(symbol, rate);
86 }
87
88 public long getRefreshTime() {
89 return _REFRESH_TIME;
90 }
91
92 private static final long _REFRESH_TIME = Time.MINUTE * 20;
93
94 private String _symbol;
95
96 }