View Javadoc
1   /**
2    * Copyright 2011, Aiki IT, FotoRenamer
3    * <p/>
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * <p/>
8    * http://www.apache.org/licenses/LICENSE-2.0
9    * <p/>
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package de.aikiit.fotorenamer.util;
17  
18  import com.google.common.base.Strings;
19  import lombok.AccessLevel;
20  import lombok.NoArgsConstructor;
21  import org.apache.logging.log4j.LogManager;
22  import org.apache.logging.log4j.Logger;
23  
24  import java.text.MessageFormat;
25  import java.util.Locale;
26  import java.util.MissingResourceException;
27  import java.util.ResourceBundle;
28  
29  /**
30   * Helper to deal with localizations and ease the usage of
31   * resource bundles within fotorenamer.
32   *
33   * @author hirsch
34   * @version 23.08.11
35   */
36  @NoArgsConstructor(access = AccessLevel.PRIVATE)
37  public final class LocalizationHelper {
38  
39      /**
40       * Logger.
41       */
42      private static final Logger LOG =
43              LogManager.getLogger(LocalizationHelper.class);
44  
45      /**
46       * ResourceBundle used for this application.
47       */
48      private static final String BASE_NAME = "fotorenamer";
49      private static final Locale FALLBACK_LOCALE = Locale.GERMANY;
50  
51      private static ResourceBundle BUNDLE;
52      private static Locale LOCALE;
53      private static MessageFormat FORMAT;
54  
55      static {
56          setLocale();
57      }
58  
59      /**
60       * Set locale depending on system properties, in case of errors fallback is Locale.GERMANY.
61       */
62      public static void setLocale() {
63          String userLanguage = System.getProperty("user.language");
64          String userCountry = System.getProperty("user.country");
65  
66          LOG.info(String.format("Your system emits the following l10n-properties: language=%s, country=%s", userLanguage, userCountry));
67  
68          if (Strings.isNullOrEmpty(userLanguage) || Strings.isNullOrEmpty(userCountry)) {
69              LOCALE = FALLBACK_LOCALE;
70              LOG.info("Falling back to locale " + LOCALE);
71          } else {
72              LOCALE = new Locale(userLanguage, userCountry);
73              LOG.info("Setting locale to " + LOCALE);
74          }
75  
76          BUNDLE = ResourceBundle.getBundle(BASE_NAME, LOCALE);
77          FORMAT = new MessageFormat("");
78          FORMAT.setLocale(LOCALE);
79      }
80  
81      /**
82       * @return the currently set Locale of this application. Fallback is Locale.GERMANY.
83       */
84      public static Locale getLocale() {
85          if (LOCALE == null) {
86              LOG.warn("Returning fallback Locale for Germany - please make sure you've configured your environment correctly via system properties 'user.country'/'user.language'.");
87              return FALLBACK_LOCALE;
88          }
89          return LOCALE;
90      }
91  
92      /**
93       * @return the currently set language
94       */
95      public static String getLanguage() {
96          return getLocale().getLanguage();
97      }
98  
99      /**
100      * Helper function to retrieve a given key
101      * from the underlying resource bundle.
102      *
103      * @param key Key to retrieve from the bundle,
104      *            e.g. <i>fotorenamer.foo.title</i>
105      * @return Returns the value from the bundle.
106      */
107     public static String getBundleString(final String key) {
108         LOG.debug("Retrieving key " + key);
109         try {
110             return BUNDLE.getString(key);
111         } catch (MissingResourceException mre) {
112             LOG.error("Retrieving unknown key " + key + ". Please fix your property files.");
113             return key;
114         }
115         // l18n basics:
116         // http://www.kodejava.org/examples/220.html
117         // l18n buttons:
118         // http://www.java2s.com/Code/Java/I18N/Createonebuttoninternationalizedly.htm
119         // l18n with parameters:
120         // http://www.java2s.com/Code/Java/I18N/ResourceBundlewithparameterposition.htm
121         // parameters are a but uneasier than with grails -
122         // http://download.oracle.com/javase/tutorial/i18n/format/messageFormat.html
123         // encoding issues / eclipse plugin:
124         // http://stackoverflow.com/questions/863838/problem-with-java-properties-utf8-encoding-in-eclipse
125     }
126 
127     /**
128      * Helper function to retrieve a given key
129      * from the underlying resource bundle while
130      * applying localization parameters.
131      *
132      * @param key        Key to retrieve from the bundle,
133      *                   e.g. <i>fotorenamer.foo.parameteredtitle</i>.
134      * @param parameters Object array with all parameters.
135      * @return Returns the value from the bundle
136      * with the given parameters applied.
137      * @see <a href="http://download.oracle.com/javase/tutorial/i18n/format/messageFormat.html">
138      * I18N-tutorial</a>
139      */
140     public static String getParameterizedBundleString(final String key, final Object... parameters) {
141         LOG.debug("Applying " + ((parameters == null) ? null : parameters
142                 .length) + " parameters to " + key);
143         FORMAT.applyPattern(getBundleString(key));
144         return FORMAT.format(parameters);
145     }
146 
147     /**
148      * Helper method to prevent CRLF injection in logs.
149      *
150      * @param input any input
151      * @return input without CRLF.
152      */
153     public static String removeCrLf(final String input) {
154         if (!Strings.isNullOrEmpty(input)) {
155             return input.replaceAll("[\r\n]", "");
156         }
157         return input;
158     }
159 }