1 package com.tonbeller.tbutils.res; 2 3 import java.util.Collection ; 4 import java.util.regex.Matcher ; 5 import java.util.regex.Pattern ; 6 7 public class ReplacingResourceProvider implements ResourceProvider { 8 ResourceProvider decoree; 9 int maxRecurse = 10; 10 11 Pattern pattern = Pattern.compile("\\$\\{([a-zA-Z0-9_\\.]+)\\}"); 13 14 public ReplacingResourceProvider(ResourceProvider decoree) { 15 this.decoree = decoree; 16 } 17 18 public void close() { 19 decoree.close(); 20 } 21 22 public String getString(String key) { 23 String s = decoree.getString(key); 24 return replace(s); 25 } 26 27 public Collection keySet() { 28 return decoree.keySet(); 29 } 30 31 public String replace(String s) { 32 return replace(s, maxRecurse); 33 } 34 35 public class RecursionOverflowException extends RuntimeException { 36 RecursionOverflowException(String s) { 37 super(s); 38 } 39 } 40 41 private String replace(String s, int recurseLevel) { 42 if (s == null) 43 return null; 44 45 Matcher m = pattern.matcher(s); 47 if (!m.find()) 48 return s; 49 50 StringBuffer sb = new StringBuffer (); 51 int start = 0; 52 do { 53 sb.append(s.substring(start, m.start())); 55 start = m.end(); 56 57 if (m.start() > 0 && s.charAt(m.start() - 1) == '$') { 59 sb.append(s.substring(m.start() + 1, m.end())); 60 } else { 61 String key = m.group(1); 63 String val = decoree.getString(key); 64 if (val != null) { 65 if (recurseLevel > 0) 66 val = replace(val, recurseLevel - 1); 67 else 68 throw new RecursionOverflowException(val); 69 sb.append(val); 70 } 71 else 72 sb.append(s.substring(m.start(), m.end())); 73 } 74 } while (m.find()); 75 sb.append(s.substring(start, s.length())); 76 77 return sb.toString(); 78 } 79 80 public void dump(Dumper d) { 81 decoree.dump(d); 82 } 83 84 public String getName() { 85 return getClass().getName(); 86 } 87 88 public int getMaxRecurse() { 89 return maxRecurse; 90 } 91 92 public void setMaxRecurse(int maxRecurse) { 93 this.maxRecurse = maxRecurse; 94 } 95 96 97 } 98 | Popular Tags |