1 25 26 package org.objectweb.easybeans.i18n; 27 28 import java.text.MessageFormat ; 29 import java.util.HashMap ; 30 import java.util.Locale ; 31 import java.util.Map ; 32 import java.util.MissingResourceException ; 33 import java.util.ResourceBundle ; 34 35 41 public final class I18n { 42 43 46 private static final String RESOURCE_BUNDLE_NAME = "I18n"; 47 48 52 private static final String NO_PACKAGE = "NO_PACKAGE"; 53 54 57 private static Map <String , I18n> bundles = null; 58 59 62 private ResourceBundle resourceBundle = null; 63 64 69 private I18n(final String packageName, final ClassLoader cl) { 70 71 String bundleName = packageName + "." + RESOURCE_BUNDLE_NAME; 72 73 try { 75 Locale locale = Locale.getDefault(); 76 resourceBundle = ResourceBundle.getBundle(bundleName, locale, cl); 77 } catch (MissingResourceException mre) { 78 resourceBundle = null; 79 } 80 } 81 82 87 public static I18n getInstance(final Class c) { 88 return getInstance(c, Thread.currentThread().getContextClassLoader()); 89 } 90 91 97 public static I18n getInstance(final Class c, final ClassLoader cl) { 98 Package p = c.getPackage(); 99 if (p != null) { 100 return getInstance(p.getName(), cl); 101 } 102 return getInstance(NO_PACKAGE, cl); 103 } 104 105 110 public static I18n getInstance(final String packageName) { 111 return getInstance(packageName, Thread.currentThread().getContextClassLoader()); 112 } 113 114 120 public static I18n getInstance(final String packageName, final ClassLoader cl) { 121 if (bundles == null) { 122 bundles = new HashMap <String , I18n>(); 123 } 124 125 I18n i18n = bundles.get(packageName); 126 if (i18n != null) { 127 return i18n; 128 } 129 130 i18n = new I18n(packageName, cl); 131 bundles.put(packageName, i18n); 132 return i18n; 133 } 134 135 141 public String getMessage(final String key, final Object ... objs) { 142 String pattern = key; 143 if (resourceBundle != null) { 145 try { 146 pattern = resourceBundle.getString(key); 147 } catch (MissingResourceException mre) { 148 pattern = key; 150 } 151 } 152 try { 153 return MessageFormat.format(pattern, objs); 154 } catch (IllegalArgumentException iae) { 155 return key; 156 } 157 } 158 159 } 160 161 | Popular Tags |