1 15 package org.apache.hivemind.impl; 16 17 import java.util.Locale ; 18 import java.util.MissingResourceException ; 19 import java.util.ResourceBundle ; 20 21 import org.apache.commons.logging.Log; 22 import org.apache.hivemind.util.Defense; 23 24 30 public class MessageFormatter extends AbstractMessages 31 { 32 private final ResourceBundle _bundle; 33 34 public MessageFormatter(ResourceBundle bundle) 35 { 36 Defense.notNull(bundle, "bundle"); 37 _bundle = bundle; 38 } 39 40 44 public MessageFormatter(Log log, ResourceBundle bundle) 45 { 46 this(bundle); 47 } 48 49 55 public MessageFormatter(Class referenceClass) 56 { 57 this(referenceClass, getStringsName(referenceClass)); 58 } 59 60 public MessageFormatter(Class referenceClass, String name) 61 { 62 this(getResourceBundleName(referenceClass, name)); 63 } 64 65 69 public MessageFormatter(Log log, Class referenceClass, String name) 70 { 71 this(referenceClass, name); 72 } 73 74 public MessageFormatter(String bundleName) 75 { 76 this(ResourceBundle.getBundle(bundleName)); 77 } 78 79 83 public MessageFormatter(Log log, String bundleName) 84 { 85 this(bundleName); 86 } 87 88 protected String findMessage(String key) 89 { 90 try 91 { 92 return _bundle.getString(key); 93 } 94 catch (MissingResourceException ex) 95 { 96 return null; 97 } 98 } 99 100 protected Locale getLocale() 101 { 102 return Locale.getDefault(); 103 } 104 105 private static String getStringsName(Class referenceClass) 106 { 107 String className = referenceClass.getName(); 108 109 int lastDotIndex = className.lastIndexOf('.'); 110 111 String justClass = className.substring(lastDotIndex + 1); 112 113 int mpos = justClass.indexOf("Messages"); 114 115 return justClass.substring(0, mpos) + "Strings"; 116 } 117 118 private static String getResourceBundleName(Class referenceClass, String name) 119 { 120 String packageName = null; 121 if (referenceClass.getPackage() != null) 122 { 123 packageName = referenceClass.getPackage().getName(); 124 } 125 else 126 { 127 final int lastDotIndex = referenceClass.getName().lastIndexOf('.'); 128 packageName = (lastDotIndex == -1 ? "" : referenceClass.getName().substring( 129 0, 130 lastDotIndex)); 131 132 } 133 return packageName.equals("") ? name : packageName + "." + name; 134 } 135 } | Popular Tags |