diff --git a/src/main/java/org/beetl/core/AntlrProgramBuilder.java b/src/main/java/org/beetl/core/AntlrProgramBuilder.java index ffc63403250638b1e3f61993be8f56c2d00ba49f..b461dc295603adceaeaa15eef8c3e33e67d799ae 100644 --- a/src/main/java/org/beetl/core/AntlrProgramBuilder.java +++ b/src/main/java/org/beetl/core/AntlrProgramBuilder.java @@ -486,9 +486,7 @@ public class AntlrProgramBuilder { registerVar(vas); return vas; } else { - BeetlException ex = new BeetlException(BeetlException.VAR_NOT_DEFINED); - ex.pushToken(this.getBTToken(token)); - throw ex; + throw new BeetlException(BeetlException.VAR_NOT_DEFINED).pushToken(this.getBTToken(token)); } } @@ -526,9 +524,7 @@ public class AntlrProgramBuilder { registerVar(vas); return vas; } else { - BeetlException ex = new BeetlException(BeetlException.VAR_NOT_DEFINED); - ex.pushToken(this.getBTToken(token)); - throw ex; + throw new BeetlException(BeetlException.VAR_NOT_DEFINED).pushToken(this.getBTToken(token)); } } @@ -540,9 +536,8 @@ public class AntlrProgramBuilder { protected void registerNewVar(ASTNode vas) { if (pbCtx.hasDefined(vas.token.text) != null) { GrammarToken token = pbCtx.hasDefined(vas.token.text); - BeetlException ex = new BeetlException(BeetlException.VAR_ALREADY_DEFINED, "已经在第" + token.line + "行定义"); - ex.pushToken(vas.token); - throw ex; + throw new BeetlException(BeetlException.VAR_ALREADY_DEFINED, "已经在第" + token.line + "行定义") + .pushToken(vas.token); } pbCtx.addVar(vas.token.text); pbCtx.setVarPosition(vas.token.text, vas); @@ -658,25 +653,25 @@ public class AntlrProgramBuilder { Statement block = null; VarDefineNode[] varDefine = new VarDefineNode[vars.length]; if (id.equals("htmltagRootExport")) { - //自定在模板最上层定义的变量 + //自定在模板最上层定义的变量 for (int i = 0; i < vars.length; i++) { - //如果已经定义,忽略,比较符合html标签和jsp tag习惯 - String varName = vars[i].trim(); - VarDescrption varDescrption = pbCtx.root.getVars().get(varName); - if(varDescrption==null){ - VarDefineNode varNode = new VarDefineNode(this.getBTToken(vars[i].trim(), line)); - pbCtx.addRootVarAdnPosition(varNode); - varDefine[i] = varNode; - }else{ - ASTNode astNode = varDescrption.where.get(0); - if(!(astNode instanceof VarDefineNode)){ - //不可能发生,先保留 - BeetlException ex = new BeetlException(BeetlException.PARSER_HTML_TAG_ERROR, - "标签定义了一个全局变量 "+varName+" 但是此变量名在 "+astNode.token.line+" 使用了"); - ex.pushToken(this.getBTToken(id, fc.functionNs().getStart().getLine())); - } - varDefine[i] = (VarDefineNode)varDescrption.where.get(0); - } + //如果已经定义,忽略,比较符合html标签和jsp tag习惯 + String varName = vars[i].trim(); + VarDescrption varDescrption = pbCtx.root.getVars().get(varName); + if (varDescrption == null) { + VarDefineNode varNode = new VarDefineNode(this.getBTToken(vars[i].trim(), line)); + pbCtx.addRootVarAdnPosition(varNode); + varDefine[i] = varNode; + } else { + ASTNode astNode = varDescrption.where.get(0); + if (!(astNode instanceof VarDefineNode)) { + //不可能发生,先保留 + BeetlException ex = new BeetlException(BeetlException.PARSER_HTML_TAG_ERROR, + "标签定义了一个全局变量 " + varName + " 但是此变量名在 " + astNode.token.line + " 使用了"); + ex.pushToken(this.getBTToken(id, fc.functionNs().getStart().getLine())); + } + varDefine[i] = (VarDefineNode) varDescrption.where.get(0); + } } BlockContext blockCtx = fc.block(); @@ -689,15 +684,15 @@ public class AntlrProgramBuilder { } for (int i = 0; i < vars.length; i++) { - String varName = vars[i].trim(); - ASTNode astNode = pbCtx.contain(varName); - if(astNode==null){ - VarDefineNode varNode = new VarDefineNode(this.getBTToken(vars[i].trim(), line)); - this.pbCtx.addVarAndPostion(varNode); - varDefine[i] = varNode; - }else{ - varDefine[i] = (VarDefineNode)astNode; - } + String varName = vars[i].trim(); + ASTNode astNode = pbCtx.contain(varName); + if (astNode == null) { + VarDefineNode varNode = new VarDefineNode(this.getBTToken(vars[i].trim(), line)); + this.pbCtx.addVarAndPostion(varNode); + varDefine[i] = varNode; + } else { + varDefine[i] = (VarDefineNode) astNode; + } } BlockContext blockCtx = fc.block(); @@ -709,26 +704,21 @@ public class AntlrProgramBuilder { TagFactory tf = this.gt.getTagFactory(id); if (tf == null) { - BeetlException ex = new BeetlException(BeetlException.TAG_NOT_FOUND); - ex.pushToken(this.getBTToken(id, fc.functionNs().getStart().getLine())); - throw ex; + throw new BeetlException(BeetlException.TAG_NOT_FOUND) + .pushToken(this.getBTToken(id, fc.functionNs().getStart().getLine())); } - TagStatement tag = gc.createVarTag(id, expList, block, varDefine, this.getBTToken(id, line)); - - return tag; + return gc.createVarTag(id, expList, block, varDefine, this.getBTToken(id, line)); } else { BlockContext blockCtx = fc.block(); Statement block = parseBlock(blockCtx.statement(), blockCtx); TagFactory tf = this.gt.getTagFactory(id); if (tf == null) { - BeetlException ex = new BeetlException(BeetlException.TAG_NOT_FOUND); - ex.pushToken(this.getBTToken(id, fc.functionNs().getStart().getLine())); - throw ex; + throw new BeetlException(BeetlException.TAG_NOT_FOUND) + .pushToken(this.getBTToken(id, fc.functionNs().getStart().getLine())); } - TagStatement tag = gc.createTag(id, expList, block, + return gc.createTag(id, expList, block, this.getBTToken(id, fc.functionNs().getStart().getLine())); - return tag; } } @@ -900,7 +890,9 @@ public class AntlrProgramBuilder { protected Expression[] getExprssionList(ExpressionListContext expListCtx) { - if (expListCtx == null) return EMPTY_EXPRESSION; + if (expListCtx == null) { + return EMPTY_EXPRESSION; + } List ecList = expListCtx.expression(); Expression[] exps = new Expression[ecList.size()]; for (int i = 0; i < ecList.size(); i++) { @@ -1121,7 +1113,9 @@ public class AntlrProgramBuilder { } protected Expression parseExpress(ExpressionContext ctx) { - if (ctx == null) return null; + if (ctx == null) { + return null; + } if (ctx instanceof LiteralExpContext) { return parseLiteralExpress(((LiteralExpContext) ctx).literal()); @@ -1550,7 +1544,6 @@ public class AntlrProgramBuilder { Safe_outputContext soctx = varRef.safe_output(); if (soctx != null) { throw new BeetlException(BeetlException.ERROR, "语法错,赋值表达式不能使用安全输出"); - } List list = varRef.varAttribute(); @@ -1561,7 +1554,6 @@ public class AntlrProgramBuilder { if (!(first instanceof VarSquareAttribute || first instanceof VarVirtualAttribute)) { pbCtx.setVarAttr(varRef.Identifier().getText(), first.token.text); } - } VarRef var = new VarRef(vas, false, null, diff --git a/src/main/java/org/beetl/core/BodyContent.java b/src/main/java/org/beetl/core/BodyContent.java index 9046a9961faa77b4857e59f86d52783cf29b3f5e..b8c6d7e19d71d8693e1fde20002772a28478c11d 100644 --- a/src/main/java/org/beetl/core/BodyContent.java +++ b/src/main/java/org/beetl/core/BodyContent.java @@ -35,6 +35,7 @@ import java.io.IOException; * @author xiandafu */ public interface BodyContent { + /** * 获取模板或者标签的内容 * diff --git a/src/main/java/org/beetl/core/ByteWriter.java b/src/main/java/org/beetl/core/ByteWriter.java index 8160734493c1a1e696f606e673d44445a8054fbc..e26143809204a562789dd6d949d9670d13bcd274 100644 --- a/src/main/java/org/beetl/core/ByteWriter.java +++ b/src/main/java/org/beetl/core/ByteWriter.java @@ -68,7 +68,7 @@ public abstract class ByteWriter { public abstract ByteWriter getTempWriter(ByteWriter parent); - public abstract BodyContent getTempConent(); + public abstract BodyContent getTempContent(); /** * 将内容填充到bw里 diff --git a/src/main/java/org/beetl/core/GroupTemplate.java b/src/main/java/org/beetl/core/GroupTemplate.java index d9eb74d01fdd2bb57ce482114bf7846449beba61..a9812f7743e8aeec355a4bcbebf09955338604d3 100644 --- a/src/main/java/org/beetl/core/GroupTemplate.java +++ b/src/main/java/org/beetl/core/GroupTemplate.java @@ -511,9 +511,7 @@ public class GroupTemplate { return ep; } catch (IOException e) { ErrorGrammarProgram ep = new ErrorGrammarProgram(res, this, String.valueOf(text.cr1)); - BeetlException ex = new BeetlException(BeetlException.TEMPLATE_LOAD_ERROR); - ex.pushResource(res); - ep.setException(ex); + ep.setException(new BeetlException(BeetlException.TEMPLATE_LOAD_ERROR).pushResource(res)); return ep; } catch (BeetlException ex) { ErrorGrammarProgram ep = new ErrorGrammarProgram(res, this, text.systemCrStr); diff --git a/src/main/java/org/beetl/core/Transformator.java b/src/main/java/org/beetl/core/Transformator.java index eba988fc4f036c6bde8ed37999225a000255c857..3f0f0f1d783b758b1df48e10c174f12c5059844a 100644 --- a/src/main/java/org/beetl/core/Transformator.java +++ b/src/main/java/org/beetl/core/Transformator.java @@ -170,10 +170,9 @@ public class Transformator { String tagName = (String) htmlTagStack.peek(); GrammarToken token = GrammarToken.createToken(tagName, this.totalLineCount + 1); - HTMLTagParserException ex = new HTMLTagParserException("解析html tag 标签出错,未找到匹配结束标签 " + tagName); - + HTMLTagParserException ex = new HTMLTagParserException("解析html tag 标签出错,未找到匹配结束标签 " + tagName) + .setLine(totalLineCount + 1); ex.pushToken(token); - ex.line = totalLineCount + 1; this.clear(); throw ex; } diff --git a/src/main/java/org/beetl/core/cache/LocalCache.java b/src/main/java/org/beetl/core/cache/LocalCache.java index 2961ed43571452296309c5d8d483bc0f7280171f..785aaeec663c394d470e3b1c128e9221f16699ba 100644 --- a/src/main/java/org/beetl/core/cache/LocalCache.java +++ b/src/main/java/org/beetl/core/cache/LocalCache.java @@ -42,7 +42,7 @@ import java.util.function.Function; public class LocalCache implements Cache { /** 线程安全的缓存 */ - private final Map threadSafeCache = new ConcurrentHashMap<>(); + private final Map threadSafeCache = new ConcurrentHashMap<>(); @Override public Object get(Object key) { diff --git a/src/main/java/org/beetl/core/engine/GrammarCreator.java b/src/main/java/org/beetl/core/engine/GrammarCreator.java index a1b30788c46a891012b400450db683a09e3076a1..936a04e4c13b980e6de39c3f0c4e892318df4bea 100644 --- a/src/main/java/org/beetl/core/engine/GrammarCreator.java +++ b/src/main/java/org/beetl/core/engine/GrammarCreator.java @@ -124,10 +124,11 @@ public class GrammarCreator implements IGrammarConstants { return new ForStatement(forVar, exp, hasSafe, forPart, elseForPart, forVar.token); } - public GeneralForStatement createFor(VarAssignSeqStatement varAssignSeq, Expression[] expInit, Expression condtion, - Expression[] expUpdate, Statement forPart, Statement elseforPart, GrammarToken token) { + public GeneralForStatement createFor(VarAssignSeqStatement varAssignSeq, Expression[] expInit, Expression condition, + Expression[] expUpdate, Statement forPart, Statement elseforPart, + GrammarToken token) { disableSyntaxCheck(For); - return new GeneralForStatement(varAssignSeq, expInit, condtion, expUpdate, forPart, elseforPart, token); + return new GeneralForStatement(varAssignSeq, expInit, condition, expUpdate, forPart, elseforPart, token); } public WhileStatement createWhile(Expression exp, Statement whileBody, GrammarToken token) { diff --git a/src/main/java/org/beetl/core/engine/OnlineTemplateEngine.java b/src/main/java/org/beetl/core/engine/OnlineTemplateEngine.java index 6c4a061b1239593b8cb3b0b9cb3995bbfa85bbac..90c08e6a9ad98a8a52bdb3bc6775a86ad5e213f6 100644 --- a/src/main/java/org/beetl/core/engine/OnlineTemplateEngine.java +++ b/src/main/java/org/beetl/core/engine/OnlineTemplateEngine.java @@ -151,9 +151,7 @@ public class OnlineTemplateEngine extends DefaultTemplateEngine { break; } } else { - BeetlException be = new BeetlException(BeetlException.BOOLEAN_EXPECTED_ERROR); - be.token = exp.token; - throw be; + throw new BeetlException(BeetlException.BOOLEAN_EXPECTED_ERROR).setToken(exp.token); } i++; } diff --git a/src/main/java/org/beetl/core/exception/BeetlException.java b/src/main/java/org/beetl/core/exception/BeetlException.java index 613698f84bfc102a49d0f356fff943f8f1d2d6a5..1c72ff32ed0aaa0a4bd5464c23bbe39916d02cd3 100644 --- a/src/main/java/org/beetl/core/exception/BeetlException.java +++ b/src/main/java/org/beetl/core/exception/BeetlException.java @@ -228,7 +228,7 @@ public class BeetlException extends RuntimeException { * * @param resource 资源 */ - public void pushResource(Resource resource) { + public BeetlException pushResource(Resource resource) { if (this.inTagBody) { /* 如果当前渲染的是html标签,则出错资源应该使用该html标签的页面,而不是渲染改标签的页面 @@ -242,12 +242,13 @@ public class BeetlException extends RuntimeException { 2018-9-9 */ this.inTagBody = false; - return; + return this; } if (this.resource == null) { this.resource = resource; } this.errorResourceStack.add(resource); + return this; } /** @@ -255,13 +256,26 @@ public class BeetlException extends RuntimeException { * * @param token 语法单词 */ - public void pushToken(GrammarToken token) { + public BeetlException pushToken(GrammarToken token) { if (this.token == null) { this.token = token; } this.errorTokenStack.add(token); + return this; } + /** + * 设置Token的内容 + * + * @param newToken 新的Token + * @return 本身 + */ + public BeetlException setToken(GrammarToken newToken) { + this.token = newToken; + return this; + } + + /** * 返回一个错误描述信息 */ diff --git a/src/main/java/org/beetl/core/exception/HTMLTagParserException.java b/src/main/java/org/beetl/core/exception/HTMLTagParserException.java index d697be74d72b42e104385dd823bd49ee01b18d28..da51268c65d0b88bfedcf2568deaa596b6cb1921 100644 --- a/src/main/java/org/beetl/core/exception/HTMLTagParserException.java +++ b/src/main/java/org/beetl/core/exception/HTMLTagParserException.java @@ -54,4 +54,15 @@ public class HTMLTagParserException extends BeetlException { public String getHtmlTagErrorMsg() { return super.getMessage(); } + + /** + * 设置行号 + * + * @param newLine 新的行号 + * @return 自身 + */ + public HTMLTagParserException setLine(int newLine) { + this.line = newLine; + return this; + } } diff --git a/src/main/java/org/beetl/core/fun/FileFunctionWrapper.java b/src/main/java/org/beetl/core/fun/FileFunctionWrapper.java index 85506bd369d54d5d6c15741a7f27cd72a4659138..e9837804825ff11507a0b44c1177c5874b0a82c0 100644 --- a/src/main/java/org/beetl/core/fun/FileFunctionWrapper.java +++ b/src/main/java/org/beetl/core/fun/FileFunctionWrapper.java @@ -39,7 +39,8 @@ import org.beetl.core.exception.BeetlException; */ public class FileFunctionWrapper implements Function { - String resourceId = null; + /** 资源文件名称 */ + private final String resourceId; /** * 模板文件的资源标示 @@ -63,14 +64,8 @@ public class FileFunctionWrapper implements Function { template.renderTo(ctx.byteWriter); Object[] vars = template.getCtx().vars; Object o = vars[vars.length - 1]; - if (o != Context.NOT_EXIST_OBJECT) { - return o; - } else { - return null; - } - + return o != Context.NOT_EXIST_OBJECT ? o : null; } catch (BeetlException ex) { - throw ex; } catch (Exception ex) { throw new BeetlException(BeetlException.NATIVE_CALL_EXCEPTION, "调用方法出错 " + this.resourceId, ex); diff --git a/src/main/java/org/beetl/core/fun/FunctionWrapper.java b/src/main/java/org/beetl/core/fun/FunctionWrapper.java index 6c337142e585a100fa90c707bb257a149dc2d266..a75729eca9214c51dad97be8642ad999cf0a62fe 100644 --- a/src/main/java/org/beetl/core/fun/FunctionWrapper.java +++ b/src/main/java/org/beetl/core/fun/FunctionWrapper.java @@ -51,7 +51,7 @@ public abstract class FunctionWrapper implements Function { this.functionName = funName; } - protected boolean checkContextRequried(Class[] paras) { + protected boolean checkContextRequired(Class[] paras) { return paras.length != 0 && paras[paras.length - 1] == Context.class; } @@ -60,26 +60,22 @@ public abstract class FunctionWrapper implements Function { System.arraycopy(paras, 0, newParas, 0, paras.length); newParas[paras.length] = ctx; return newParas; - } /** * 得到对象的所有FunctionWrapper,改对象的所有Public 方法都将注册到Beetl里 */ public static List getFunctionWrapper(String ns, Class c, Object o) { - ObjectInfo info = ObjectUtil.getObjectInfo(c); Map> map = info.getMap(); - List fwList = new ArrayList(); + List fwList = new ArrayList<>(); for (Entry> entry : map.entrySet()) { - - if (entry.getValue().size() == 1) { - - Method method = entry.getValue().get(0); + List methodList = entry.getValue(); + Method method = methodList.get(0); + if (methodList.size() == 1) { FunctionWrapper fw = new SingleFunctionWrapper(ns.concat(".").concat(method.getName()), c, o, method); fwList.add(fw); } else { - Method method = entry.getValue().get(0); String name = method.getName(); FunctionWrapper fw = new MutipleFunctionWrapper(ns.concat(".").concat(name), c, o, entry.getValue() .toArray(new Method[0])); @@ -88,6 +84,5 @@ public abstract class FunctionWrapper implements Function { } return fwList; - } } diff --git a/src/main/java/org/beetl/core/fun/GeneralGetMethodInvoker.java b/src/main/java/org/beetl/core/fun/GeneralGetMethodInvoker.java index 7261483ffb8e411c689214d654f72f2641f9782f..39d8ce30c2b379b3d2faa66cee9601073206e989 100644 --- a/src/main/java/org/beetl/core/fun/GeneralGetMethodInvoker.java +++ b/src/main/java/org/beetl/core/fun/GeneralGetMethodInvoker.java @@ -21,10 +21,8 @@ public class GeneralGetMethodInvoker implements MethodInvoker { return method.invoke(o, name); } catch (IllegalArgumentException e) { throw new BeetlException(BeetlException.ATTRIBUTE_INVALID, "错误参数", e); - } catch (IllegalAccessException e) { throw new BeetlException(BeetlException.ATTRIBUTE_INVALID, "无法访问", e); - } catch (InvocationTargetException e) { Throwable target = e.getTargetException(); if (target instanceof BeetlException) { diff --git a/src/main/java/org/beetl/core/fun/SingleFunctionWrapper.java b/src/main/java/org/beetl/core/fun/SingleFunctionWrapper.java index 446b9b2bc647d993fba1dcbb6ba558679400679c..e77c97fe4c91e869295f93fcd4764f0406865d0e 100644 --- a/src/main/java/org/beetl/core/fun/SingleFunctionWrapper.java +++ b/src/main/java/org/beetl/core/fun/SingleFunctionWrapper.java @@ -46,7 +46,7 @@ public class SingleFunctionWrapper extends FunctionWrapper { this.target = target; this.cls = cls; this.m = m; - this.requiredContext = this.checkContextRequried(m.getParameterTypes()); + this.requiredContext = this.checkContextRequired(m.getParameterTypes()); } diff --git a/src/main/java/org/beetl/core/io/ByteBodyContent.java b/src/main/java/org/beetl/core/io/ByteBodyContent.java index 8e4c408d92c20ad3ba22e2988063245b9a7244e8..f251473f52db8180c77ced4378ba6df1e425775e 100644 --- a/src/main/java/org/beetl/core/io/ByteBodyContent.java +++ b/src/main/java/org/beetl/core/io/ByteBodyContent.java @@ -47,17 +47,18 @@ public class ByteBodyContent implements BodyContent { this.bs = bs; this.charset = charset; this.count = count; - } public String getBody() { return this.toString(); } + @Override public String toString() { try { return new String(bs, 0, count, charset); } catch (UnsupportedEncodingException e) { + // TODO: DEBUG 环境才抛异常,非DEBUG环境返回""等字符串 throw new RuntimeException(e); } } @@ -65,6 +66,5 @@ public class ByteBodyContent implements BodyContent { @Override public void fill(ByteWriter bw) throws IOException { bw.write(bs, count); - } } diff --git a/src/main/java/org/beetl/core/io/ByteWriter_Byte.java b/src/main/java/org/beetl/core/io/ByteWriter_Byte.java index e15364aead113f06e06a754eaaba58a6687132b6..011b4f06f7daba6eb75ae7f7f85016504ba927aa 100644 --- a/src/main/java/org/beetl/core/io/ByteWriter_Byte.java +++ b/src/main/java/org/beetl/core/io/ByteWriter_Byte.java @@ -40,11 +40,12 @@ public class ByteWriter_Byte extends ByteWriter { protected String cs; DefaultEncoder encode = null; - // protected Charset charset = null; - // CharsetEncoder encoder = null; - // ByteBuffer byteBuffer = null; - // byte[] bs = new byte[256]; - + /** + * 构造方法 + * @param os 输出流 + * @param cs + * @param ctx + */ public ByteWriter_Byte(OutputStream os, String cs, Context ctx) { super(ctx); this.os = os; @@ -60,7 +61,7 @@ public class ByteWriter_Byte extends ByteWriter { @Override public final void write(final char[] cbuf) throws IOException { this.write(cbuf, cbuf.length); - //todo:性能如何? + // TODO:性能如何? } @Override @@ -76,13 +77,11 @@ public class ByteWriter_Byte extends ByteWriter { public void write(byte[] bs, int count) throws IOException { os.write(bs, 0, count); - } public void writeString(String str) throws IOException { if (str != null) { encode.write(str, os); - // os.write(str.getBytes(cs)); } } @@ -93,24 +92,23 @@ public class ByteWriter_Byte extends ByteWriter { @Override public void flush() throws IOException { - if (parent != null) + if (parent != null) { parent.flush(); + } this.os.flush(); - } @Override public void fill(ByteWriter bw) throws IOException { ByteWriter_Byte bwb = (ByteWriter_Byte) bw; NoLockByteArrayOutputStream byteArray = (NoLockByteArrayOutputStream) bwb.os; - this.write(byteArray.buf, byteArray.count); - + this.write(byteArray.buf, byteArray.pos); } @Override - public BodyContent getTempConent() { + public BodyContent getTempContent() { NoLockByteArrayOutputStream byteArray = (NoLockByteArrayOutputStream) this.os; - return new ByteBodyContent(byteArray.buf, byteArray.count, this.cs); + return new ByteBodyContent(byteArray.buf, byteArray.pos, this.cs); } public OutputStream getOs() { diff --git a/src/main/java/org/beetl/core/io/ByteWriter_Char.java b/src/main/java/org/beetl/core/io/ByteWriter_Char.java index e44a62e78135f31d24602c6a9c00d05f9c6bb12e..ca316bf49ebaaa89f5c0a81edfd7a66b94470afe 100644 --- a/src/main/java/org/beetl/core/io/ByteWriter_Char.java +++ b/src/main/java/org/beetl/core/io/ByteWriter_Char.java @@ -44,18 +44,15 @@ public final class ByteWriter_Char extends ByteWriter { @Override public final void write(char[] cbuf) throws IOException { w.write(cbuf); - } @Override public void write(char[] cbuf, int len) throws IOException { w.write(cbuf, 0, len); - } @Override public void writeString(String str) throws IOException { - if (str != null) { int len = str.length(); char[] buf = localBuffer.getCharBuffer(len); @@ -65,21 +62,17 @@ public final class ByteWriter_Char extends ByteWriter { } else { w.write(str); } - } - } @Override public final void write(byte[] bs) throws IOException { this.writeString(new String(bs, cs)); - } @Override public final void write(byte[] bs, int count) throws IOException { this.writeString(new String(bs, 0, count, cs)); - } @Override @@ -89,8 +82,9 @@ public final class ByteWriter_Char extends ByteWriter { @Override public void flush() throws IOException { - if (parent != null) + if (parent != null) { parent.flush(); + } this.w.flush(); } @@ -104,14 +98,13 @@ public final class ByteWriter_Char extends ByteWriter { public void fill(ByteWriter bw) throws IOException { NoLockStringWriter blw = ((NoLockStringWriter) ((ByteWriter_Char) bw).w); char[] buf = blw.buf; - this.write(buf, blw.count); - + this.write(buf, blw.pos); } @Override - public BodyContent getTempConent() { + public BodyContent getTempContent() { NoLockStringWriter blw = (NoLockStringWriter) w; - return new StringBodyContent(blw.buf, blw.count); + return new StringBodyContent(blw.buf, blw.pos); } public Writer getW() { @@ -133,6 +126,5 @@ public final class ByteWriter_Char extends ByteWriter { @Override public void writeNumberChars(char[] chars, int len) throws IOException { this.w.write(chars, 0, len); - } } diff --git a/src/main/java/org/beetl/core/io/CachedStringWriter.java b/src/main/java/org/beetl/core/io/CachedStringWriter.java index 8d06c8f0085a90b9934e2146c80f0591427c49f3..d12d5e0ef269fd9e2a8019dc8d1bfab5d67cda3c 100644 --- a/src/main/java/org/beetl/core/io/CachedStringWriter.java +++ b/src/main/java/org/beetl/core/io/CachedStringWriter.java @@ -5,26 +5,27 @@ package org.beetl.core.io; *
  *
  *     Writer writer = CachedStringWriter.buffers.get();
- *     tempalte.renderTo(writer);
+ *     template.renderTo(writer);
  *     String result = writer.toString();
  * 
*/ public class CachedStringWriter extends NoLockStringWriter { - public String toString() { - String str = new String(buf, 0, count); - count = 0; - /** + @Override + public String toString() { + String str = new String(buf, 0, pos); + pos = 0; + /* * 如果buf过长,可以考虑清空或者缩容 * 考虑Web应用通常是直接输出到ServletIOStream * 所以这种很少使用,只作为性能要求很高场合要用 * if(buf.length>1024*10) buf = new char[1024]; */ - return str; } public static ThreadLocal buffers = new ThreadLocal() { + @Override public CachedStringWriter initialValue() { return new CachedStringWriter(); } diff --git a/src/main/java/org/beetl/core/io/DefaultEncoder.java b/src/main/java/org/beetl/core/io/DefaultEncoder.java index d41e08de325cead3212e6f2621ede3aebbcb3ee9..c2981d854b77abdc16785e629c2efcb58f5ca745 100644 --- a/src/main/java/org/beetl/core/io/DefaultEncoder.java +++ b/src/main/java/org/beetl/core/io/DefaultEncoder.java @@ -36,25 +36,18 @@ public class DefaultEncoder { } public void write(final char[] chars, final int len, final OutputStream out) throws IOException { - if (chars != null && len != 0) { - - final CharsetEncoder encoder; - final ByteBuffer bb; - byte[] buffer = this.localBuffer.getByteBuffer((int) (len * this.expansionFactor)); - if (buffer.length != 0) { - (encoder = this.charsetEncoder).reset().encode(CharBuffer.wrap(chars, 0, len), - bb = ByteBuffer.wrap(buffer), true); - encoder.flush(bb); - out.write(buffer, 0, bb.position()); - } else { - buffer = new byte[(int) (len * this.expansionFactor)]; - (encoder = this.charsetEncoder).reset().encode(CharBuffer.wrap(chars, 0, len), - bb = ByteBuffer.wrap(buffer), true); - encoder.flush(bb); - out.write(buffer, 0, bb.position()); - } - + if (chars == null || len == 0) { + return; + } + final ByteBuffer bb; + byte[] buffer = this.localBuffer.getByteBuffer((int) (len * this.expansionFactor)); + if (buffer.length == 0) { + buffer = new byte[(int) (len * this.expansionFactor)]; } + final CharsetEncoder encoder = this.charsetEncoder; + encoder.reset().encode(CharBuffer.wrap(chars, 0, len), bb = ByteBuffer.wrap(buffer), true); + encoder.flush(bb); + out.write(buffer, 0, bb.position()); } private static CharsetEncoder newEncoder(String csn) throws UnsupportedCharsetException { diff --git a/src/main/java/org/beetl/core/io/IOUtil.java b/src/main/java/org/beetl/core/io/IOUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..181f98971a295a5e764b54d4dceac20b51f5f886 --- /dev/null +++ b/src/main/java/org/beetl/core/io/IOUtil.java @@ -0,0 +1,30 @@ +package org.beetl.core.io; + +public class IOUtil { + + /** + * 拷贝一份内容 + * + * @param original 原始字节数组 + * @param newLength 待拷贝的长度 + * @return 新的数组实例 + */ + public static byte[] copyOf(byte[] original, int newLength) { + byte[] copy = new byte[newLength]; + System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); + return copy; + } + + /** + * 拷贝一份内容 + * + * @param original 原始字符数组 + * @param newLength 待拷贝的长度 + * @return 新的数组实例 + */ + public static char[] copyOf(char[] original, int newLength) { + char[] copy = new char[newLength]; + System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); + return copy; + } +} diff --git a/src/main/java/org/beetl/core/io/NoLockByteArrayOutputStream.java b/src/main/java/org/beetl/core/io/NoLockByteArrayOutputStream.java index 6e1bf209ecb51861fe10daa7d70f3b28f9fe192e..806b50bc23c910be5344f611c0fc997ae096cbf3 100644 --- a/src/main/java/org/beetl/core/io/NoLockByteArrayOutputStream.java +++ b/src/main/java/org/beetl/core/io/NoLockByteArrayOutputStream.java @@ -31,54 +31,83 @@ import java.io.OutputStream; public class NoLockByteArrayOutputStream extends OutputStream { - protected byte buf[]; - - protected int count; - + /** 默认的缓存大小 */ + private static final int DEFAULT_BUFFER_SIZE = 32; + /** 缓存 */ + protected byte[] buf; + /** 缓存中的位置 */ + protected int pos; + + /** + * 构造方法 + */ public NoLockByteArrayOutputStream() { - this(32); + this(DEFAULT_BUFFER_SIZE); } + /** + * 构造方法 + * + * @param size 缓存大小 + */ public NoLockByteArrayOutputStream(int size) { - buf = new byte[size]; } - public void write(int b) { - int newcount = count + 1; - if (newcount > buf.length) { - buf = copyOf(buf, Math.max(buf.length << 1, newcount)); + /** + * 向流中写入一个字节 + * + * @param src 字节来源 + */ + public void write(int src) { + int newPos = pos + 1; + if (newPos > buf.length) { // 扩容 + buf = IOUtil.copyOf(buf, Math.max(buf.length << 1, newPos)); } - buf[count] = (byte) b; - count = newcount; + buf[pos] = (byte) src; + pos = newPos; } - public void write(byte b[], int off, int len) { - - int newcount = count + len; - if (newcount > buf.length) { - buf = copyOf(buf, Math.max(buf.length << 1, newcount)); + /** + * 向流中写入一个字节数组 + * + * @param src 字节数组 + * @param off 在 {@param src} 中的起始下标 + * @param len 在 {@param src} 中的长度 + */ + public void write(byte[] src, int off, int len) { + int newPos = pos + len; + if (newPos > buf.length) { + buf = IOUtil.copyOf(buf, Math.max(buf.length << 1, newPos)); } - System.arraycopy(b, off, buf, count, len); - count = newcount; - } - - public static byte[] copyOf(byte[] original, int newLength) { - byte[] copy = new byte[newLength]; - System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); - return copy; + System.arraycopy(src, off, buf, pos, len); + pos = newPos; } + /** + * 重置 + */ public void reset() { - count = 0; + pos = 0; } - public byte toByteArray()[] { - return copyOf(this.buf, count); + /** + * 转成字节数组 + * + * @return 新的字节数组实例 + */ + public byte[] toByteArray() { + return IOUtil.copyOf(this.buf, pos); } + /** + * 获取已写入的大小 + * + * @return 已写入的大小 + */ public int size() { - return count; + return pos; } + } diff --git a/src/main/java/org/beetl/core/io/NoLockStringWriter.java b/src/main/java/org/beetl/core/io/NoLockStringWriter.java index ac406d09aa82e511ee7f1c42f88a16ffd037ba6e..480d059be65461ff8e9d08e208d059def6def313 100644 --- a/src/main/java/org/beetl/core/io/NoLockStringWriter.java +++ b/src/main/java/org/beetl/core/io/NoLockStringWriter.java @@ -27,35 +27,38 @@ */ package org.beetl.core.io; +import org.jetbrains.annotations.NotNull; + import java.io.IOException; import java.io.Writer; public class NoLockStringWriter extends Writer { - //todo reuse parent writer buf?? - protected char buf[]; - protected int count; + /** 默认的缓存长度 */ + private static final int DEFAULT_BUFFER_SIZE = 64; + + // todo reuse parent writer buf?? + protected char[] buf; + protected int pos; + /** + * 构造方法 + */ public NoLockStringWriter() { - this.buf = new char[64]; + this.buf = new char[DEFAULT_BUFFER_SIZE]; } @Override - public void write(char[] cbuf, int off, int len) throws IOException { - int newcount = count + len; - if (newcount > buf.length) { - buf = copyOf(buf, Math.max(buf.length << 1, newcount)); + public void write(char[] src, int off, int len) throws IOException { + int newPos = pos + len; + if (newPos > buf.length) { + buf = IOUtil.copyOf(buf, Math.max(buf.length << 1, newPos)); } - System.arraycopy(cbuf, off, buf, count, len); - count = newcount; - } - - public static char[] copyOf(char[] original, int newLength) { - char[] copy = new char[newLength]; - System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); - return copy; + System.arraycopy(src, off, buf, pos, len); + pos = newPos; } + @Override public void write(String str) throws IOException { if (str != null) { this.write(str.toCharArray()); @@ -70,11 +73,11 @@ public class NoLockStringWriter extends Writer { @Override public void close() throws IOException { // TODO Auto-generated method stub - } + @Override public String toString() { - return new String(buf, 0, count); + return new String(buf, 0, pos); } } diff --git a/src/main/java/org/beetl/core/io/StringBodyContent.java b/src/main/java/org/beetl/core/io/StringBodyContent.java index 406a53e2c2869c867bb0f9711a9bba8058d6d8bf..544cf37853278f1fd738857684dac2ee1c374ba7 100644 --- a/src/main/java/org/beetl/core/io/StringBodyContent.java +++ b/src/main/java/org/beetl/core/io/StringBodyContent.java @@ -38,8 +38,12 @@ import org.beetl.core.ByteWriter; * @author xiandafu */ public class StringBodyContent implements BodyContent { + + /** 表示缓存的字符数组 */ char[] buf; + /** 记录缓存的长度 */ int count; + /** 缓存 toString 方法的结果 */ String str = null; public StringBodyContent(char[] buf, int count) { @@ -47,6 +51,7 @@ public class StringBodyContent implements BodyContent { this.count = count; } + @Override public String toString() { if (str == null) { str = new String(buf, 0, count); @@ -63,6 +68,5 @@ public class StringBodyContent implements BodyContent { @Override public void fill(ByteWriter bw) throws IOException { bw.write(this.buf, count); - } } diff --git a/src/main/java/org/beetl/core/misc/ALU.java b/src/main/java/org/beetl/core/misc/ALU.java index 9027be5cdce2bb488c2d4f222da23c7b64e8efcc..b42a14ced24a7146fac4929c65a254eb6a58d152 100644 --- a/src/main/java/org/beetl/core/misc/ALU.java +++ b/src/main/java/org/beetl/core/misc/ALU.java @@ -459,9 +459,7 @@ public class ALU { case SHORT: double c = ((Number) o2).doubleValue(); if (c == 0) { - BeetlException ex = new BeetlException(BeetlException.DIV_ZERO_ERROR); - ex.pushToken(node2.token); - throw ex; + throw new BeetlException(BeetlException.DIV_ZERO_ERROR).pushToken(node2.token); } double a = ((Number) o1).doubleValue() / ((Number) o2).doubleValue(); return trim(a, (Number) o1, (Number) o2); @@ -610,10 +608,11 @@ public class ALU { return b1.compareTo(b2) > 0; default: int result = compareObject(o1, o2, node1, node2, ">"); - if (result == -2) + if (result == -2) { throw UnsupportedTypeException(o1, o2, node1, node2, ">"); - else + } else { return result > 0; + } } } else { throw valueIsNullException(o1, o2, node1, node2); @@ -645,10 +644,11 @@ public class ALU { return b1.compareTo(b2) >= 0; default: int result = compareObject(o1, o2, node1, node2, ">="); - if (result == -2) + if (result == -2) { throw UnsupportedTypeException(o1, o2, node1, node2, ">="); - else + } else { return result >= 0; + } } } else { throw valueIsNullException(o1, o2, node1, node2); @@ -680,10 +680,11 @@ public class ALU { return b1.compareTo(b2) < 0; default: int result = compareObject(o1, o2, node1, node2, "<"); - if (result == -2) + if (result == -2) { throw UnsupportedTypeException(o1, o2, node1, node2, "<"); - else + } else { return result < 0; + } } } else { throw valueIsNullException(o1, o2, node1, node2); @@ -715,10 +716,11 @@ public class ALU { return b1.compareTo(b2) <= 0; default: int result = compareObject(o1, o2, node1, node2, "<="); - if (result == -2) + if (result == -2) { throw UnsupportedTypeException(o1, o2, node1, node2, "<="); - else + } else { return result <= 0; + } } } else { throw valueIsNullException(o1, o2, node1, node2); @@ -732,19 +734,17 @@ public class ALU { Comparable ac = (Comparable) a; try { int result = ac.compareTo(b); - if (result > 0) + if (result > 0) { return 1; - else if (result < 0) + } else if (result < 0) { return -1; + } return result; } catch (RuntimeException e) { - BeetlException ex = new BeetlException(BeetlException.EXPRESSION_NOT_COMPATIBLE, e); - GrammarToken token = GrammarToken.createToken(node1.token.text + " " + node2.token.text, - node1.token.line); - ex.pushToken(token); - throw ex; + throw new BeetlException(BeetlException.EXPRESSION_NOT_COMPATIBLE, e) + .pushToken(GrammarToken.createToken(node1.token.text + " " + node2.token.text, + node1.token.line)); } - } else { return -2; } @@ -752,57 +752,36 @@ public class ALU { private static RuntimeException UnsupportedTypeException(final Object o1, final Object o2, final ASTNode node1, final ASTNode node2, String type) { - BeetlException ex = new BeetlException(BeetlException.EXPRESSION_NOT_COMPATIBLE, o1.getClass() + type - + o2.getClass()); - GrammarToken token = GrammarToken.createToken(node1.token.text + type + node2.token.text, node1.token.line); - ex.pushToken(token); - throw ex; + String tagName = node1.token.text + type + node2.token.text; + throw new BeetlException(BeetlException.EXPRESSION_NOT_COMPATIBLE, o1.getClass() + type + o2.getClass()) + .pushToken(GrammarToken.createToken(tagName, node1.token.line)); } private static RuntimeException numberExpectedException(final Object o1, ASTNode node1) { - BeetlException ex = new BeetlException(BeetlException.NUMBER_EXPECTED_ERROR); - ex.pushToken(node1.token); - - throw ex; + throw new BeetlException(BeetlException.NUMBER_EXPECTED_ERROR).pushToken(node1.token); } private static RuntimeException valueIsNullException(final Object o1, ASTNode node1) { - BeetlException ex = new BeetlException(BeetlException.NULL); - ex.pushToken(node1.token); - throw ex; + throw new BeetlException(BeetlException.NULL).pushToken(node1.token); } - private static BeetlException valueIsNullException(final Object o1, final Object o2, final ASTNode node1, - final ASTNode node2) { - BeetlException ex = null; - if (o1 == null) { - ex = new BeetlException(BeetlException.NULL); - ex.pushToken(node1.token); - } else { - ex = new BeetlException(BeetlException.NULL); - ex.pushToken(node2.token); - } - throw ex; - + private static BeetlException valueIsNullException(final Object o1, final Object o2, + final ASTNode node1, final ASTNode node2) { + throw o1 == null + ? new BeetlException(BeetlException.NULL).pushToken(node1.token) + : new BeetlException(BeetlException.NULL).pushToken(node2.token); } private static BigDecimal getBigDecimal(Object o) { - if (o instanceof BigDecimal) { - return (BigDecimal) o; - } else { - return new BigDecimal(o.toString()); - } + return o instanceof BigDecimal ? (BigDecimal) o : new BigDecimal(String.valueOf(o)); } /** * */ public static Boolean isTrue(final Object o, ASTNode node) { - if (o == null) { - BeetlException be = new BeetlException(BeetlException.NULL); - be.pushToken(node.token); - throw be; + throw new BeetlException(BeetlException.NULL).pushToken(node.token); } if (Boolean.TRUE == o) { @@ -812,9 +791,8 @@ public class ALU { } else if (o instanceof Boolean) { return ((Boolean) o); } else { - BeetlException ex = new BeetlException(BeetlException.BOOLEAN_EXPECTED_ERROR, o.getClass().toString()); - ex.pushToken(node.token); - throw ex; + throw new BeetlException(BeetlException.BOOLEAN_EXPECTED_ERROR, o.getClass().toString()) + .pushToken(node.token); } } } diff --git a/src/main/java/org/beetl/core/parser/BeetlAntlrErrorStrategy.java b/src/main/java/org/beetl/core/parser/BeetlAntlrErrorStrategy.java index 78c32a9a4088d8c0f9c1cdf4f58ba4d93ec673d4..09134dacb1369b3beb723a4eb6ec77c125178d2b 100644 --- a/src/main/java/org/beetl/core/parser/BeetlAntlrErrorStrategy.java +++ b/src/main/java/org/beetl/core/parser/BeetlAntlrErrorStrategy.java @@ -46,232 +46,178 @@ import org.beetl.core.statement.GrammarToken; /** * antlr 语法解析错的处理策略。对所有语法错误,都抛出以阻止继续解析 - * @author xiandafu * + * @author xiandafu */ -public class BeetlAntlrErrorStrategy extends DefaultErrorStrategy -{ - - static HashSet keys = new HashSet(); - static Map expects = new HashMap(); - static{ - expects.put("LEFT_PAR", "("); - expects.put("RIGHT_PAR", ")"); - - } - static { - keys.add("select"); - keys.add("if"); - keys.add("for"); - keys.add("elsefor"); - keys.add("while"); - keys.add("switch"); - keys.add("return"); - keys.add("break"); - keys.add("var"); - keys.add("continue"); - keys.add("directive"); - keys.add("in"); - keys.add("case"); - keys.add("default"); - keys.add("try"); - keys.add("catch"); - - } - @Override - public void recover(Parser recognizer, RecognitionException e) - { - - //不会执行到此处,因为在report部分就抛出异常了 - super.recover(recognizer, e); - } - - @Override - public void reportError(Parser recognizer, RecognitionException e) - { - // if we've already reported an error and have not matched a token - // yet successfully, don't report any errors. - if (inErrorRecoveryMode(recognizer)) - { - // System.err.print("[SPURIOUS] "); - return; // don't report spurious errors - } - beginErrorCondition(recognizer); - if (e instanceof NoViableAltException) - { - reportNoViableAlternative(recognizer, (NoViableAltException) e); - } - else if (e instanceof InputMismatchException) - { - reportInputMismatch(recognizer, (InputMismatchException) e); - } - else if (e instanceof FailedPredicateException) - { - reportFailedPredicate(recognizer, (FailedPredicateException) e); - } - else - { - // System.err.println("unknown recognition error type: " + e.getClass().getName()); - BeetlException exception = new BeetlException(BeetlException.PARSER_UNKNOW_ERROR, e.getClass().getName(), e); - // exception.token = this.getGrammarToken(e.getOffendingToken()); - exception.pushToken(this.getGrammarToken(e.getOffendingToken())); - - throw exception; - } - - } - - protected void reportNoViableAlternative(Parser recognizer, NoViableAltException e) - { - TokenStream tokens = recognizer.getInputStream(); - String input; - if (tokens instanceof TokenStream) - { - if (e.getStartToken().getType() == Token.EOF) - input = "<文件尾>"; - else - input = tokens.getText(e.getStartToken(), e.getOffendingToken()); - } - else - { - input = "<未知输入>"; - } - BeetlException exception = null; - if(keys.contains(e.getOffendingToken().getText())){ - exception = new BeetlParserException(BeetlException.PARSER_VIABLE_ERROR, - "不允许"+e.getOffendingToken().getText()+"关键出现在这里"+":"+escapeWSAndQuote(input), e); - }else{ - exception = new BeetlParserException(BeetlException.PARSER_VIABLE_ERROR, - escapeWSAndQuote(input), e); - } - // String msg = "no viable alternative at input " + escapeWSAndQuote(input); - - exception.pushToken(this.getGrammarToken(e.getOffendingToken())); - - throw exception; - } - - protected void reportInputMismatch(Parser recognizer, InputMismatchException e) - { - Token t1 = recognizer.getInputStream().LT(-1); - String msg = "缺少输入在 " + getTokenErrorDisplay(t1) + " 后面, 期望 " - + e.getExpectedTokens().toString(recognizer.getVocabulary()); - BeetlException exception = new BeetlParserException(BeetlException.PARSER_MISS_ERROR, msg, e); - // exception.token = this.getGrammarToken(e.getOffendingToken()); - exception.pushToken(this.getGrammarToken(t1)); - - throw exception; - - } - - protected void reportFailedPredicate(Parser recognizer, FailedPredicateException e) - { - String ruleName = recognizer.getRuleNames()[recognizer.getContext().getRuleIndex()]; - BeetlException exception = new BeetlParserException(BeetlException.PARSER_PREDICATE_ERROR, ruleName, e); - // exception.token = this.getGrammarToken(e.getOffendingToken()); - exception.pushToken(this.getGrammarToken(e.getOffendingToken())); - - throw exception; - } - - /** Make sure we don't attempt to recover from problems in subrules. */ - @Override - public void sync(Parser recognizer) - { - } - - /** Make sure we don't attempt to recover inline; if the parser - * successfully recovers, it won't throw an exception. - */ - @Override - public Token recoverInline(Parser recognizer) throws RecognitionException - { - // SINGLE TOKEN DELETION - Token matchedSymbol = singleTokenDeletion(recognizer); - if (matchedSymbol != null) - { - // we have deleted the extra token. - // now, move past ttype token as if all were ok - recognizer.consume(); - return matchedSymbol; - } - - // SINGLE TOKEN INSERTION - if (singleTokenInsertion(recognizer)) - { - return getMissingSymbol(recognizer); - } +public class BeetlAntlrErrorStrategy extends DefaultErrorStrategy { + + static HashSet keys = new HashSet<>(); + static Map expects = new HashMap<>(); + + static { + expects.put("LEFT_PAR", "("); + expects.put("RIGHT_PAR", ")"); + + } + + static { + keys.add("select"); + keys.add("if"); + keys.add("for"); + keys.add("elsefor"); + keys.add("while"); + keys.add("switch"); + keys.add("return"); + keys.add("break"); + keys.add("var"); + keys.add("continue"); + keys.add("directive"); + keys.add("in"); + keys.add("case"); + keys.add("default"); + keys.add("try"); + keys.add("catch"); + + } + + @Override + public void recover(Parser recognizer, RecognitionException e) { + //不会执行到此处,因为在report部分就抛出异常了 + super.recover(recognizer, e); + } + + @Override + public void reportError(Parser recognizer, RecognitionException e) { + // if we've already reported an error and have not matched a token + // yet successfully, don't report any errors. + if (inErrorRecoveryMode(recognizer)) { + // System.err.print("[SPURIOUS] "); + return; // don't report spurious errors + } + beginErrorCondition(recognizer); + if (e instanceof NoViableAltException) { + reportNoViableAlternative(recognizer, (NoViableAltException) e); + } else if (e instanceof InputMismatchException) { + reportInputMismatch(recognizer, (InputMismatchException) e); + } else if (e instanceof FailedPredicateException) { + reportFailedPredicate(recognizer, (FailedPredicateException) e); + } else { + throw new BeetlException(BeetlException.PARSER_UNKNOW_ERROR, e.getClass().getName(), e) + .pushToken(this.getGrammarToken(e.getOffendingToken())); + } + + } + + protected void reportNoViableAlternative(Parser recognizer, NoViableAltException e) { + TokenStream tokens = recognizer.getInputStream(); + String input = tokens == null ? "<未知输入>" + : e.getStartToken().getType() == Token.EOF ? "<文件尾>" + : tokens.getText(e.getStartToken(), e.getOffendingToken()); + String msg = keys.contains(e.getOffendingToken().getText()) + ? "不允许" + e.getOffendingToken().getText() + "关键出现在这里" + ":" + escapeWSAndQuote(input) + : escapeWSAndQuote(input); + throw new BeetlParserException(BeetlException.PARSER_VIABLE_ERROR, msg, e) + .pushToken(this.getGrammarToken(e.getOffendingToken())); + } + + protected void reportInputMismatch(Parser recognizer, InputMismatchException e) { + Token t1 = recognizer.getInputStream().LT(-1); + String msg = "缺少输入在 " + getTokenErrorDisplay(t1) + " 后面, 期望 " + + e.getExpectedTokens().toString(recognizer.getVocabulary()); + throw new BeetlParserException(BeetlException.PARSER_MISS_ERROR, msg, e) + .pushToken(this.getGrammarToken(t1)); + + } + + protected void reportFailedPredicate(Parser recognizer, FailedPredicateException e) { + String ruleName = recognizer.getRuleNames()[recognizer.getContext().getRuleIndex()]; + throw new BeetlParserException(BeetlException.PARSER_PREDICATE_ERROR, ruleName, e) + .pushToken(this.getGrammarToken(e.getOffendingToken())); + } + + /** Make sure we don't attempt to recover from problems in subrules. */ + @Override + public void sync(Parser recognizer) { + } + + /** + * Make sure we don't attempt to recover inline; if the parser + * successfully recovers, it won't throw an exception. + */ + @Override + public Token recoverInline(Parser recognizer) throws RecognitionException { + // SINGLE TOKEN DELETION + Token matchedSymbol = singleTokenDeletion(recognizer); + if (matchedSymbol != null) { + // we have deleted the extra token. + // now, move past ttype token as if all were ok + recognizer.consume(); + return matchedSymbol; + } + + // SINGLE TOKEN INSERTION + if (singleTokenInsertion(recognizer)) { + return getMissingSymbol(recognizer); + } // BeetlException exception = new BeetlParserException(BeetlException.PARSER_MISS_ERROR); // exception.pushToken(this.getGrammarToken(recognizer.getCurrentToken())); // throw exception; - throw new InputMismatchException(recognizer); - } - - protected void reportMissingToken(Parser recognizer) - { - if (inErrorRecoveryMode(recognizer)) - { - return; - } - - beginErrorCondition(recognizer); - -// Token t = recognizer.getCurrentToken(); - Token t = recognizer.getTokenStream().LT(-1); - IntervalSet expecting = getExpectedTokens(recognizer); - String expect = expecting.toString(recognizer.getVocabulary()); - if(expects.containsKey(expect)){ - expect = expects.get(expect); - } - if(expect.equals("'>>'")){ - expect = "'模板的占位结束符号'"; - } - - String tokenStr = getTokenErrorDisplay(t); - String msg = null; - if(expect.equals("'}'")&&tokenStr.equals("'>>'")) { - msg = "未找到 '{' 匹配的结束符号 '}'"; - }else { - //常规情况 - msg = "缺少输入 " + expect + " 在 " + tokenStr+" 后面"; - } - - BeetlException exception = new BeetlParserException(BeetlException.PARSER_MISS_ERROR, msg); - exception.pushToken(this.getGrammarToken(t)); - throw exception; - } - - protected void reportUnwantedToken(Parser recognizer) - { - if (inErrorRecoveryMode(recognizer)) - { - return; - } - - beginErrorCondition(recognizer); - - Token t = recognizer.getCurrentToken(); - String tokenName = getTokenErrorDisplay(t); - IntervalSet expecting = getExpectedTokens(recognizer); - String key = getErrorKey(expecting.toString(recognizer.getVocabulary())); - String msg = "多余输入 " + tokenName + " 期望 " + key; - BeetlException exception = new BeetlParserException(BeetlException.PARSER_MISS_ERROR, msg); - // exception.token = this.getGrammarToken(t); - exception.pushToken(this.getGrammarToken(t)); - throw exception; - } - - protected String getErrorKey(String key) { - if(key.equals("'>>'")) { - return "占位结束符号"; - } - return key; - } - - protected GrammarToken getGrammarToken(Token token) - { - return GrammarToken.createToken(token.getText(), token.getLine()); - } + throw new InputMismatchException(recognizer); + } + + protected void reportMissingToken(Parser recognizer) { + if (inErrorRecoveryMode(recognizer)) { + return; + } + + beginErrorCondition(recognizer); + + Token t = recognizer.getTokenStream().LT(-1); + IntervalSet expecting = getExpectedTokens(recognizer); + String expect = expecting.toString(recognizer.getVocabulary()); + if (expects.containsKey(expect)) { + expect = expects.get(expect); + } + if (expect.equals("'>>'")) { + expect = "'模板的占位结束符号'"; + } + + String tokenStr = getTokenErrorDisplay(t); + String msg = null; + if (expect.equals("'}'") && tokenStr.equals("'>>'")) { + msg = "未找到 '{' 匹配的结束符号 '}'"; + } else { + //常规情况 + msg = "缺少输入 " + expect + " 在 " + tokenStr + " 后面"; + } + throw new BeetlParserException(BeetlException.PARSER_MISS_ERROR, msg).pushToken(this.getGrammarToken(t)); + } + + protected void reportUnwantedToken(Parser recognizer) { + if (inErrorRecoveryMode(recognizer)) { + return; + } + + beginErrorCondition(recognizer); + + Token t = recognizer.getCurrentToken(); + String tokenName = getTokenErrorDisplay(t); + IntervalSet expecting = getExpectedTokens(recognizer); + String key = getErrorKey(expecting.toString(recognizer.getVocabulary())); + String msg = "多余输入 " + tokenName + " 期望 " + key; + throw new BeetlParserException(BeetlException.PARSER_MISS_ERROR, msg).pushToken(this.getGrammarToken(t)); + } + + protected String getErrorKey(String key) { + if (key.equals("'>>'")) { + return "占位结束符号"; + } + return key; + } + + protected GrammarToken getGrammarToken(Token token) { + return GrammarToken.createToken(token.getText(), token.getLine()); + } } diff --git a/src/main/java/org/beetl/core/parser/SyntaxErrorListener.java b/src/main/java/org/beetl/core/parser/SyntaxErrorListener.java index 50dd42c07664c5491c62e19ea018d9bfadaede53..00a2ddb5001d0cc6a6e9e76b9ce137724b63cbbe 100644 --- a/src/main/java/org/beetl/core/parser/SyntaxErrorListener.java +++ b/src/main/java/org/beetl/core/parser/SyntaxErrorListener.java @@ -10,10 +10,7 @@ import org.beetl.core.statement.GrammarToken; public class SyntaxErrorListener extends BaseErrorListener { public void syntaxError(Recognizer recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { - - BeetlException be = new BeetlException(BeetlException.TOKEN_ERROR); - be.token = new GrammarToken(BeetlUtil.reportChineseTokenError(msg), line, charPositionInLine); - throw be; - + throw new BeetlException(BeetlException.TOKEN_ERROR) + .setToken(new GrammarToken(BeetlUtil.reportChineseTokenError(msg), line, charPositionInLine)); } } diff --git a/src/main/java/org/beetl/core/resource/ClasspathResource.java b/src/main/java/org/beetl/core/resource/ClasspathResource.java index 2627c9049fd49c672a5ce6b7262e4ac72ddec117..f243b1e85ce65a47829fb914c0be779c6073607c 100644 --- a/src/main/java/org/beetl/core/resource/ClasspathResource.java +++ b/src/main/java/org/beetl/core/resource/ClasspathResource.java @@ -65,23 +65,17 @@ public class ClasspathResource extends Resource { } if (url == null) { - BeetlException be = new BeetlException(BeetlException.TEMPLATE_LOAD_ERROR); - be.pushResource(this); - throw be; + throw new BeetlException(BeetlException.TEMPLATE_LOAD_ERROR).pushResource(this); } InputStream is; try { is = url.openStream(); } catch (IOException e1) { - BeetlException be = new BeetlException(BeetlException.TEMPLATE_LOAD_ERROR); - be.pushResource(this); - throw be; + throw new BeetlException(BeetlException.TEMPLATE_LOAD_ERROR).pushResource(this); } if (is == null) { - BeetlException be = new BeetlException(BeetlException.TEMPLATE_LOAD_ERROR); - be.pushResource(this); - throw be; + throw new BeetlException(BeetlException.TEMPLATE_LOAD_ERROR).pushResource(this); } if (url.getProtocol().equals("file")) { diff --git a/src/main/java/org/beetl/core/resource/CompositeResourceLoader.java b/src/main/java/org/beetl/core/resource/CompositeResourceLoader.java index d1f614df19310233a5d91942bf12639f1d2596bc..8ac94e0f5eecbf89884299804709317cedcce37c 100644 --- a/src/main/java/org/beetl/core/resource/CompositeResourceLoader.java +++ b/src/main/java/org/beetl/core/resource/CompositeResourceLoader.java @@ -97,8 +97,9 @@ public class CompositeResourceLoader implements ResourceLoader { @Override public boolean exist(String key) { ResourceLoaderKeyEntry rlke = this.match(key); - if (rlke == null) + if (rlke == null) { return false; + } return rlke.getResourceLoader().exist(rlke.getNewKey()); } @@ -170,22 +171,21 @@ public class CompositeResourceLoader implements ResourceLoader { @Override public Reader openReader() { - BeetlException be = new BeetlException(BeetlException.TEMPLATE_LOAD_ERROR, "复合资源加载器未匹配路径:" + this.id); - be.pushResource(this); - throw be; + throw new BeetlException(BeetlException.TEMPLATE_LOAD_ERROR, "复合资源加载器未匹配路径:" + this.id) + .pushResource(this); } @Override public boolean isModified() { - return true; } } @Override public String getResourceId(Resource resource, String id) { - if (resource == null) + if (resource == null) { return id; + } //判断如果是同一前缀,则需要考虑相对路径 ResourceLoaderKeyEntry rlke = this.match(id); return (resource.getResourceLoader() == rlke.getResourceLoader()) diff --git a/src/main/java/org/beetl/core/resource/MapResourceLoader.java b/src/main/java/org/beetl/core/resource/MapResourceLoader.java index 1d3b02ec036da9ba19b4bbc85579394978a5e098..d62a06714170f1f75e6ce56facf4212aaec472ba 100644 --- a/src/main/java/org/beetl/core/resource/MapResourceLoader.java +++ b/src/main/java/org/beetl/core/resource/MapResourceLoader.java @@ -36,9 +36,7 @@ public class MapResourceLoader extends HashMap implements Resour public Reader openReader() { String val = get(key); if (val == null) { - BeetlException ex = new BeetlException(BeetlException.TEMPLATE_LOAD_ERROR); - ex.pushResource(this); - throw ex; + throw new BeetlException(BeetlException.TEMPLATE_LOAD_ERROR).pushResource(this); } return new StringReader(val); } diff --git a/src/main/java/org/beetl/core/statement/ForStatement.java b/src/main/java/org/beetl/core/statement/ForStatement.java index e3edae68521267cda5a48f6acdaf7ad203d91534..dc81940425e4937358a1aaf923af47c0eca04a48 100644 --- a/src/main/java/org/beetl/core/statement/ForStatement.java +++ b/src/main/java/org/beetl/core/statement/ForStatement.java @@ -70,9 +70,7 @@ public final class ForStatement extends Statement implements IGoto { ILoopStatus it = null; if (collection == null) { if (!(this.hasSafe || ctx.safeOutput)) { - BeetlException ex = new BeetlException(BeetlException.NULL); - ex.pushToken(exp.token); - throw ex; + throw new BeetlException(BeetlException.NULL).pushToken(exp.token); } else { it = new GeneralLoopStatus(Collections.EMPTY_LIST); } @@ -80,10 +78,9 @@ public final class ForStatement extends Statement implements IGoto { } else { it = GeneralLoopStatus.getIteratorStatus(collection); if (it == null) { - BeetlParserException ex = new BeetlParserException(BeetlParserException.COLLECTION_EXPECTED_ERROR, - "实际类型是:" + collection.getClass()); - ex.pushToken(exp.token); - throw ex; + throw new BeetlParserException(BeetlParserException.COLLECTION_EXPECTED_ERROR, + "实际类型是:" + collection.getClass()) + .pushToken(exp.token); } } @@ -112,7 +109,9 @@ public final class ForStatement extends Statement implements IGoto { } if (!it.hasData()) { - if (elseforPart != null) elseforPart.execute(ctx); + if (elseforPart != null) { + elseforPart.execute(ctx); + } } return; @@ -123,7 +122,9 @@ public final class ForStatement extends Statement implements IGoto { } if (!it.hasData()) { - if (elseforPart != null) elseforPart.execute(ctx); + if (elseforPart != null) { + elseforPart.execute(ctx); + } } } diff --git a/src/main/java/org/beetl/core/statement/FormatExpression.java b/src/main/java/org/beetl/core/statement/FormatExpression.java index 580e87e99cf07cdda8a75b9de99f7302cd6e3054..48405facf7874a7a53d853d706de2cac5d9c3783 100644 --- a/src/main/java/org/beetl/core/statement/FormatExpression.java +++ b/src/main/java/org/beetl/core/statement/FormatExpression.java @@ -55,33 +55,27 @@ public class FormatExpression extends Expression { } public Object evaluateValue(Object o, Context ctx) { - Format format = null; if (name != null) { format = ctx.gt.getFormat(name); } else { - if (o == null) return null; + if (o == null) { + return null; + } format = ctx.gt.getDefaultFormat(o.getClass()); } if (format == null) { - BeetlException ex = new BeetlException(BeetlException.FORMAT_NOT_FOUND); - ex.pushToken(token); - throw ex; + throw new BeetlException(BeetlException.FORMAT_NOT_FOUND).pushToken(token); } try { - if (format instanceof ContextFormat) { - return ((ContextFormat) format).format(o, pattern, ctx); - } else { - return format.format(o, pattern); - } - + return format instanceof ContextFormat + ? ((ContextFormat) format).format(o, pattern, ctx) + : format.format(o, pattern); } catch (Exception e) { - BeetlException ex = new BeetlException(BeetlException.NATIVE_CALL_EXCEPTION, "调用格式化函数抛出异常", e); - ex.pushToken(token); - throw ex; + throw new BeetlException(BeetlException.NATIVE_CALL_EXCEPTION, "调用格式化函数抛出异常", e) + .pushToken(token); } - } public String getName() { diff --git a/src/main/java/org/beetl/core/statement/FunctionExpression.java b/src/main/java/org/beetl/core/statement/FunctionExpression.java index 4555d7e0edc4b7c7d843d0599846d44b78d93ffd..7c345c5bf62d8d898aa1f787e7749f1efaa53b4a 100644 --- a/src/main/java/org/beetl/core/statement/FunctionExpression.java +++ b/src/main/java/org/beetl/core/statement/FunctionExpression.java @@ -64,13 +64,10 @@ public class FunctionExpression extends Expression { // 检查html实现 Resource resource = getResource(ctx.gt, name); - if (resource!=null&&resource.getResourceLoader().exist(resource.getId())) { + if (resource != null && resource.getResourceLoader().exist(resource.getId())) { fn = new FileFunctionWrapper(resource.getId().toString()); - } else { - BeetlException ex = new BeetlException(BeetlException.FUNCTION_NOT_FOUND); - ex.pushToken(token); - throw ex; + throw new BeetlException(BeetlException.FUNCTION_NOT_FOUND).pushToken(token); } } @@ -83,53 +80,38 @@ public class FunctionExpression extends Expression { try { value = fn.call(paras, ctx); } catch (BeetlException ex) { - ex.pushToken(token); - throw ex; + throw ex.pushToken(token); } catch (RuntimeException ex) { - BeetlException be = new BeetlException(BeetlException.NATIVE_CALL_EXCEPTION, "调用方法出错 " + name, ex); - be.pushToken(this.token); - throw be; + throw new BeetlException(BeetlException.NATIVE_CALL_EXCEPTION, "调用方法出错 " + name, ex) + .pushToken(this.token); } - Object ret = null; - - if (vas == null) { - ret = value; - } else { - + if (vas != null) { for (VarAttribute attr : vas) { try { value = attr.evaluate(ctx, value); } catch (BeetlException ex) { - ex.pushToken(attr.token); - throw ex; - + throw ex.pushToken(attr.token); } catch (RuntimeException ex) { - BeetlException be = new BeetlException(BeetlException.ATTRIBUTE_INVALID, "属性访问出错", ex); - be.pushToken(attr.token); - throw be; + throw new BeetlException(BeetlException.ATTRIBUTE_INVALID, "属性访问出错", ex).pushToken(attr.token); } if (value == null) { if (hasSafe) { return safeExp == null ? null : safeExp.evaluate(ctx); } else { - BeetlException be = new BeetlException(BeetlException.ERROR, "空指针 "); - be.pushToken(attr.token); - throw be; + throw new BeetlException(BeetlException.ERROR, "空指针 ").pushToken(attr.token); } - } } - ret = value; } - if (ret == null && hasSafe) { + if (value == null && hasSafe) { return safeExp == null ? null : safeExp.evaluate(ctx); } else { - return ret; + return value; } } @@ -140,7 +122,6 @@ public class FunctionExpression extends Expression { String functionRoot = resourceMap.get("functionRoot"); String path = name.replace(".", "/"); return gt.getResourceLoader().getResource(functionRoot + "/" + path + "." + functionSuffix); - } } diff --git a/src/main/java/org/beetl/core/statement/NativeCallExpression.java b/src/main/java/org/beetl/core/statement/NativeCallExpression.java index 1ae31340c42ab2626d9af813c3e483a5c7a47856..7088783a51b71e4e418640627551be300fa781b9 100644 --- a/src/main/java/org/beetl/core/statement/NativeCallExpression.java +++ b/src/main/java/org/beetl/core/statement/NativeCallExpression.java @@ -55,11 +55,9 @@ public class NativeCallExpression extends Expression { lastNode = insNode; } else { targetCls = ctx.gt.loadClassBySimpleName(this.clsNode.clazz); - if (targetCls == null) { - BeetlException be = new BeetlException(BeetlException.NATIVE_CALL_EXCEPTION, "该类不存在"); - be.pushToken(GrammarToken.createToken(clsNode.clazz, token.line)); - throw be; + throw new BeetlException(BeetlException.NATIVE_CALL_EXCEPTION, "该类不存在") + .pushToken(GrammarToken.createToken(clsNode.clazz, token.line)); } lastNode = clsNode; @@ -77,44 +75,33 @@ public class NativeCallExpression extends Expression { } targetObj = f.get(targetObj); targetCls = f.getType(); - } catch (SecurityException e) { - BeetlException be = new BeetlException(BeetlException.NATIVE_CALL_EXCEPTION, "不能调用属性", e); - be.pushToken(GrammarToken.createToken(attr, token.line)); - throw be; + throw new BeetlException(BeetlException.NATIVE_CALL_EXCEPTION, "不能调用属性", e) + .pushToken(GrammarToken.createToken(attr, token.line)); } catch (NoSuchFieldException e) { - BeetlException be = new BeetlException(BeetlException.NATIVE_CALL_EXCEPTION, "无此属性", e); - be.pushToken(GrammarToken.createToken(attr, token.line)); - throw be; + throw new BeetlException(BeetlException.NATIVE_CALL_EXCEPTION, "无此属性", e) + .pushToken(GrammarToken.createToken(attr, token.line)); } catch (IllegalArgumentException | IllegalAccessException e) { - BeetlException be = new BeetlException(BeetlException.NATIVE_CALL_EXCEPTION, "访问属性出错", e); - be.pushToken(GrammarToken.createToken(attr, token.line)); - throw be; + throw new BeetlException(BeetlException.NATIVE_CALL_EXCEPTION, "访问属性出错", e) + .pushToken(GrammarToken.createToken(attr, token.line)); } } else if (node instanceof NativeArrayNode) { checkNull(targetCls, lastNode); if (!targetCls.isArray()) { - BeetlException be = new BeetlException(BeetlException.ARRAY_TYPE_ERROR); // 最好是把上一个字符显示出来 - be.pushToken(GrammarToken.createToken("[]", token.line)); - throw be; + throw new BeetlException(BeetlException.ARRAY_TYPE_ERROR) + .pushToken(GrammarToken.createToken("[]", token.line)); } Expression exp = ((NativeArrayNode) node).exp; Object value = exp.evaluate(ctx); if (value instanceof Number) { int index = ((Number) value).intValue(); targetObj = ((Object[]) targetObj)[index]; - if (targetObj != null) { - targetCls = targetObj.getClass(); - } else { - // todo or component of array - targetCls = null; - } + targetCls = targetObj == null ? null : targetObj.getClass(); // todo or component of array } else { - BeetlException be = new BeetlException(BeetlException.ARRAY_INDEX_ERROR, "数组指针必须是Number类型"); - be.pushToken(GrammarToken.createToken("[]", token.line)); - throw be; + throw new BeetlException(BeetlException.ARRAY_INDEX_ERROR, "数组指针必须是Number类型") + .pushToken(GrammarToken.createToken("[]", token.line)); } } else if (node instanceof NativeMethodNode) { NativeMethodNode methodNode = (NativeMethodNode) node; @@ -127,50 +114,35 @@ public class NativeCallExpression extends Expression { for (int i = 0; i < expList.length; i++) { args[i] = expList[i].evaluate(ctx); parameterType[i] = args[i] == null ? null : args[i].getClass(); - } this.checkNull(targetCls, lastNode); ObjectMethodMatchConf mf = ObjectUtil.findMethod(targetCls, method, parameterType); if (mf == null) { - BeetlException ex = new BeetlException(BeetlParserException.NATIVE_CALL_INVALID, - "根据参数未找到匹配的方法" + method + BeetlUtil.getParameterDescription(parameterType)); - ex.pushToken(GrammarToken.createToken(token.text, token.line)); - throw ex; + throw new BeetlException(BeetlParserException.NATIVE_CALL_INVALID, + "根据参数未找到匹配的方法" + method + BeetlUtil.getParameterDescription(parameterType)) + .pushToken(GrammarToken.createToken(token.text, token.line)); } if (targetObj == null && !Modifier.isStatic(mf.method.getModifiers())) { - BeetlException ex = new BeetlException(BeetlException.NULL); - ex.pushToken(GrammarToken.createToken(token.text, token.line)); - throw ex; + throw new BeetlException(BeetlException.NULL) + .pushToken(GrammarToken.createToken(token.text, token.line)); } try { - targetObj = ObjectUtil.invoke(targetObj, mf, args); - - if (targetObj != null) { - targetCls = targetObj.getClass(); - } else { - targetCls = null; - } - + targetCls = targetObj == null ? null : targetObj.getClass(); } catch (SecurityException e) { - BeetlException be = new BeetlException(BeetlException.NATIVE_CALL_EXCEPTION, "不能调用方法", e); - be.pushToken(GrammarToken.createToken(method, token.line)); - throw be; + throw new BeetlException(BeetlException.NATIVE_CALL_EXCEPTION, "不能调用方法", e) + .pushToken(GrammarToken.createToken(method, token.line)); } catch (IllegalArgumentException e) { - BeetlException be = new BeetlException(BeetlException.NATIVE_CALL_EXCEPTION, "错误的参数", e); - be.pushToken(GrammarToken.createToken(method, token.line)); - throw be; + throw new BeetlException(BeetlException.NATIVE_CALL_EXCEPTION, "错误的参数", e) + .pushToken(GrammarToken.createToken(method, token.line)); } catch (IllegalAccessException e) { - BeetlException be = new BeetlException(BeetlException.NATIVE_CALL_EXCEPTION, "无法访问方法", e); - be.pushToken(GrammarToken.createToken(method, token.line)); - throw be; + throw new BeetlException(BeetlException.NATIVE_CALL_EXCEPTION, "无法访问方法", e) + .pushToken(GrammarToken.createToken(method, token.line)); } catch (InvocationTargetException e) { - BeetlException be = new BeetlException(BeetlException.NATIVE_CALL_EXCEPTION, "内部调用报错", - e.getTargetException()); - be.pushToken(GrammarToken.createToken(method, token.line)); - throw be; + throw new BeetlException(BeetlException.NATIVE_CALL_EXCEPTION, "内部调用报错", e.getTargetException()) + .pushToken(GrammarToken.createToken(method, token.line)); } } @@ -183,24 +155,22 @@ public class NativeCallExpression extends Expression { private void checkNull(Object o, NativeNode node) { if (o == null) { - - BeetlException be = new BeetlException(BeetlException.NULL); - be.pushToken(GrammarToken.createToken(node.getName(), token.line)); - throw be; - + throw new BeetlException(BeetlException.NULL) + .pushToken(GrammarToken.createToken(node.getName(), token.line)); } } private void checkPermit(Context ctx, Class targetCls, Object targetObj, String method) { - if (targetCls == null) return; - NativeSecurityManager securityManager = ctx.gt.getNativeSecurity(); - if(securityManager==null){ - return ; - } + if (targetCls == null) { + return; + } + NativeSecurityManager securityManager = ctx.gt.getNativeSecurity(); + if (securityManager == null) { + return; + } if (!securityManager.permit(ctx.template.program.res.getId(), targetCls, targetObj, method)) { - BeetlException be = new BeetlException(BeetlException.NATIVE_SECUARITY_EXCEPTION); - be.pushToken(GrammarToken.createToken(method, token.line)); - throw be; + throw new BeetlException(BeetlException.NATIVE_SECUARITY_EXCEPTION) + .pushToken(GrammarToken.createToken(method, token.line)); } } } diff --git a/src/main/java/org/beetl/core/statement/TryCatchStatement.java b/src/main/java/org/beetl/core/statement/TryCatchStatement.java index 085d99be73992160f8930bac88082cb2acfbf722..19db5fcac965ce8bb253f6c06072ba7f750d61c2 100644 --- a/src/main/java/org/beetl/core/statement/TryCatchStatement.java +++ b/src/main/java/org/beetl/core/statement/TryCatchStatement.java @@ -73,9 +73,7 @@ public class TryCatchStatement extends Statement { if (ex instanceof BeetlException) { throw (BeetlException) ex; } else { - BeetlException be = new BeetlException(BeetlException.ERROR, ex.getMessage(), ex); - be.pushToken(tryPart.token); - throw be; + throw new BeetlException(BeetlException.ERROR, ex.getMessage(), ex).pushToken(tryPart.token); } } } diff --git a/src/main/java/org/beetl/core/statement/VarRef.java b/src/main/java/org/beetl/core/statement/VarRef.java index a9bfd373358a60cf335ed848bc9b5a60eec7e7ae..a8efd707c7c3ef2ae772b4d4ec3cc997ac07f552 100644 --- a/src/main/java/org/beetl/core/statement/VarRef.java +++ b/src/main/java/org/beetl/core/statement/VarRef.java @@ -58,7 +58,6 @@ public class VarRef extends Expression implements IVarIndex { this.safe = safe; this.hasSafe = hasSafe; this.firstToken = firstToken; - } @Override @@ -83,28 +82,17 @@ public class VarRef extends Expression implements IVarIndex { if (hasSafe || ctx.safeOutput) { return safe == null ? null : safe.evaluate(ctx); } else { - BeetlException be = new BeetlException(BeetlException.NULL, "空指针"); - if (i == 0) { - be.pushToken(this.firstToken); - } else { - be.pushToken(attributes[i - 1].token); - } - - throw be; + throw new BeetlException(BeetlException.NULL, "空指针") + .pushToken(i == 0 ? this.firstToken : attributes[i - 1].token); } - } try { value = attr.evaluate(ctx, value); } catch (BeetlException ex) { - ex.pushToken(attr.token); - throw ex; - + throw ex.pushToken(attr.token); } catch (RuntimeException ex) { - BeetlException be = new BeetlException(BeetlException.ATTRIBUTE_INVALID, "属性访问出错", ex); - be.pushToken(attr.token); - throw be; + throw new BeetlException(BeetlException.ATTRIBUTE_INVALID, "属性访问出错", ex).pushToken(attr.token); } } @@ -145,10 +133,8 @@ public class VarRef extends Expression implements IVarIndex { if (hasSafe || ctx.safeOutput) { return new Result(safe == null ? null : safe.evaluate(ctx), true); } else { - BeetlException be = new BeetlException(BeetlException.NULL, - "_root为空指针,无" + this.firstToken.text + "值"); - be.pushToken(this.firstToken); - throw be; + throw new BeetlException(BeetlException.NULL, "_root为空指针,无" + this.firstToken.text + "值") + .pushToken(this.firstToken); } } @@ -157,10 +143,9 @@ public class VarRef extends Expression implements IVarIndex { try { value = aa.value(root, attr); } catch (RuntimeException e) { - BeetlException ex = new BeetlException(BeetlException.ATTRIBUTE_INVALID, - "访问 _root " + root.getClass() + "." + attr + " 属性访问错误"); - ex.pushToken(this.firstToken); - throw ex; + throw new BeetlException(BeetlException.ATTRIBUTE_INVALID, + "访问 _root " + root.getClass() + "." + attr + " 属性访问错误") + .pushToken(this.firstToken); } ctx.vars[varIndex] = value; @@ -210,37 +195,21 @@ public class VarRef extends Expression implements IVarIndex { Result ret = this.getValue(ctx); Object value = ret.value; if (value == null) { - BeetlException ex = new BeetlException(BeetlException.NULL); - ex.pushToken(this.firstToken); - throw ex; + throw new BeetlException(BeetlException.NULL).pushToken(this.firstToken); } for (int i = 0; i < attributes.length - 1; i++) { - VarAttribute attr = attributes[i]; if (value == null) { - - BeetlException be = new BeetlException(BeetlException.NULL, "空指针"); - if (i == 0) { - be.pushToken(this.firstToken); - } else { - be.pushToken(attributes[i - 1].token); - } - - throw be; - + throw new BeetlException(BeetlException.NULL, "空指针") + .pushToken(i == 0 ? this.firstToken : attributes[i - 1].token); } - try { value = attr.evaluate(ctx, value); } catch (BeetlException ex) { - ex.pushToken(attr.token); - throw ex; - + throw ex.pushToken(attr.token); } catch (RuntimeException ex) { - BeetlException be = new BeetlException(BeetlException.ATTRIBUTE_INVALID, "属性访问出错", ex); - be.pushToken(attr.token); - throw be; + throw new BeetlException(BeetlException.ATTRIBUTE_INVALID, "属性访问出错", ex).pushToken(attr.token); } } diff --git a/src/main/java/org/beetl/core/statement/VarRefAssignExpress.java b/src/main/java/org/beetl/core/statement/VarRefAssignExpress.java index 2eebee0dff1565177993d610f8c7dc8a569daf80..abdce2c38d863201e18ab470760e266dfe8b2373 100644 --- a/src/main/java/org/beetl/core/statement/VarRefAssignExpress.java +++ b/src/main/java/org/beetl/core/statement/VarRefAssignExpress.java @@ -60,7 +60,6 @@ public class VarRefAssignExpress extends Expression implements IVarIndex { public Object evaluate(Context ctx) { Object value = exp.evaluate(ctx); if (lastVarAttribute == null) { - ctx.vars[varIndex] = value; return value; } @@ -74,29 +73,18 @@ public class VarRefAssignExpress extends Expression implements IVarIndex { } if (obj == null) { - BeetlException bx = new BeetlException(BeetlException.NULL); - bx.pushToken(varRef.token); - throw bx; + throw new BeetlException(BeetlException.NULL).pushToken(varRef.token); } try { - AttributeAccess aa = AABuilder.buildFiledAccessor(obj.getClass()); aa.setValue(obj, key, value); - return value; - } catch (ClassCastException ex) { - BeetlException bx = new BeetlException(BeetlException.ATTRIBUTE_INVALID, ex); - bx.pushToken(lastVarAttribute.token); - throw bx; + throw new BeetlException(BeetlException.ATTRIBUTE_INVALID, ex).pushToken(lastVarAttribute.token); } catch (BeetlException be) { - be.pushToken(lastVarAttribute.token); - throw be; + throw be.pushToken(lastVarAttribute.token); } - -// return value; - } @Override diff --git a/src/main/java/org/beetl/core/statement/optimal/VarRefOptimal.java b/src/main/java/org/beetl/core/statement/optimal/VarRefOptimal.java index 95575ee672350e5ee254f2c68edc35efc4b3a792..bd95977231af35d17ebb4e93f69af3882eff65ed 100644 --- a/src/main/java/org/beetl/core/statement/optimal/VarRefOptimal.java +++ b/src/main/java/org/beetl/core/statement/optimal/VarRefOptimal.java @@ -48,20 +48,16 @@ public class VarRefOptimal extends VarRef { GrammarToken firstToken) { super(null, false, null, token, firstToken); this.attribute = attribute; - } @Override public Object evaluate(Context ctx) { - Object value = this.getRefValue(ctx); if (value == null) { if (this.hasSafe || ctx.safeOutput) { return null; } - BeetlException be = new BeetlException(BeetlException.NULL, "空指针"); - be.pushToken(this.token); - throw be; + throw new BeetlException(BeetlException.NULL, "空指针").pushToken(this.token); } try { @@ -77,9 +73,7 @@ public class VarRefOptimal extends VarRef { throw ex; } catch (RuntimeException ex) { - BeetlException be = new BeetlException(BeetlException.ATTRIBUTE_INVALID, "属性访问出错", ex); - be.pushToken(attribute.token); - throw be; + throw new BeetlException(BeetlException.ATTRIBUTE_INVALID, "属性访问出错", ex).pushToken(attribute.token); } return value; @@ -89,41 +83,34 @@ public class VarRefOptimal extends VarRef { private Object getRefValue(Context ctx) { Object value = ctx.vars[varIndex]; - if (value == Context.NOT_EXIST_OBJECT) { - if (ctx.globalVar != null && ctx.globalVar.containsKey("_root")) { - // 如果有一个根对象 - Object root = ctx.getGlobal("_root"); - - if (root == null) { - return null; - } - String attr = this.firstToken.text; - AttributeAccess aa = AABuilder.buildFiledAccessor(root.getClass()); - try { - value = aa.value(root, attr); - } catch (RuntimeException e) { - BeetlException ex = new BeetlException(BeetlException.ATTRIBUTE_INVALID, - "_root " + root.getClass() + " 属性访问错误"); - ex.pushToken(this.firstToken); - throw ex; - } - - return value; + if (value != Context.NOT_EXIST_OBJECT) { + return value; + } - } else { - return null; - } + if (ctx.globalVar == null || !ctx.globalVar.containsKey("_root")) { + return null; + } - } else { - return value; + // 如果有一个根对象 + Object root = ctx.getGlobal("_root"); + if (root == null) { + return null; + } + String attr = this.firstToken.text; + AttributeAccess aa = AABuilder.buildFiledAccessor(root.getClass()); + try { + value = aa.value(root, attr); + } catch (RuntimeException e) { + throw new BeetlException(BeetlException.ATTRIBUTE_INVALID, "_root " + root.getClass() + " 属性访问错误") + .pushToken(this.firstToken); } + return value; } @Override public void setVarIndex(int index) { this.varIndex = index; - } @Override diff --git a/src/main/java/org/beetl/core/text/HtmlTagStartFragment.java b/src/main/java/org/beetl/core/text/HtmlTagStartFragment.java index b87275e752f572f49ba1f80dc1f3cb88948d0b6d..ea5bad0f7c3980ac0a4f029adaedbfb3ce177808 100644 --- a/src/main/java/org/beetl/core/text/HtmlTagStartFragment.java +++ b/src/main/java/org/beetl/core/text/HtmlTagStartFragment.java @@ -122,14 +122,9 @@ public class HtmlTagStartFragment extends ScriptFragment { try { html.parser(); } catch (RuntimeException ex) { - BeetlException exception = new BeetlException(BeetlException.PARSER_HTML_TAG_ERROR, ex.getMessage(), ex); - String tagName = "<>"; - if (html.tagName != null) { - tagName = "<" + html.tagName + ">"; - } - GrammarToken grammarToken = GrammarToken.createToken(tagName, source.curLine + 1); - exception.pushToken(grammarToken); - throw exception; + String tagName = html.tagName == null ? "<>" : "<" + html.tagName + ">"; + throw new BeetlException(BeetlException.PARSER_HTML_TAG_ERROR, ex.getMessage(), ex) + .pushToken(GrammarToken.createToken(tagName, source.curLine + 1)); } source.move(html.index); @@ -148,14 +143,11 @@ public class HtmlTagStartFragment extends ScriptFragment { int end = 0; int index = -1; while ((index = attr.indexOf(phStart, start)) != -1) { - int holdStart = index; - while ((end = attr.indexOf(phEnd, holdStart)) != -1) { if (attr.charAt(end - 1) == '\\') { // 非占位结束符号 holdStart = end + 1; - continue; } else { break; } @@ -194,7 +186,6 @@ public class HtmlTagStartFragment extends ScriptFragment { public void appendCr() { appendCr = true; - } }