1
14
15 package com.liferay.portlet.translator.util;
16
17 import com.liferay.portal.kernel.util.HttpUtil;
18 import com.liferay.portal.kernel.util.StringBundler;
19 import com.liferay.portal.kernel.util.StringUtil;
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.translator.model.Translation;
24
25 import java.net.URL;
26
27
32 public class TranslationWebCacheItem implements WebCacheItem {
33
34 public TranslationWebCacheItem(String translationId, String fromText) {
35 _translationId = translationId;
36 _fromText = fromText;
37 }
38
39 public Object convert(String key) throws WebCacheException {
40 Translation translation = new Translation(_translationId, _fromText);
41
42 try {
43 StringBundler sb = new StringBundler(6);
44
45 sb.append("http://babelfish.yahoo.com/translate_txt?");
46 sb.append("ei=UTF-8&doit=done&fr=bf-res&intl=1&tt=urltext");
47 sb.append("&trtext=");
48 sb.append(HttpUtil.encodeURL(_fromText));
49 sb.append("&lp=");
50 sb.append(_translationId);
51
52 String text = HttpUtil.URLtoString(new URL(sb.toString()));
53
54 int x = text.indexOf("<div id=\"result\">");
55
56 x = text.indexOf(">", x) + 1;
57 x = text.indexOf(">", x) + 1;
58
59 int y = text.indexOf("</div>", x);
60
61 String toText = text.substring(x, y).trim();
62
63 toText = StringUtil.replace(toText, "\n", " ");
64
65 translation.setToText(toText);
66 }
67 catch (Exception e) {
68 throw new WebCacheException(e);
69 }
70
71 return translation;
72 }
73
74 public long getRefreshTime() {
75 return _REFRESH_TIME;
76 }
77
78 private static final long _REFRESH_TIME = Time.DAY * 90;
79
80 private String _translationId;
81 private String _fromText;
82
83 }