1 34 35 36 package com.micronova.util; 37 38 import java.util.regex.*; 39 import java.util.*; 40 41 42 43 public class Template 44 { 45 46 47 public static String escapeGroup(String x) 48 { 49 StringBuffer in = new StringBuffer (x); 50 StringBuffer out = new StringBuffer (); 51 52 boolean isEscaped = false; 53 54 for (int i = 0; i < in.length(); i ++) 55 { 56 char c = in.charAt(i); 57 58 if (c == '$') 59 { 60 out.append("\\$"); 61 } 62 else if (c == '\\') 63 { 64 out.append("\\\\"); 65 } 66 else 67 { 68 out.append(c); 69 } 70 } 71 72 return out.toString(); 73 } 74 75 76 77 public static Object render(String template, Pattern pattern, int groupIndex, ObjectSource objectSource, Object objectSourceClient, boolean isRecursive, boolean allowGroup) throws Exception 78 { 79 int templateLength = template.length(); 80 81 StringBuffer output = new StringBuffer (); 82 83 Matcher matcher = pattern.matcher(template); 84 85 while (matcher.find()) 86 { 87 String group = matcher.group(groupIndex); 88 89 Object replacement = objectSource.getObject(objectSourceClient, group); 90 91 if (replacement != null) 92 { 93 if (isRecursive) 94 { 95 replacement = render(replacement.toString(), pattern, groupIndex, objectSource, objectSourceClient, isRecursive, allowGroup); 96 } 97 } 98 99 101 if ((matcher.start() == 0) && (matcher.end() == templateLength)) 102 { 103 return replacement; 104 } 105 106 if (replacement != null) 107 { 108 if (!allowGroup) 109 { 110 replacement = escapeGroup(replacement.toString()); 111 } 112 } 113 else 114 { 115 replacement = ""; 116 } 117 118 matcher.appendReplacement(output, (String )replacement); 119 } 120 121 matcher.appendTail(output); 122 123 return output.toString(); 124 } 125 } 126 | Popular Tags |