001
014
015 package com.liferay.portlet.currencyconverter.util;
016
017 import com.liferay.portal.kernel.util.GetterUtil;
018 import com.liferay.portal.kernel.util.HttpUtil;
019 import com.liferay.portal.kernel.util.StringPool;
020 import com.liferay.portal.kernel.util.Time;
021 import com.liferay.portal.kernel.webcache.WebCacheException;
022 import com.liferay.portal.kernel.webcache.WebCacheItem;
023 import com.liferay.portlet.currencyconverter.model.Currency;
024
025 import java.util.StringTokenizer;
026
027
030 public class CurrencyWebCacheItem implements WebCacheItem {
031
032 public CurrencyWebCacheItem(String symbol) {
033 _symbol = symbol;
034 }
035
036 public Object convert(String key) throws WebCacheException {
037 String symbol = _symbol;
038 double rate = 0.0;
039
040 try {
041 if (symbol.length() == 6) {
042 String fromSymbol = symbol.substring(0, 3);
043 String toSymbol = symbol.substring(3, 6);
044
045 if (!CurrencyUtil.isCurrency(fromSymbol) ||
046 !CurrencyUtil.isCurrency(toSymbol)) {
047
048 throw new WebCacheException(symbol);
049 }
050 }
051 else if (symbol.length() == 3) {
052 if (!CurrencyUtil.isCurrency(symbol)) {
053 throw new WebCacheException(symbol);
054 }
055 }
056 else {
057 throw new WebCacheException(symbol);
058 }
059
060 String text = HttpUtil.URLtoString(
061 "http:
062 symbol + "=X&f=sl1d1t1c1ohgv&e=.csv");
063
064 StringTokenizer st = new StringTokenizer(text, StringPool.COMMA);
065
066
067
068 st.nextToken();
069
070 rate = GetterUtil.getDouble(
071 st.nextToken().replace('"', ' ').trim());
072 }
073 catch (Exception e) {
074 throw new WebCacheException(e);
075 }
076
077 return new Currency(symbol, rate);
078 }
079
080 public long getRefreshTime() {
081 return _REFRESH_TIME;
082 }
083
084 private static final long _REFRESH_TIME = Time.MINUTE * 20;
085
086 private String _symbol;
087
088 }