001
014
015 package com.liferay.portlet.translator.util;
016
017 import com.liferay.portal.kernel.microsofttranslator.MicrosoftTranslator;
018 import com.liferay.portal.kernel.microsofttranslator.MicrosoftTranslatorFactoryUtil;
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.translator.model.Translation;
024
025
029 public class TranslationWebCacheItem implements WebCacheItem {
030
031 public TranslationWebCacheItem(String translationId, String fromText) {
032 _translationId = translationId;
033 _fromText = fromText;
034 }
035
036 @Override
037 public Object convert(String key) throws WebCacheException {
038 Translation translation = new Translation(_translationId, _fromText);
039
040 try {
041 MicrosoftTranslator microsoftTranslator =
042 MicrosoftTranslatorFactoryUtil.getMicrosoftTranslator();
043
044 int x = _translationId.indexOf(StringPool.UNDERLINE);
045
046 if ((x == -1) || ((x + 1) == _translationId.length())) {
047 throw new WebCacheException(
048 "Invalid translation ID " + _translationId);
049 }
050
051 if (Character.isUpperCase(_translationId.charAt(x + 1))) {
052 x = _translationId.indexOf(StringPool.UNDERLINE, x + 1);
053
054 if ((x == -1) || ((x + 1) == _translationId.length())) {
055 throw new WebCacheException(
056 "Invalid translation ID " + _translationId);
057 }
058 }
059
060 String fromLanguage = _translationId.substring(0, x);
061 String toLanguage = _translationId.substring(x + 1);
062
063 String toText = microsoftTranslator.translate(
064 fromLanguage, toLanguage, _fromText);
065
066 translation.setToText(toText);
067 }
068 catch (Exception e) {
069 throw new WebCacheException(e);
070 }
071
072 return translation;
073 }
074
075 @Override
076 public long getRefreshTime() {
077 return _REFRESH_TIME;
078 }
079
080 private static final long _REFRESH_TIME = Time.DAY * 90;
081
082 private String _fromText;
083 private String _translationId;
084
085 }