View Javadoc

1   /**
2    * This file Copyright (c) 2008-2011 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.cms.i18n;
35  
36  import info.magnolia.cms.core.Content;
37  import info.magnolia.cms.core.NodeData;
38  import info.magnolia.cms.util.NodeDataUtil;
39  import info.magnolia.context.MgnlContext;
40  
41  import java.util.Collection;
42  import java.util.HashSet;
43  import java.util.Iterator;
44  import java.util.LinkedHashMap;
45  import java.util.Locale;
46  import java.util.Map;
47  import java.util.Set;
48  
49  import javax.jcr.Node;
50  import javax.jcr.RepositoryException;
51  
52  import org.apache.commons.lang.StringUtils;
53  import org.slf4j.Logger;
54  import org.slf4j.LoggerFactory;
55  
56  /**
57   * An abstract implementation of {@link I18nContentSupport} which stores the
58   * locale specific content in node data having a local suffix:
59   * <name>_<locale>.
60   *
61   * The detection of the current locale, based on the URI for instance, is left to the concrete implementation.
62   * @author philipp
63   *
64   */
65  public abstract class AbstractI18nContentSupport implements I18nContentSupport {
66  
67      private static final Logger log = LoggerFactory.getLogger(AbstractI18nContentSupport.class);
68  
69      /**
70       * The content is served for this locale if the the content is not available for the current locale.
71       */
72      private Locale fallbackLocale = new Locale("en");
73  
74      /**
75       * If no locale can be determined the default locale will be set. If no default locale is defined the fallback locale is used.
76       */
77      protected Locale defaultLocale;
78  
79      private boolean enabled = false;
80  
81      /**
82       * The active locales.
83       */
84      private Map<String, Locale> locales = new LinkedHashMap<String, Locale>();
85  
86      @Override
87      public Locale getLocale() {
88          Locale locale = null;
89          if(MgnlContext.getWebContextOrNull() != null){
90              locale = MgnlContext.getAggregationState().getLocale();
91          }
92          if (locale == null) {
93              return fallbackLocale;
94          }
95          return locale;
96      }
97  
98      @Override
99      public void setLocale(Locale locale) {
100         MgnlContext.getAggregationState().setLocale(locale);
101     }
102 
103     @Override
104     public Locale getFallbackLocale() {
105         return this.fallbackLocale;
106     }
107 
108     @Override
109     public void setFallbackLocale(Locale fallbackLocale) {
110         this.fallbackLocale = fallbackLocale;
111     }
112 
113     /**
114      * Returns the closest locale for which {@link #isLocaleSupported(Locale)} is true.
115      * <ul>
116      * <li>If the locale has a country specified (fr_CH) the locale without country (fr) will be returned.</li>
117      * <li>If the locale has no country specified (fr) the first locale with the same language but specific country (fr_CH) will be returned.</li>
118      * <li>If this fails the fall-back locale is returned</li>
119      * </ul>
120      * Warning: if you have configured both (fr and fr_CH) this method will jiter between this two values.
121      */
122     protected Locale getNextLocale(Locale locale) {
123         // if this locale defines a country
124         if(StringUtils.isNotEmpty(locale.getCountry())){
125             // try to use the language only
126             Locale langOnlyLocale = new Locale(locale.getLanguage());
127             if(isLocaleSupported(langOnlyLocale)){
128                 return langOnlyLocale;
129             }
130         }
131         // try to find a locale with the same language (ignore the country)
132         for (Iterator<Locale> iter = getLocales().iterator(); iter.hasNext();) {
133             Locale otherCountryLocale = iter.next();
134             // same lang, but not the same country as well or we end up in the loop
135             if(locale.getLanguage().equals(otherCountryLocale.getLanguage()) && !locale.equals(otherCountryLocale)){
136                 return otherCountryLocale;
137             }
138         }
139         return getFallbackLocale();
140     }
141 
142     /**
143      * Extracts the language from the uri.
144      */
145     @Override
146     public Locale determineLocale() {
147         Locale locale;
148 
149         locale = onDetermineLocale();
150 
151         // depending on the implementation the returned local can be null (not defined)
152         if(locale == null){
153             locale = getDefaultLocale();
154         }
155         // if we have a locale but it is not supported we try to get the closest locale
156         if(!isLocaleSupported(locale)){
157             locale = getNextLocale(locale);
158         }
159         // instead of returning the content fallback language
160         // we are going to return the default locale which might differ
161         if(locale.equals(getFallbackLocale())){
162             locale = getDefaultLocale();
163         }
164         return locale;
165     }
166 
167     protected abstract Locale onDetermineLocale();
168 
169     protected static Locale determineLocalFromString(String localeStr) {
170         if(StringUtils.isNotEmpty(localeStr)){
171             String[] localeArr = StringUtils.split(localeStr, "_");
172             if(localeArr.length ==1){
173                 return new Locale(localeArr[0]);
174             }
175             else if(localeArr.length == 2){
176                 return new Locale(localeArr[0],localeArr[1]);
177             }
178         }
179         return null;
180     }
181 
182     @Override
183     public String toI18NURI(String uri) {
184         if (!isEnabled()) {
185             return uri;
186         }
187         Locale locale = getLocale();
188         if (isLocaleSupported(locale)) {
189             return toI18NURI(uri, locale);
190         }
191         return uri;
192     }
193 
194     protected abstract String toI18NURI(String uri, Locale locale);
195 
196     /**
197      * Removes the prefix.
198      */
199     @Override
200     public String toRawURI(String i18nURI) {
201         if (!isEnabled()) {
202             return i18nURI;
203         }
204 
205         Locale locale = getLocale();
206         if (isLocaleSupported(locale)) {
207             return toRawURI(i18nURI, locale);
208         }
209         return i18nURI;
210     }
211 
212     protected abstract String toRawURI(String i18nURI, Locale locale);
213 
214     @Override
215     public NodeData getNodeData(Content node, String name, Locale locale) throws RepositoryException {
216         String nodeDataName = name + "_" + locale;
217         if (node.hasNodeData(nodeDataName)) {
218             return node.getNodeData(nodeDataName);
219         }
220         return null;
221     }
222 
223     /**
224      * Returns the nodedata with the name &lt;name&gt;_&lt;current language&gt; or &lt;name&gt;_&lt;fallback language&gt
225      * otherwise returns &lt;name&gt;.
226      */
227     @Override
228     public NodeData getNodeData(Content node, String name) {
229         NodeData nd = null;
230 
231         if (isEnabled()) {
232             try {
233                 // test for the current language
234                 Locale locale = getLocale();
235                 Set<Locale> checkedLocales = new HashSet<Locale>();
236 
237                 // getNextContentLocale() returns null once the end of the locale chain is reached
238                 while(locale != null){
239                     nd = getNodeData(node, name, locale);
240                     if (!isEmpty(nd)) {
241                         return nd;
242                     }
243                     checkedLocales.add(locale);
244                     locale = getNextContentLocale(locale, checkedLocales);
245                 }
246             }
247             catch (RepositoryException e) {
248                 log.error("can't read i18n nodeData " + name + " from node " + node, e);
249             }
250         }
251 
252         // return the node data
253         return node.getNodeData(name);
254     }
255 
256     @Override
257     public Node getNode(Node node, String name) throws RepositoryException {
258         if (isEnabled()) {
259 
260             try {
261                 // test for the current language
262                 Locale locale = getLocale();
263                 Set<Locale> checkedLocales = new HashSet<Locale>();
264 
265                 // getNextContentLocale() returns null once the end of the locale chain is reached
266                 while(locale != null){
267                     String localeSpecificChildName = name + "_" + locale;
268                     if (node.hasNode(localeSpecificChildName))
269                         return node.getNode(localeSpecificChildName);
270                     checkedLocales.add(locale);
271                     locale = getNextContentLocale(locale, checkedLocales);
272                 }
273             }
274             catch (RepositoryException e) {
275                 log.error("can't read i18n node " + name + " from node " + node, e);
276             }
277         }
278 
279         return node.getNode(name);
280     }
281 
282     /**
283      * Uses {@link #getNextLocale(Locale)} to find the next locale. If the returned locale is in the
284      * checkedLocales set it falls back to the fall-back locale. If the fall-back locale itself is
285      * passed to the method, the method returns null to signal the end of the chain.
286      */
287     protected Locale getNextContentLocale(Locale locale, Set<Locale> checkedLocales) {
288         if(locale.equals(getFallbackLocale())){
289             return null;
290         }
291         Locale candidate = getNextLocale(locale);
292         if(!checkedLocales.contains(candidate)){
293             return candidate;
294         }
295         return getFallbackLocale();
296     }
297 
298     @Override
299     public boolean isEnabled() {
300         return this.enabled;
301     }
302 
303     public void setEnabled(boolean enabled) {
304         this.enabled = enabled;
305     }
306 
307     @Override
308     public Collection<Locale> getLocales() {
309         return this.locales.values();
310     }
311 
312     public void addLocale(LocaleDefinition ld) {
313         if (ld.isEnabled()) {
314             this.locales.put(ld.getId(), ld.getLocale());
315         }
316     }
317 
318     protected boolean isLocaleSupported(Locale locale) {
319         return locale != null && locales.containsKey(locale.toString());
320     }
321 
322     /**
323      * Checks if the nodedata field is empty.
324      */
325     protected boolean isEmpty(NodeData nd) {
326         if (nd != null && nd.isExist()) {
327             // TODO use a better way to find out if it is empty
328             return StringUtils.isEmpty(NodeDataUtil.getValueString(nd));
329         }
330         return true;
331     }
332 
333     public Locale getDefaultLocale() {
334         if(this.defaultLocale == null){
335             return getFallbackLocale();
336         }
337         return this.defaultLocale;
338     }
339 
340     public void setDefaultLocale(Locale defaultLocale) {
341         this.defaultLocale = defaultLocale;
342     }
343 }