* @return the variable storing the generated string.
*/
String generateStringVar(String string, Element elt)
throws Exception
{
CharBuffer cb = new CharBuffer();
int i = 0;
boolean first = true;
int length = string.length();
String strVar = "_xsl_str" + _unique++;
if (string.indexOf('{') < 0 &&
string.indexOf('}') < 0) {
print("String " + strVar + " = \"");
printString(string);
println("\";");
return strVar;
}
else if (string.lastIndexOf('{') == 0 &&
string.indexOf('}') == string.length() - 1) {
println("String " + strVar + " = \"\";");
string = string.substring(1, string.length() - 1);
addStringExpr(strVar, string, elt, true);
return strVar;
}
String cbVar = "_xsl_cb" + _unique++;
println("com.caucho.util.CharBuffer " + cbVar +
" = com.caucho.util.CharBuffer.allocate();");
for (; i < length; i++) {
char ch = string.charAt(i);
if (ch == '\n') {
cb.append("\\n");
}
else if (ch == '"') {
cb.append("\\\"");
}
else if (ch == '{' && i + 1 < length) {
// {{ is treated as a single {
if (string.charAt(i + 1) == '{') {
cb.append('{');
i++;
}
// the value is computed from an XPath expr
else {
// print the gathered text if any
if (cb.length() > 0)
println(cbVar + ".append(\"" + cb.toString() + "\");");
// scan the contents of '{' ... '}'
cb.clear();
for (i++; i < length && string.charAt(i) != '}'; i++)
cb.append(string.charAt(i));
// and add the results
addStringExpr(cbVar, cb.toString(), elt, false);
cb.clear();
first = false;
}
}
// }} is treated as a single }
else if (ch == '}' && i + 1 < length) {
if (string.charAt(i + 1) == '}') {
cb.append('}');
i++;
}
else
cb.append('}');
}
// <#= interpolates
else if (i + 2 < length && ch == '<' &&
string.charAt(i + 1) == '#' &&
string.charAt(i + 2) == '=') {
// print the gathered text if any
if (cb.length() > 0)
println(cbVar + ".append(\"" + cb.toString() + "\");");
// scan the contents of '<#=' ... '#>'
cb.clear();
for (i += 3;
i + 1 < length && string.charAt(i) != '#' &&
string.charAt(i + 1) != '>';
i++)
cb.append(string.charAt(i));
i++;
// and add the results
println(cbVar + ".append(" + cb + ");");
cb.clear();
first = false;
}
else
cb.append((char) ch);
}
// add any trailing text
if (cb.length() > 0)
println(cbVar + ".append(\"" + cb + "\");");
println("String " + strVar + " = " + cbVar + ".close();");
return strVar;