Home » lucene-3.0.1-src » org.apache.lucene.messages » [javadoc | source]

    1   package org.apache.lucene.messages;
    2   
    3   /**
    4    * Licensed to the Apache Software Foundation (ASF) under one or more
    5    * contributor license agreements.  See the NOTICE file distributed with
    6    * this work for additional information regarding copyright ownership.
    7    * The ASF licenses this file to You under the Apache License, Version 2.0
    8    * (the "License"); you may not use this file except in compliance with
    9    * the License.  You may obtain a copy of the License at
   10    *
   11    *     http://www.apache.org/licenses/LICENSE-2.0
   12    *
   13    * Unless required by applicable law or agreed to in writing, software
   14    * distributed under the License is distributed on an "AS IS" BASIS,
   15    * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   16    * See the License for the specific language governing permissions and
   17    * limitations under the License.
   18    */
   19   
   20   import java.lang.reflect.Field;
   21   import java.lang.reflect.Modifier;
   22   import java.security.AccessController;
   23   import java.security.PrivilegedAction;
   24   import java.text.MessageFormat;
   25   import java.util.HashMap;
   26   import java.util.Iterator;
   27   import java.util.Locale;
   28   import java.util.Map;
   29   import java.util.MissingResourceException;
   30   import java.util.ResourceBundle;
   31   
   32   /**
   33    * MessageBundles classes extend this class, to implement a bundle.
   34    * 
   35    * For Native Language Support (NLS), system of software internationalization.
   36    * 
   37    * This interface is similar to the NLS class in eclipse.osgi.util.NLS class -
   38    * initializeMessages() method resets the values of all static strings, should
   39    * only be called by classes that extend from NLS (see TestMessages.java for
   40    * reference) - performs validation of all message in a bundle, at class load
   41    * time - performs per message validation at runtime - see NLSTest.java for
   42    * usage reference
   43    * 
   44    * MessageBundle classes may subclass this type.
   45    */
   46   public class NLS {
   47   
   48     private static Map<String, Class<Object>> bundles = 
   49       new HashMap<String, Class<Object>>(0);
   50   
   51     protected NLS() {
   52       // Do not instantiate
   53     }
   54   
   55     public static String getLocalizedMessage(String key) {
   56       return getLocalizedMessage(key, Locale.getDefault());
   57     }
   58   
   59     public static String getLocalizedMessage(String key, Locale locale) {
   60       Object message = getResourceBundleObject(key, locale);
   61       if (message == null) {
   62         return "Message with key:" + key + " and locale: " + locale
   63             + " not found.";
   64       }
   65       return message.toString();
   66     }
   67   
   68     public static String getLocalizedMessage(String key, Locale locale,
   69         Object... args) {
   70       String str = getLocalizedMessage(key, locale);
   71   
   72       if (args.length > 0) {
   73         str = MessageFormat.format(str, args);
   74       }
   75   
   76       return str;
   77     }
   78   
   79     public static String getLocalizedMessage(String key, Object... args) {
   80       return getLocalizedMessage(key, Locale.getDefault(), args);
   81     }
   82   
   83     /**
   84      * Initialize a given class with the message bundle Keys Should be called from
   85      * a class that extends NLS in a static block at class load time.
   86      * 
   87      * @param bundleName
   88      *          Property file with that contains the message bundle
   89      * @param clazz
   90      *          where constants will reside
   91      */
   92     @SuppressWarnings("unchecked")
   93     protected static void initializeMessages(String bundleName, Class clazz) {
   94       try {
   95         load(clazz);
   96         if (!bundles.containsKey(bundleName))
   97           bundles.put(bundleName, clazz);
   98       } catch (Throwable e) {
   99         // ignore all errors and exceptions
  100         // because this function is supposed to be called at class load time.
  101       }
  102     }
  103   
  104     private static Object getResourceBundleObject(String messageKey, Locale locale) {
  105   
  106       // slow resource checking
  107       // need to loop thru all registered resource bundles
  108       for (Iterator<String> it = bundles.keySet().iterator(); it.hasNext();) {
  109         Class<Object> clazz = bundles.get(it.next());
  110         ResourceBundle resourceBundle = ResourceBundle.getBundle(clazz.getName(),
  111             locale);
  112         if (resourceBundle != null) {
  113           try {
  114             Object obj = resourceBundle.getObject(messageKey);
  115             if (obj != null)
  116               return obj;
  117           } catch (MissingResourceException e) {
  118             // just continue it might be on the next resource bundle
  119           }
  120         }
  121       }
  122       // if resource is not found
  123       return null;
  124     }
  125   
  126     /**
  127      * @param clazz
  128      */
  129     private static void load(Class<Object> clazz) {
  130       final Field[] fieldArray = clazz.getDeclaredFields();
  131   
  132       boolean isFieldAccessible = (clazz.getModifiers() & Modifier.PUBLIC) != 0;
  133   
  134       // build a map of field names to Field objects
  135       final int len = fieldArray.length;
  136       Map<String, Field> fields = new HashMap<String, Field>(len * 2);
  137       for (int i = 0; i < len; i++) {
  138         fields.put(fieldArray[i].getName(), fieldArray[i]);
  139         loadfieldValue(fieldArray[i], isFieldAccessible, clazz);
  140       }
  141     }
  142   
  143     /**
  144      * @param field
  145      * @param isFieldAccessible
  146      */
  147     private static void loadfieldValue(Field field, boolean isFieldAccessible,
  148         Class<Object> clazz) {
  149       int MOD_EXPECTED = Modifier.PUBLIC | Modifier.STATIC;
  150       int MOD_MASK = MOD_EXPECTED | Modifier.FINAL;
  151       if ((field.getModifiers() & MOD_MASK) != MOD_EXPECTED)
  152         return;
  153   
  154       // Set a value for this empty field.
  155       if (!isFieldAccessible)
  156         makeAccessible(field);
  157       try {
  158         field.set(null, field.getName());
  159         validateMessage(field.getName(), clazz);
  160       } catch (IllegalArgumentException e) {
  161         // should not happen
  162       } catch (IllegalAccessException e) {
  163         // should not happen
  164       }
  165     }
  166   
  167     /**
  168      * @param key
  169      *          - Message Key
  170      */
  171     private static void validateMessage(String key, Class<Object> clazz) {
  172       // Test if the message is present in the resource bundle
  173       try {
  174         ResourceBundle resourceBundle = ResourceBundle.getBundle(clazz.getName(),
  175             Locale.getDefault());
  176         if (resourceBundle != null) {
  177           Object obj = resourceBundle.getObject(key);
  178           if (obj == null)
  179             System.err.println("WARN: Message with key:" + key + " and locale: "
  180                 + Locale.getDefault() + " not found.");
  181         }
  182       } catch (MissingResourceException e) {
  183         System.err.println("WARN: Message with key:" + key + " and locale: "
  184             + Locale.getDefault() + " not found.");
  185       } catch (Throwable e) {
  186         // ignore all other errors and exceptions
  187         // since this code is just a test to see if the message is present on the
  188         // system
  189       }
  190     }
  191   
  192     /*
  193      * Make a class field accessible
  194      */
  195     @SuppressWarnings("unchecked")
  196     private static void makeAccessible(final Field field) {
  197       if (System.getSecurityManager() == null) {
  198         field.setAccessible(true);
  199       } else {
  200         AccessController.doPrivileged(new PrivilegedAction() {
  201           public Object run() {
  202             field.setAccessible(true);
  203             return null;
  204           }
  205         });
  206       }
  207     }
  208   }

Home » lucene-3.0.1-src » org.apache.lucene.messages » [javadoc | source]