use of cn.bran.japid.template.JapidTemplate in project Japid by branaway.
the class JapidAbstractCompiler method script.
protected void script(String token) {
String[] lines = new String[] { token };
if (token.indexOf(NEW_LINE) > -1) {
lines = parser.getToken().split(NEW_LINE);
}
for (int i = 0; i < lines.length; i++) {
// .trim();
String line = lines[i];
if (lines.length > 1 && line.trim().length() == 0)
line = "//japid compiler: artificial line to avoid being treated as a terminating line";
if (startsWithIgnoreSpace(line, "import")) {
getTemplateClassMetaData().addImportLine(line);
} else if (startsWithIgnoreSpace(line, "//")) {
// ignore
} else if (startsWithIgnoreSpace(line, "extends")) {
String layout = line.trim().substring("extends".length()).trim();
// remove quotes if they present
boolean hasParam = false;
int p = 0;
for (; p < layout.length(); p++) {
char c = layout.charAt(p);
if (c == ' ' || c == '\t' || c == '(') {
hasParam = true;
break;
}
}
if (!hasParam) {
layout = layout.replace("'", "");
layout = layout.replace("\"", "");
layout = removeEndingString(layout, ";");
layout = removeEndingString(layout, HTML);
layout = removeEndingString(layout, "/");
if (layout.startsWith(".")) {
// new feature allow extends .sub.layout.html
if (layout.startsWith("./")) {
layout = getTemplateClassMetaData().packageName + layout.substring(1);
} else {
layout = getTemplateClassMetaData().packageName + layout;
}
}
getTemplateClassMetaData().superClass = layout.replace('/', '.');
} else {
String layoutName = layout.substring(0, p);
layoutName = layoutName.replace("'", "");
layoutName = layoutName.replace("\"", "");
layoutName = layoutName.replace('/', '.');
layoutName = removeEndingString(layoutName, HTML);
try {
// due to similarity, let's borrow a tag parsing
Tag tag = new TagInvocationLineParser().parse(layoutName + layout.substring(p));
if (tag.tagName.startsWith(".")) {
// partial path, use current package as the root and
// append the path to it
tag.tagName = getTemplateClassMetaData().packageName + tag.tagName;
}
getTemplateClassMetaData().superClass = tag.tagName;
getTemplateClassMetaData().superClassRenderArgs = tag.args;
} catch (RuntimeException e) {
throw new JapidCompilationException(template, parser.getLineNumber(), e.getMessage());
}
}
} else if (startsWithIgnoreSpace(line, "contentType")) {
// TODO: should also take standard tag name: Content-Type
String contentType = line.trim().substring("contentType".length()).trim().replace("'", "").replace("\"", "");
if (contentType.endsWith(";"))
contentType = contentType.substring(0, contentType.length());
getTemplateClassMetaData().setContentType(contentType);
} else if (startsWithIgnoreSpace(line, "setHeader")) {
String headerkv = line.trim().substring("setHeader".length()).trim();
String[] split = headerkv.split("[ |\t]");
if (split.length < 2) {
throw new JapidCompilationException(template, parser.getLineNumber(), "setHeaader must take a key and a value string");
}
String name = split[0];
String value = headerkv.substring(name.length()).trim();
getTemplateClassMetaData().setHeader(name, value);
} else if (startsWithIgnoreSpace(line, ARGS)) {
String args = line.trim().substring(ARGS.length()).trim();
templateArgs(args);
} else if (startsWithIgnoreSpace(line, "trim")) {
String sw = line.trim().substring("trim".length()).trim().replace(";", "").replace("'", "").replace("\"", "");
if ("on".equals(sw) || "true".equals(sw)) {
getTemplateClassMetaData().trimStaticContent();
}
} else if (startsWithIgnoreSpace(line, "stopwatch")) {
String sw = line.trim().substring("stopwatch".length()).trim().replace(";", "").replace("'", "").replace("\"", "");
if ("on".equals(sw) || "yes".equals(sw) || "true".equals(sw))
getTemplateClassMetaData().turnOnStopwatch();
} else if (startsWithIgnoreSpace(line, "tracefile")) {
String sw = line.trim().substring("tracefile".length()).trim().replace(";", "").replace("'", "").replace("\"", "");
if ("on".equals(sw) || "yes".equals(sw) || "true".equals(sw))
getTemplateClassMetaData().turnOnTraceFile();
else
getTemplateClassMetaData().turnOffTraceFile();
} else if (startsWithIgnoreSpace(line, "log") || line.trim().equals("log")) {
String args = line.trim().substring("log".length()).trim().replace(";", "");
if (args.trim().length() == 0)
args = "\"\"";
String logLine = "System.out.println(\"" + this.template.name.replace('\\', '/') + "(line " + (parser.getLineNumber() + i) + "): \" + " + args + ");";
println(logLine);
} else if (startsWithIgnoreSpace(line, "invoke")) {
String args = line.trim().substring("invoke".length()).trim().replace(";", "");
doActionInvokeDirective(args);
markLine(parser.getLineNumber() + i);
println();
} else if (startsWith(line, "a")) {
// `a == `invoke, the a must be
// the first char to avoid
// collision
String args = line.substring(2).trim().replace(";", "");
doActionInvokeDirective(args);
markLine(parser.getLineNumber() + i);
println();
} else if (startsWithIgnoreSpace(line, "suppressNull") || line.trim().equals("suppressNull")) {
String npe = line.trim().substring("suppressNull".length()).trim().replace(";", "").replace("'", "").replace("\"", "");
if ("on".equals(npe) || "yes".equals(npe) || "".equals(npe))
getTemplateClassMetaData().suppressNull();
} else if (line.trim().equals("abstract")) {
getTemplateClassMetaData().setAbstract(true);
} else if (startsWithIgnoreSpace(line, "tag")) {
String tagline = line.trim().substring(4);
doTagDirective(tagline);
} else if (startsWith(line, "t")) {
// `t == `tag, the t must be the
// first char to avoid collision
String tagline = line.substring(2);
doTagDirective(tagline);
} else if (startsWithIgnoreSpace(line, "each") || startsWithIgnoreSpace(line, "Each")) {
// support one line type of tag invocation.
Tag tag = buildTagDirective(line);
tag.tagName = "Each";
tag.hasBody = true;
startTag(tag);
} else if (startsWithIgnoreSpace(line, "set")) {
Tag set = buildTagDirective(line);
if (line.contains(":") || line.contains("="))
set.hasBody = false;
else
set.hasBody = true;
startTag(set);
if (!set.hasBody) {
// one liner.
set = popStack();
}
} else if (startsWithIgnoreSpace(line, "get")) {
Tag get = buildTagDirective(line);
get.hasBody = false;
startTag(get);
get = popStack();
} else if (startsWithIgnoreSpace(line, "def")) {
// a function definition block
Tag get = buildTagDirective(line);
get.hasBody = true;
startTag(get);
} else if (startsWithIgnoreSpace(line, INCLUDE)) {
// the include directive
// compile the target and include the layout part in the current output flow
String target = parseInclude(line);
String src;
try {
src = DirUtil.readFileAsString(target);
JapidTemplate template = new JapidTemplate(target, src);
JapidAbstractCompiler c = JapidTemplateTransformer.selectCompiler(src);
c.setUseWithPlay(getTemplateClassMetaData().useWithPlay);
c.compile(template);
String jsrc = template.javaSource;
getTemplateClassMetaData().merge(c.getTemplateClassMetaData());
println("/* include %s */", target);
String code = extractRenderingCode(jsrc);
println(code);
println("/* end of %s */", target);
} catch (Exception e) {
throw new JapidCompilationException(template, parser.getLineNumber() + i, "The target of include does not exist: " + target + ". " + e);
}
} else if (line.trim().startsWith("noplay")) {
// template is play independent
getTemplateClassMetaData().useWithPlay = this.useWithPlay = false;
} else if (line.trim().equalsIgnoreCase("xml")) {
// template is play independent
getTemplateClassMetaData().setContentType(MimeTypeEnum.xml.header);
} else if (line.trim().equalsIgnoreCase("json")) {
// template is play independent
getTemplateClassMetaData().setContentType(MimeTypeEnum.json.header);
} else if (line.trim().equalsIgnoreCase("css")) {
// template is play independent
getTemplateClassMetaData().setContentType(MimeTypeEnum.css.header);
} else if (line.trim().equalsIgnoreCase("txt") || line.trim().equalsIgnoreCase("text")) {
// template is play independent
getTemplateClassMetaData().setContentType(MimeTypeEnum.txt.header);
} else if (line.trim().equalsIgnoreCase("js") || line.trim().equalsIgnoreCase("javascript")) {
// template is play independent
getTemplateClassMetaData().setContentType(MimeTypeEnum.js.header);
} else if (line.trim().startsWith("verbatim")) {
parser.verbatim = true;
Tag get = buildTagDirective(line);
get.hasBody = true;
startTag(get);
} else if (startsWithIgnoreSpace(line, "if")) {
// `if expr {, the last { is optional
String expr = line.trim();
String clause = expr.substring(2);
if (JavaSyntaxTool.isIf(clause)) {
print(expr);
markLine(parser.getLineNumber() + i);
println();
} else if (JavaSyntaxTool.isOpenIf(clause)) {
handleOpenIf(i, expr);
}
// String expr = line.trim();
// if (expr.matches(OPEN_IF_PATTERN1)) {
// handleOpenIf(i, expr);
// } else {
// // plain Java if
// // wait! but may be open due to regex limitation.
// Matcher m = IF_PATTERN.matcher(expr);
// if (m.matches()){
// String condition = m.group(1);
// if (JavaSyntaxTool.isValidExpr(condition)){
// // true classic if
// print(expr);
// markLine(parser.getLineNumber() + i);
// println();
// }
// else {
// // is actually open if
// handleOpenIf(i, expr);
// }
// }
// }
} else if (line.matches(ELSE_IF_PATTERN_STRING)) {
// semi open
String expr = line.trim();
Matcher matcher = ELSE_IF_PATTERN.matcher(line);
if (matcher.matches()) {
expr = matcher.group(1).trim();
boolean negative = expr.startsWith("!");
if (negative)
expr = expr.substring(1).trim();
String cleanExpr = removeEndingString(expr, "{");
verifyExpr(cleanExpr);
expr = "} else if(" + (negative ? "!" : "") + "asBoolean(" + cleanExpr + ")) {";
}
print(expr);
markLine(parser.getLineNumber() + i);
println();
} else if (line.matches(OPEN_ELSE_IF_PATTERN_STRING)) {
// open
String expr = line.trim();
Matcher matcher = OPEN_ELSE_IF_PATTERN.matcher(line);
if (matcher.matches()) {
expr = matcher.group(1).trim();
boolean negative = expr.startsWith("!");
if (negative) {
handleOpenElseIf(i, expr.substring(1), negative);
} else {
if (expr.startsWith("(") && expr.endsWith(")")) {
// test if the part is classic if
String ex = expr.substring(1, expr.length() - 1);
if (JavaSyntaxTool.isValidExpr(ex)) {
//OK, the insider is a valid expression (better be boolean!)
// end previous if shadow and star a new one
Tag tagShadow = tagsStackShadow.peek();
if (tagShadow instanceof TagIf) {
tagsStackShadow.pop();
// to close an open if
// start a new if
Tag.TagIf iftag = new Tag.TagIf(expr, parser.getLineNumber());
pushToStack(iftag);
expr = "} else if(" + ex + ")) {";
print(expr);
markLine(parser.getLineNumber() + i);
println();
} else {
throw new JapidCompilationException(template, parser.getLineNumber() + i, "the open \"else if\" statement is not properly matched to a previous if");
}
} else {
handleOpenElseIf(i, expr, negative);
}
} else {
handleOpenElseIf(i, expr, negative);
}
}
} else {
throw new RuntimeException("JapidAbstractCompiler bug: Should never be here!");
}
} else if (line.matches(OPEN_ELSE_STRING)) {
Tag tagShadow = tagsStackShadow.peek();
if (tagShadow instanceof TagIf) {
tagsStackShadow.pop();
// to close an open if
// start a new if
print("} else {");
markLine(parser.getLineNumber() + i);
println();
Tag.TagIf iftag = new Tag.TagIf("", parser.getLineNumber());
pushToStack(iftag);
} else {
throw new JapidCompilationException(template, parser.getLineNumber() + i, "the open \"else\" statement is not properly matched to a previous if");
}
} else if (line.trim().matches(OPEN_FOR_PATTERN_STRING)) {
// simply replace it with a "each" tag call
String expr = line.trim();
Matcher matcher = OPEN_FOR_PATTERN.matcher(expr);
if (matcher.matches()) {
String instanceDecl = matcher.group(1);
if (!JavaSyntaxTool.isValidSingleVarDecl(instanceDecl))
throw new JapidCompilationException(template, parser.getLineNumber() + i, "loop variable declaration error: " + instanceDecl);
instanceDecl = JavaSyntaxTool.cleanDeclPrimitive(instanceDecl);
String collection = matcher.group(2);
if (!JavaSyntaxTool.isValidExpr(collection))
throw new JapidCompilationException(template, parser.getLineNumber() + i, "syntax error: " + collection);
expr = "each " + collection + " | " + instanceDecl;
Tag tag = buildTagDirective(expr);
tag.tagName = "Each";
tag.hasBody = true;
startTag(tag);
} else {
// should not happen
print(expr);
markLine(parser.getLineNumber() + i);
println();
}
} else if (line.trim().length() == 0) {
// a single ` empty line, treated as the closing for `tag
try {
Tag tagShadow = tagsStackShadow.peek();
if (tagShadow.isRoot()) {
// System.out.println("");
} else {
tagShadow = tagsStackShadow.pop();
if (tagShadow instanceof TagIf) {
// to close an open if
print("}");
markLine(parser.getLineNumber() + i);
println();
} else {
if (!tagsStack.empty()) {
Tag tag = tagsStack.peek();
if (!tag.isRoot()) {
tag = popStack();
endTag(tag);
}
}
}
}
} catch (Exception e) {
// should throw it out?
e.printStackTrace();
}
} else {
// OK plain Java code
if (line.length() > 0) {
print(line);
markLine(parser.getLineNumber() + i);
println();
}
}
}
skipLineBreak = true;
}
use of cn.bran.japid.template.JapidTemplate in project Japid by branaway.
the class JapidTemplateTransformer method generate.
/**
*
* @param fileName
* the relative path of the template file from the source folder,
* e.g., "my/path/mytemplate.html", which maps to
* my.path.mytemplate.java
* @return
* @throws Exception
*/
public File generate(String fileName) throws Exception {
String realSrcFile = sourceFolder == null ? fileName : sourceFolder + "/" + fileName;
String src = DirUtil.readFileAsString(realSrcFile);
JapidTemplate temp = new JapidTemplate(fileName, src);
JapidAbstractCompiler c = selectCompiler(src);
c.setUseWithPlay(usePlay);
c.compile(temp);
String jsrc = temp.javaSource;
String fileNameRoot = DirUtil.mapSrcToJava(fileName);
String target = targetFolder == null ? sourceFolder : targetFolder;
String realTargetFile = target == null ? fileNameRoot : target + "/" + fileNameRoot;
File f = DirUtil.writeToFile(jsrc, realTargetFile);
return f;
}
use of cn.bran.japid.template.JapidTemplate in project Japid by branaway.
the class CompilerTests method testTagline.
@Test
public void testTagline() throws IOException, ParseException {
String srcFile = "tests/tagline.html";
String src = readFile(srcFile);
JapidTemplate bt = new JapidTemplate("tagline.html", src);
JapidAbstractCompiler cp = new JapidTemplateCompiler();
cp.compile(bt);
String code = bt.javaSource;
System.out.println(code);
CompilationUnit cu = JavaSyntaxTool.parse(code);
// System.out.println(cu);
}
use of cn.bran.japid.template.JapidTemplate in project Japid by branaway.
the class CompilerTests method testTagNamedArgsWithBody.
@Test
public void testTagNamedArgsWithBody() throws IOException, ParseException {
String srcFile = "tests/callTagWithBody.html";
String src = readFile(srcFile);
JapidTemplate bt = new JapidTemplate("tests/callTagWithBody.html", src);
JapidAbstractCompiler cp = new JapidTemplateCompiler();
cp.compile(bt);
String code = bt.javaSource;
assertTrue("invalid java code", JavaSyntaxTool.isValid(code));
System.out.println(code);
}
use of cn.bran.japid.template.JapidTemplate in project Japid by branaway.
the class CompilerTests method testInclude.
@Test
public void testInclude() throws IOException, ParseException {
String srcFile = "tests/include.html";
String src = readFile(srcFile);
JapidTemplate bt = new JapidTemplate(srcFile, src);
JapidAbstractCompiler cp = new JapidTemplateCompiler();
cp.compile(bt);
System.out.println(bt.javaSource);
assertTrue("invalid java code", JavaSyntaxTool.isValid(bt.javaSource));
}
Aggregations