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 @Override
037 public Object convert(String key) throws WebCacheException {
038 String symbol = _symbol;
039 double rate = 0.0;
040
041 try {
042 if (symbol.length() == 6) {
043 String fromSymbol = symbol.substring(0, 3);
044 String toSymbol = symbol.substring(3, 6);
045
046 if (!CurrencyUtil.isCurrency(fromSymbol) ||
047 !CurrencyUtil.isCurrency(toSymbol)) {
048
049 throw new WebCacheException(symbol);
050 }
051 }
052 else if (symbol.length() == 3) {
053 if (!CurrencyUtil.isCurrency(symbol)) {
054 throw new WebCacheException(symbol);
055 }
056 }
057 else {
058 throw new WebCacheException(symbol);
059 }
060
061 String text = HttpUtil.URLtoString(
062 "http:
063 symbol + "=X&f=sl1d1t1c1ohgv&e=.csv");
064
065 StringTokenizer st = new StringTokenizer(text, StringPool.COMMA);
066
067
068
069 st.nextToken();
070
071 rate = GetterUtil.getDouble(
072 st.nextToken().replace('"', ' ').trim());
073 }
074 catch (Exception e) {
075 throw new WebCacheException(e);
076 }
077
078 return new Currency(symbol, rate);
079 }
080
081 @Override
082 public long getRefreshTime() {
083 return _REFRESH_TIME;
084 }
085
086 private static final long _REFRESH_TIME = Time.MINUTE * 20;
087
088 private String _symbol;
089
090 }