KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tonbeller > tbutils > res > ReplacingResourceProvider


1 package com.tonbeller.tbutils.res;
2
3 import java.util.Collection JavaDoc;
4 import java.util.regex.Matcher JavaDoc;
5 import java.util.regex.Pattern JavaDoc;
6
7 public class ReplacingResourceProvider implements ResourceProvider {
8   ResourceProvider decoree;
9   int maxRecurse = 10;
10   
11   // matches "${xxx}"
12
Pattern JavaDoc 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 JavaDoc getString(String JavaDoc key) {
23     String JavaDoc s = decoree.getString(key);
24     return replace(s);
25   }
26
27   public Collection JavaDoc keySet() {
28     return decoree.keySet();
29   }
30   
31   public String JavaDoc replace(String JavaDoc s) {
32     return replace(s, maxRecurse);
33   }
34   
35   public class RecursionOverflowException extends RuntimeException JavaDoc {
36     RecursionOverflowException(String JavaDoc s) {
37       super(s);
38     }
39   }
40
41   private String JavaDoc replace(String JavaDoc s, int recurseLevel) {
42     if (s == null)
43       return null;
44
45     // found pattern?
46
Matcher JavaDoc m = pattern.matcher(s);
47     if (!m.find())
48       return s;
49
50     StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
51     int start = 0;
52     do {
53       // append stuff before the "${"
54
sb.append(s.substring(start, m.start()));
55       start = m.end();
56
57       // escape: "$${xxx}" becomes "${xxx}" like ant
58
if (m.start() > 0 && s.charAt(m.start() - 1) == '$') {
59         sb.append(s.substring(m.start() + 1, m.end()));
60       } else {
61         // append replacement string
62
String JavaDoc key = m.group(1);
63         String JavaDoc 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 JavaDoc 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