1   /**
2    * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
3    *
4    * This library is free software; you can redistribute it and/or modify it under
5    * the terms of the GNU Lesser General Public License as published by the Free
6    * Software Foundation; either version 2.1 of the License, or (at your option)
7    * any later version.
8    *
9    * This library is distributed in the hope that it will be useful, but WITHOUT
10   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11   * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
12   * details.
13   */
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  /**
28   * <a href="TranslationWebCacheItem.java.html"><b><i>View Source</i></b></a>
29   *
30   * @author Brian Wing Shun Chan
31   */
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  }