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