1 package org.apache.velocity.runtime.parser.node;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import org.apache.velocity.context.Context;
23 import org.apache.velocity.exception.MethodInvocationException;
24 import org.apache.velocity.runtime.parser.Token;
25
26
27
28
29
30
31
32
33 public class NodeUtils
34 {
35
36
37
38
39
40
41
42
43
44
45
46 public static String specialText(Token t)
47 {
48 StringBuffer specialText = new StringBuffer();
49
50 if (t.specialToken == null || t.specialToken.image.startsWith("##") )
51 {
52 return "";
53 }
54
55 Token tmp_t = t.specialToken;
56
57 while (tmp_t.specialToken != null)
58 {
59 tmp_t = tmp_t.specialToken;
60 }
61
62 while (tmp_t != null)
63 {
64 String st = tmp_t.image;
65
66 StringBuffer sb = new StringBuffer();
67
68 for(int i = 0; i < st.length(); i++)
69 {
70 char c = st.charAt(i);
71
72 if ( c == '#' || c == '$' )
73 {
74 sb.append( c );
75 }
76
77
78
79
80
81
82
83 if ( c == '\\')
84 {
85 boolean ok = true;
86 boolean term = false;
87
88 int j = i;
89 for( ok = true; ok && j < st.length(); j++)
90 {
91 char cc = st.charAt( j );
92
93 if (cc == '\\')
94 {
95
96
97
98 continue;
99 }
100 else if( cc == '$' )
101 {
102
103
104
105 term = true;
106 ok = false;
107 }
108 else
109 {
110
111
112
113 ok = false;
114 }
115 }
116
117 if (term)
118 {
119 String foo = st.substring( i, j );
120 sb.append( foo );
121 i = j;
122 }
123 }
124 }
125
126
127
128
129
130
131
132
133
134
135 specialText.append(sb.toString());
136
137 tmp_t = tmp_t.next;
138 }
139
140 return specialText.toString();
141 }
142
143
144
145
146
147
148
149 public static String tokenLiteral( Token t )
150 {
151 return specialText( t ) + t.image;
152 }
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170 public static String interpolate(String argStr, Context vars) throws MethodInvocationException
171 {
172 StringBuffer argBuf = new StringBuffer();
173
174 for (int cIdx = 0 ; cIdx < argStr.length();)
175 {
176 char ch = argStr.charAt(cIdx);
177
178 switch (ch)
179 {
180 case '$':
181 StringBuffer nameBuf = new StringBuffer();
182 for (++cIdx ; cIdx < argStr.length(); ++cIdx)
183 {
184 ch = argStr.charAt(cIdx);
185 if (ch == '_' || ch == '-'
186 || Character.isLetterOrDigit(ch))
187 nameBuf.append(ch);
188 else if (ch == '{' || ch == '}')
189 continue;
190 else
191 break;
192 }
193
194 if (nameBuf.length() > 0)
195 {
196 Object value = vars.get(nameBuf.toString());
197
198 if (value == null)
199 argBuf.append("$").append(nameBuf.toString());
200 else
201 argBuf.append(value.toString());
202 }
203 break;
204
205 default:
206 argBuf.append(ch);
207 ++cIdx;
208 break;
209 }
210 }
211
212 return argBuf.toString();
213 }
214 }