1   /**
2    * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
3    *
4    * The contents of this file are subject to the terms of the Liferay Enterprise
5    * Subscription License ("License"). You may not use this file except in
6    * compliance with the License. You can obtain a copy of the License by
7    * contacting Liferay, Inc. See the License for the specific language governing
8    * permissions and limitations under the License, including but not limited to
9    * distribution rights of the Software.
10   *
11   *
12   *
13   */
14  
15  package com.liferay.portlet.translator.util;
16  
17  import com.liferay.portal.kernel.util.CharPool;
18  import com.liferay.portal.kernel.util.HttpUtil;
19  import com.liferay.portal.kernel.util.StringBundler;
20  import com.liferay.portal.kernel.util.StringUtil;
21  import com.liferay.portal.kernel.util.Time;
22  import com.liferay.portal.kernel.webcache.WebCacheException;
23  import com.liferay.portal.kernel.webcache.WebCacheItem;
24  import com.liferay.portlet.translator.model.Translation;
25  
26  import java.net.URL;
27  
28  /**
29   * <a href="TranslationWebCacheItem.java.html"><b><i>View Source</i></b></a>
30   *
31   * @author Brian Wing Shun Chan
32   */
33  public class TranslationWebCacheItem implements WebCacheItem {
34  
35      public TranslationWebCacheItem(String translationId, String fromText) {
36          _translationId = translationId;
37          _fromText = fromText;
38      }
39  
40      public Object convert(String key) throws WebCacheException {
41          Translation translation = new Translation(_translationId, _fromText);
42  
43          try {
44              StringBundler sb = new StringBundler(6);
45  
46              sb.append("http://babelfish.yahoo.com/translate_txt?");
47              sb.append("ei=UTF-8&doit=done&fr=bf-res&intl=1&tt=urltext");
48              sb.append("&trtext=");
49              sb.append(HttpUtil.encodeURL(_fromText));
50              sb.append("&lp=");
51              sb.append(_translationId);
52  
53              String text = HttpUtil.URLtoString(new URL(sb.toString()));
54  
55              int x = text.indexOf("<div id=\"result\">");
56  
57              x = text.indexOf(">", x) + 1;
58              x = text.indexOf(">", x) + 1;
59  
60              int y = text.indexOf("</div>", x);
61  
62              String toText = text.substring(x, y).trim();
63  
64              toText = StringUtil.replace(
65                  toText, CharPool.NEW_LINE, CharPool.SPACE);
66  
67              translation.setToText(toText);
68          }
69          catch (Exception e) {
70              throw new WebCacheException(e);
71          }
72  
73          return translation;
74      }
75  
76      public long getRefreshTime() {
77          return _REFRESH_TIME;
78      }
79  
80      private static final long _REFRESH_TIME = Time.DAY * 90;
81  
82      private String _translationId;
83      private String _fromText;
84  
85  }