1 18 19 package cowsultants.itracker.ejb.client.resources; 20 21 import java.text.DecimalFormat ; 22 import java.text.NumberFormat ; 23 import java.util.Locale ; 24 25 import cowsultants.itracker.ejb.client.util.Logger; 26 27 import org.apache.oro.text.regex.*; 28 29 33 public class MessageFormat { 34 private static final Perl5Matcher matcher = new Perl5Matcher(); 35 private static final PatternCompiler compiler = new Perl5Compiler(); 36 private static Pattern pattern; 37 38 static { 39 try { 40 pattern = compiler.compile("{(\\d+),?([\\w]*),?(.*?)}", Perl5Compiler.CASE_INSENSITIVE_MASK|Perl5Compiler.SINGLELINE_MASK); 41 } catch(MalformedPatternException mpe) { 42 Logger.logError("Invalid pattern specified. No formatting will be performed.", mpe); 43 pattern = null; 44 } 45 } 46 47 public static String format(String message, Object [] options) { 48 return format(message, options, ITrackerResources.getLocale()); 49 } 50 51 public static String format(String message, Object [] options, Locale locale) { 52 String output = message; 53 54 if(pattern != null) { 55 int currentOffset = 0; 56 StringBuffer buffer = new StringBuffer (); 57 PatternMatcherInput input = new PatternMatcherInput(message); 58 59 while(matcher.contains(input, pattern)) { 60 MatchResult result = null; 61 try { 62 result = matcher.getMatch(); 63 int numGroups = result.groups(); 64 int optionNumber = Integer.parseInt(result.group(1)); 65 66 buffer.append(message.substring(currentOffset, result.beginOffset(0))); 67 currentOffset = result.endOffset(0); 68 69 if(options != null && optionNumber < options.length && options[optionNumber] != null) { 70 if(numGroups > 2 && "number".equalsIgnoreCase(result.group(2))) { 71 try { 73 NumberFormat formatter = NumberFormat.getInstance(locale); 74 if(numGroups > 3) { 75 formatter = new DecimalFormat (result.group(3)); 76 } 77 buffer.append(formatter.format(Double.parseDouble(options[optionNumber].toString()))); 78 } catch(Exception e) { 79 Logger.logDebug("Unable to format " + options[optionNumber] + " as number.", e); 80 buffer.append(options[optionNumber].toString()); 81 } 82 } else { 83 buffer.append(options[optionNumber].toString()); 84 } 85 } 86 } catch(Exception e) { 87 Logger.logError("Unable to perform option replacement for option " + (result == null ? "NULL" : result.group(1))); 88 Logger.logDebug("Invalid option has current offest of " + currentOffset + " in message '" + message + "'", e); 89 } 90 } 91 92 if(buffer.length() > 0) { 93 buffer.append(message.substring(currentOffset)); 94 output = buffer.toString(); 95 } 96 } 97 98 return output; 99 } 100 101 } 102 | Popular Tags |