use of cn.bran.japid.template.JapidTemplate in project Japid by branaway.
the class CompilerRequestor method acceptResult.
@Override
public void acceptResult(CompilationResult result) {
// If error
if (result.hasErrors()) {
// bran: sort the problems and report the first one
CategorizedProblem[] errors = result.getErrors();
Arrays.sort(errors, new Comparator<CategorizedProblem>() {
@Override
public int compare(CategorizedProblem o1, CategorizedProblem o2) {
return o1.getSourceLineNumber() - o2.getSourceLineNumber();
}
});
for (IProblem problem : errors) {
String className = new String(problem.getOriginatingFileName()).replace("/", ".");
className = className.substring(0, className.length() - 5);
String message = problem.getMessage();
if (problem.getID() == IProblem.CannotImportPackage) {
// Non sense !
message = problem.getArguments()[0] + " cannot be resolved";
}
RendererClass rc = this.rendererCompiler.japidClasses.get(className);
if (rc.getSrcFile() == null)
throw new RuntimeException("no source file for compiling " + className);
if (rc.getOriSourceCode() == null)
throw new RuntimeException("no original source code for compiling " + className);
JapidTemplate tmpl = new JapidTemplate(rc.getSrcFile().getPath(), rc.getOriSourceCode());
throw new JapidCompilationException(tmpl, DirUtil.mapJavaLineToSrcLine(rc.getSourceCode(), problem.getSourceLineNumber()), message + " while compiling " + className);
}
}
// Something has been compiled
ClassFile[] clazzFiles = result.getClassFiles();
for (int i = 0; i < clazzFiles.length; i++) {
final ClassFile clazzFile = clazzFiles[i];
final char[][] compoundName = clazzFile.getCompoundName();
final StringBuffer clazzName = new StringBuffer();
for (int j = 0; j < compoundName.length; j++) {
if (j != 0) {
clazzName.append('.');
}
clazzName.append(compoundName[j]);
}
byte[] bytes = clazzFile.getBytes();
JapidFlags.debug("Bytecode generated for " + clazzName);
// XXX address anonymous inner class issue!! ....$1...
String cname = clazzName.toString();
RendererClass rc = this.rendererCompiler.japidClasses.get(cname);
if (rc == null) {
if (cname.contains("$")) {
// inner class
rc = new RendererClass();
rc.setClassName(cname);
this.rendererCompiler.japidClasses.put(cname, rc);
} else {
throw new RuntimeException("name not in the classes container: " + cname);
}
}
rc.setBytecode(bytes);
}
}
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 BranLayoutCompilerTest method testHop.
@Test
public void testHop() throws IOException {
FileInputStream fis = new FileInputStream("JapidSample/app/japidviews/_layouts/Layout.html");
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
BufferedReader br = new BufferedReader(isr);
String src = "";
for (String line = br.readLine(); line != null; line = br.readLine()) {
src += line + "\n";
}
JapidTemplate bt = new JapidTemplate("tag/Layout.html", src);
JapidAbstractCompiler cp = new JapidLayoutCompiler();
cp.compile(bt);
System.out.println(bt.javaSource);
}
use of cn.bran.japid.template.JapidTemplate in project Japid by branaway.
the class CompilerTests method testOpenBrace.
@Test
public void testOpenBrace() throws IOException {
String srcFile = "tests/openBrace.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