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