1 23 package com.sun.enterprise.admin.util; 24 25 37 38 39 public class MessageFormatter implements IStringSource 40 { 41 44 public MessageFormatter(IStringSource source ) 45 { 46 setSource(source); 47 } 48 49 50 53 public void setSource(IStringSource source) 54 { 55 mSource = source; 58 } 59 60 61 64 public IStringSource getSource() 65 { 66 Assert.assertit((mSource!=null), "mSource"); 67 return mSource; 68 } 69 70 71 76 public String getString(String lookupKey) 77 { 78 return(mSource.getString(lookupKey)); 80 } 81 82 83 94 public static String format(String base, Object [] toInsert) 95 { 96 99 101 if(toInsert == null || toInsert.length <= 0) 102 return null; 103 104 String ret = base; 105 106 for(int i = 0; i < toInsert.length; i++) 107 { 108 String token = makeToken(i + 1); 109 String replace = toInsert[i].toString(); 110 ret = replaceToken(ret, token, replace); 111 112 if(ret == null || ret.length() <= 0) 113 return null; 114 } 115 return ret; 116 } 117 118 119 124 public static String format(String base, Object o1) 125 { 126 return format(base, new Object [] {o1}); 127 } 128 129 130 136 public static String format(String base, Object o1, Object o2) 137 { 138 return format(base, new Object [] {o1, o2}); 139 } 140 141 142 149 public static String format(String base, Object o1, Object o2, Object o3) 150 { 151 return format(base, new Object [] {o1, o2, o3}); 152 } 153 154 155 162 public String getAndFormat(String key, Object o1) 163 { 164 return getAndFormat(key, new Object [] { o1} ); 165 } 166 167 168 176 public String getAndFormat(String key, Object o1, Object o2) 177 { 178 return getAndFormat(key, new Object [] { o1, o2} ); 179 } 180 181 182 191 public String getAndFormat(String key, Object o1, Object o2, Object o3) 192 { 193 return getAndFormat(key, new Object [] { o1, o2, o3} ); 194 } 195 196 197 204 public String getAndFormat(String key, Object [] toInsert) 205 { 206 return format(getString(key), toInsert); 207 } 208 209 210 private static String makeToken(int num) 211 { 212 218 return "{" + num + "}"; 219 } 220 221 222 private static String replaceToken(String s, String token, String replace) 223 { 224 227 228 if(s == null || s.length() <= 0 || token == null || token.length() <= 0) 229 return s; 230 231 int index = s.indexOf(token); 232 233 if(index < 0) 234 return s; 235 236 int tokenLength = token.length(); 237 String ret = s.substring(0, index); 238 ret += replace; 239 ret += s.substring(index + tokenLength); 240 241 return ret; 242 } 243 244 245 private IStringSource mSource = null; 246 247 250 public static void main(String [] notUsed) 251 { 252 String test2A = "hello {1}, How are {2}?"; 253 String test2AResult = format(test2A, "Carbon-based lifeform", "you"); 254 Debug.println("INPUT: " + test2A + "\nOUTPUT: " + test2AResult); 255 } 256 } 257 258 259 | Popular Tags |