From 44bcc51df824ba05732c24bd746af413812d4db5 Mon Sep 17 00:00:00 2001 From: junhwong Date: Wed, 3 Aug 2016 12:53:17 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BB=80=E4=B9=88=E9=AC=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mano-server/hibernate.cfg.xml | 70 - .../mano-server/nb-configuration.xml | 18 - .../mano-server/nbactions.xml | 46 - del/mano-server-projects/mano-server/pom.xml | 155 --- .../com/diosay/mano/server/Bootstrap.java | 330 ----- .../main/java/mano/bootstrap/Bootstrap.java | 374 ------ .../mano/bootstrap/ConnectionManager.java | 16 - .../main/java/mano/bootstrap/DemoService.java | 258 ---- .../src/main/resources/conf.apps/app.ref.xml | 5 - .../src/main/resources/conf/app.def.xml | 7 - .../src/main/resources/conf/mano.web.xml | 26 - .../src/main/resources/conf/mano.xml | 27 - .../src/main/resources/conf/service/http.xml | 115 -- .../mano-server/src/resources/bin/run.bat | 17 - .../src/resources/conf/app.def.xml | 7 - .../mano-server/src/resources/conf/server.xml | 98 -- .../mano-web/nb-configuration.xml | 18 - del/mano-server-projects/mano-web/pom.xml | 37 - .../main/java/java/lang/MANO_WEB_MACRO.java | 18 - .../java/mano/web/HttpSessionService.java | 43 - .../main/java/mano/web/OtplViewEngine.java | 392 ------ .../mano/web/modules/StaticFileModule.java | 225 ---- .../mano/web/modules/UrlRoutingModule.java | 753 ----------- .../java/mano/web/runtime/HttpChannel.java | 153 --- .../java/mano/web/runtime/HttpListener.java | 24 - .../java/mano/web/runtime/HttpProtocol11.java | 261 ---- .../mano/web/runtime/HttpRequestImpl.java | 254 ---- .../mano/web/runtime/HttpResponseImpl.java | 289 ---- .../java/mano/web/runtime/HttpService.java | 487 ------- .../open-tpl/demo/each.html | 5 - .../open-tpl/demo/for.html | 19 - .../open-tpl/demo/func.html | 2 - .../open-tpl/demo/if.html | 25 - .../open-tpl/demo/master.html | 27 - .../open-tpl/demo/page.html | 3 - .../open-tpl/nb-configuration.xml | 18 - del/mano-server-projects/open-tpl/pom.xml | 21 - .../src/main/java/com/diosay/otpl/Block.java | 177 --- .../com/diosay/otpl/CompileException.java | 31 - .../main/java/com/diosay/otpl/Compiler.java | 1179 ----------------- .../main/java/com/diosay/otpl/Document.java | 122 -- .../main/java/com/diosay/otpl/EndBlock.java | 92 -- .../src/main/java/com/diosay/otpl/Lexer.java | 41 - .../src/main/java/com/diosay/otpl/Node.java | 160 --- .../src/main/java/com/diosay/otpl/Parser.java | 388 ------ .../src/main/java/com/diosay/otpl/Span.java | 114 -- .../main/java/com/diosay/otpl/StringUtil.java | 333 ----- .../src/main/java/com/diosay/otpl/Text.java | 101 -- .../src/main/java/com/diosay/otpl/Token.java | 70 - .../com/diosay/otpl/lexers/BodyLexer.java | 55 - .../com/diosay/otpl/lexers/BreakLexer.java | 51 - .../com/diosay/otpl/lexers/ContinueLexer.java | 49 - .../com/diosay/otpl/lexers/EachLexer.java | 155 --- .../com/diosay/otpl/lexers/ElifLexer.java | 49 - .../com/diosay/otpl/lexers/ElseLexer.java | 48 - .../java/com/diosay/otpl/lexers/ForLexer.java | 254 ---- .../java/com/diosay/otpl/lexers/IfLexer.java | 114 -- .../com/diosay/otpl/lexers/IncludeLexer.java | 55 - .../com/diosay/otpl/lexers/LayoutLexer.java | 58 - .../com/diosay/otpl/lexers/PlaceLexer.java | 90 -- .../com/diosay/otpl/lexers/PrintLexer.java | 71 - .../com/diosay/otpl/lexers/SectionLexer.java | 88 -- .../com/diosay/otpl/lexers/TextLexer.java | 47 - .../com/diosay/otpl/lexers/VariableLexer.java | 84 -- .../runtime/BuiltinFunctionInterface.java | 25 - .../com/diosay/otpl/runtime/CodeLoader.java | 374 ------ .../diosay/otpl/runtime/ExecutionContext.java | 141 -- .../java/com/diosay/otpl/runtime/Filter.java | 27 - .../com/diosay/otpl/runtime/Interpreter.java | 552 -------- .../java/com/diosay/otpl/runtime/OpCode.java | 169 --- .../com/diosay/otpl/runtime/OpcodeType.java | 209 --- .../java/com/diosay/otpl/runtime/Util.java | 33 - .../java/com/diosay/otpl/runtime/Writer.java | 43 - .../diosay/otpl/runtime/opcodes/Block.java | 82 -- .../com/diosay/otpl/runtime/opcodes/Body.java | 55 - .../diosay/otpl/runtime/opcodes/Break.java | 118 -- .../otpl/runtime/opcodes/BreakDescriptor.java | 50 - .../otpl/runtime/opcodes/BreakFalse.java | 58 - .../com/diosay/otpl/runtime/opcodes/Call.java | 98 -- .../otpl/runtime/opcodes/CallBlock.java | 73 - .../diosay/otpl/runtime/opcodes/Callvri.java | 74 -- .../otpl/runtime/opcodes/EndHeader.java | 43 - .../otpl/runtime/opcodes/EndOfFile.java | 43 - .../diosay/otpl/runtime/opcodes/Include.java | 62 - .../diosay/otpl/runtime/opcodes/Layout.java | 66 - .../otpl/runtime/opcodes/LoadConst.java | 61 - .../diosay/otpl/runtime/opcodes/LoadLong.java | 49 - .../otpl/runtime/opcodes/LoadMember.java | 125 -- .../diosay/otpl/runtime/opcodes/LoadNull.java | 42 - .../diosay/otpl/runtime/opcodes/LoadReal.java | 49 - .../otpl/runtime/opcodes/LoadString.java | 58 - .../diosay/otpl/runtime/opcodes/LoadTrue.java | 38 - .../otpl/runtime/opcodes/LoadVariable.java | 58 - .../com/diosay/otpl/runtime/opcodes/Nop.java | 57 - .../diosay/otpl/runtime/opcodes/Operator.java | 257 ---- .../com/diosay/otpl/runtime/opcodes/Peek.java | 41 - .../com/diosay/otpl/runtime/opcodes/Pop.java | 41 - .../diosay/otpl/runtime/opcodes/Print.java | 63 - .../otpl/runtime/opcodes/PrintString.java | 92 -- .../otpl/runtime/opcodes/SetVariable.java | 62 - .../runtime/opcodes/SourceLineNumber.java | 49 - .../java/com/diosay/otpl4j/SourceLine.java | 32 - .../src/main/java/mano/otpl/Block.java | 110 -- .../src/main/java/mano/otpl/Document.java | 76 -- .../open-tpl/src/main/java/mano/otpl/End.java | 22 - .../src/main/java/mano/otpl/Node.java | 125 -- .../main/java/mano/otpl/OtplViewEngine.java | 105 -- .../src/main/java/mano/otpl/Parser.java | 386 ------ .../src/main/java/mano/otpl/Span.java | 34 - .../main/java/mano/otpl/emit/EmitParser.java | 990 -------------- .../main/java/mano/otpl/emit/Interpreter.java | 667 ---------- .../src/main/java/mano/otpl/emit/OpCode.java | 127 -- .../src/main/java/mano/otpl/emit/OpCodes.java | 281 ---- .../src/main/java/mano/otpl/emit/Tuple.java | 140 -- del/mano-server-projects/pom.xml | 20 - .../mano-tplib/nb-configuration.xml | 18 - del/mano.project/mano-tplib/pom.xml | 27 - .../com/diosay/tplib/FastJsonConverter.java | 85 -- del/mano.project/pom.xml | 20 - del/maven-manoserver-plugin/nbactions.xml | 10 - del/maven-manoserver-plugin/pom.xml | 53 - .../maven/manoserver/plugin/DeployMojo.java | 151 --- .../manoserver/plugin/OtpCompileMojo.java | 104 -- .../maven/manoserver/plugin/RunMojo.java | 134 -- del/test-webapp-projects/pom.xml | 20 - .../test-webapp-dao/nbactions.xml | 10 - .../test-webapp-dao/pom.xml | 40 - .../diosay/test/webapp/dao/SessionHelper.java | 28 - .../test-webapp-model/nbactions.xml | 10 - .../test-webapp-model/pom.xml | 40 - .../diosay/test/webapp/model/Product.hbm.xml | 14 - .../com/diosay/test/webapp/model/Product.java | 30 - .../test-webapp/nb-configuration.xml | 18 - .../test-webapp/nbactions.xml | 17 - del/test-webapp-projects/test-webapp/pom.xml | 124 -- .../main/java/com/diosay/test/webapp/App.java | 33 - .../com/diosay/test/webapp/CheckLogin.java | 37 - .../diosay/test/webapp/controllers/Home.java | 72 - .../diosay/test/webapp/controllers/My.java | 20 - .../src/main/webapp/WEB-INF/hibernate.cfg.xml | 37 - .../src/main/webapp/WEB-INF/mano.web.xml | 30 - .../main/webapp/WEB-INF/manoserver.properties | 38 - .../test-webapp/src/main/webapp/index.html | 10 - .../src/main/webapp/views/home/dologin.html | 13 - .../src/main/webapp/views/home/index.html | 16 - .../src/main/webapp/views/home/login.html | 22 - .../src/main/webapp/views/my/index.html | 11 - 147 files changed, 16663 deletions(-) delete mode 100644 del/mano-server-projects/mano-server/hibernate.cfg.xml delete mode 100644 del/mano-server-projects/mano-server/nb-configuration.xml delete mode 100644 del/mano-server-projects/mano-server/nbactions.xml delete mode 100644 del/mano-server-projects/mano-server/pom.xml delete mode 100644 del/mano-server-projects/mano-server/src/main/java/com/diosay/mano/server/Bootstrap.java delete mode 100644 del/mano-server-projects/mano-server/src/main/java/mano/bootstrap/Bootstrap.java delete mode 100644 del/mano-server-projects/mano-server/src/main/java/mano/bootstrap/ConnectionManager.java delete mode 100644 del/mano-server-projects/mano-server/src/main/java/mano/bootstrap/DemoService.java delete mode 100644 del/mano-server-projects/mano-server/src/main/resources/conf.apps/app.ref.xml delete mode 100644 del/mano-server-projects/mano-server/src/main/resources/conf/app.def.xml delete mode 100644 del/mano-server-projects/mano-server/src/main/resources/conf/mano.web.xml delete mode 100644 del/mano-server-projects/mano-server/src/main/resources/conf/mano.xml delete mode 100644 del/mano-server-projects/mano-server/src/main/resources/conf/service/http.xml delete mode 100644 del/mano-server-projects/mano-server/src/resources/bin/run.bat delete mode 100644 del/mano-server-projects/mano-server/src/resources/conf/app.def.xml delete mode 100644 del/mano-server-projects/mano-server/src/resources/conf/server.xml delete mode 100644 del/mano-server-projects/mano-web/nb-configuration.xml delete mode 100644 del/mano-server-projects/mano-web/pom.xml delete mode 100644 del/mano-server-projects/mano-web/src/main/java/java/lang/MANO_WEB_MACRO.java delete mode 100644 del/mano-server-projects/mano-web/src/main/java/mano/web/HttpSessionService.java delete mode 100644 del/mano-server-projects/mano-web/src/main/java/mano/web/OtplViewEngine.java delete mode 100644 del/mano-server-projects/mano-web/src/main/java/mano/web/modules/StaticFileModule.java delete mode 100644 del/mano-server-projects/mano-web/src/main/java/mano/web/modules/UrlRoutingModule.java delete mode 100644 del/mano-server-projects/mano-web/src/main/java/mano/web/runtime/HttpChannel.java delete mode 100644 del/mano-server-projects/mano-web/src/main/java/mano/web/runtime/HttpListener.java delete mode 100644 del/mano-server-projects/mano-web/src/main/java/mano/web/runtime/HttpProtocol11.java delete mode 100644 del/mano-server-projects/mano-web/src/main/java/mano/web/runtime/HttpRequestImpl.java delete mode 100644 del/mano-server-projects/mano-web/src/main/java/mano/web/runtime/HttpResponseImpl.java delete mode 100644 del/mano-server-projects/mano-web/src/main/java/mano/web/runtime/HttpService.java delete mode 100644 del/mano-server-projects/open-tpl/demo/each.html delete mode 100644 del/mano-server-projects/open-tpl/demo/for.html delete mode 100644 del/mano-server-projects/open-tpl/demo/func.html delete mode 100644 del/mano-server-projects/open-tpl/demo/if.html delete mode 100644 del/mano-server-projects/open-tpl/demo/master.html delete mode 100644 del/mano-server-projects/open-tpl/demo/page.html delete mode 100644 del/mano-server-projects/open-tpl/nb-configuration.xml delete mode 100644 del/mano-server-projects/open-tpl/pom.xml delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/Block.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/CompileException.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/Compiler.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/Document.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/EndBlock.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/Lexer.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/Node.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/Parser.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/Span.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/StringUtil.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/Text.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/Token.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/BodyLexer.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/BreakLexer.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/ContinueLexer.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/EachLexer.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/ElifLexer.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/ElseLexer.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/ForLexer.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/IfLexer.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/IncludeLexer.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/LayoutLexer.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/PlaceLexer.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/PrintLexer.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/SectionLexer.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/TextLexer.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/VariableLexer.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/BuiltinFunctionInterface.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/CodeLoader.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/ExecutionContext.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/Filter.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/Interpreter.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/OpCode.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/OpcodeType.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/Util.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/Writer.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Block.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Body.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Break.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/BreakDescriptor.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/BreakFalse.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Call.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/CallBlock.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Callvri.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/EndHeader.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/EndOfFile.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Include.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Layout.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/LoadConst.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/LoadLong.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/LoadMember.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/LoadNull.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/LoadReal.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/LoadString.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/LoadTrue.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/LoadVariable.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Nop.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Operator.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Peek.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Pop.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Print.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/PrintString.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/SetVariable.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/SourceLineNumber.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl4j/SourceLine.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/mano/otpl/Block.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/mano/otpl/Document.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/mano/otpl/End.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/mano/otpl/Node.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/mano/otpl/OtplViewEngine.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/mano/otpl/Parser.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/mano/otpl/Span.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/mano/otpl/emit/EmitParser.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/mano/otpl/emit/Interpreter.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/mano/otpl/emit/OpCode.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/mano/otpl/emit/OpCodes.java delete mode 100644 del/mano-server-projects/open-tpl/src/main/java/mano/otpl/emit/Tuple.java delete mode 100644 del/mano-server-projects/pom.xml delete mode 100644 del/mano.project/mano-tplib/nb-configuration.xml delete mode 100644 del/mano.project/mano-tplib/pom.xml delete mode 100644 del/mano.project/mano-tplib/src/main/java/com/diosay/tplib/FastJsonConverter.java delete mode 100644 del/mano.project/pom.xml delete mode 100644 del/maven-manoserver-plugin/nbactions.xml delete mode 100644 del/maven-manoserver-plugin/pom.xml delete mode 100644 del/maven-manoserver-plugin/src/main/java/com/diosay/maven/manoserver/plugin/DeployMojo.java delete mode 100644 del/maven-manoserver-plugin/src/main/java/com/diosay/maven/manoserver/plugin/OtpCompileMojo.java delete mode 100644 del/maven-manoserver-plugin/src/main/java/com/diosay/maven/manoserver/plugin/RunMojo.java delete mode 100644 del/test-webapp-projects/pom.xml delete mode 100644 del/test-webapp-projects/test-webapp-dao/nbactions.xml delete mode 100644 del/test-webapp-projects/test-webapp-dao/pom.xml delete mode 100644 del/test-webapp-projects/test-webapp-dao/src/main/java/com/diosay/test/webapp/dao/SessionHelper.java delete mode 100644 del/test-webapp-projects/test-webapp-model/nbactions.xml delete mode 100644 del/test-webapp-projects/test-webapp-model/pom.xml delete mode 100644 del/test-webapp-projects/test-webapp-model/src/main/java/com/diosay/test/webapp/model/Product.hbm.xml delete mode 100644 del/test-webapp-projects/test-webapp-model/src/main/java/com/diosay/test/webapp/model/Product.java delete mode 100644 del/test-webapp-projects/test-webapp/nb-configuration.xml delete mode 100644 del/test-webapp-projects/test-webapp/nbactions.xml delete mode 100644 del/test-webapp-projects/test-webapp/pom.xml delete mode 100644 del/test-webapp-projects/test-webapp/src/main/java/com/diosay/test/webapp/App.java delete mode 100644 del/test-webapp-projects/test-webapp/src/main/java/com/diosay/test/webapp/CheckLogin.java delete mode 100644 del/test-webapp-projects/test-webapp/src/main/java/com/diosay/test/webapp/controllers/Home.java delete mode 100644 del/test-webapp-projects/test-webapp/src/main/java/com/diosay/test/webapp/controllers/My.java delete mode 100644 del/test-webapp-projects/test-webapp/src/main/webapp/WEB-INF/hibernate.cfg.xml delete mode 100644 del/test-webapp-projects/test-webapp/src/main/webapp/WEB-INF/mano.web.xml delete mode 100644 del/test-webapp-projects/test-webapp/src/main/webapp/WEB-INF/manoserver.properties delete mode 100644 del/test-webapp-projects/test-webapp/src/main/webapp/index.html delete mode 100644 del/test-webapp-projects/test-webapp/src/main/webapp/views/home/dologin.html delete mode 100644 del/test-webapp-projects/test-webapp/src/main/webapp/views/home/index.html delete mode 100644 del/test-webapp-projects/test-webapp/src/main/webapp/views/home/login.html delete mode 100644 del/test-webapp-projects/test-webapp/src/main/webapp/views/my/index.html diff --git a/del/mano-server-projects/mano-server/hibernate.cfg.xml b/del/mano-server-projects/mano-server/hibernate.cfg.xml deleted file mode 100644 index 9855ac9..0000000 --- a/del/mano-server-projects/mano-server/hibernate.cfg.xml +++ /dev/null @@ -1,70 +0,0 @@ - - - - - org.hibernate.dialect.MySQLDialect - com.mysql.jdbc.Driver - jdbc:mysql://112.124.109.67/ecp - root - sql@sa - true - thread - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/del/mano-server-projects/mano-server/nb-configuration.xml b/del/mano-server-projects/mano-server/nb-configuration.xml deleted file mode 100644 index 99bddf6..0000000 --- a/del/mano-server-projects/mano-server/nb-configuration.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - ManoLicense - - diff --git a/del/mano-server-projects/mano-server/nbactions.xml b/del/mano-server-projects/mano-server/nbactions.xml deleted file mode 100644 index e1f687c..0000000 --- a/del/mano-server-projects/mano-server/nbactions.xml +++ /dev/null @@ -1,46 +0,0 @@ - - - - run - - jar - - - process-classes - org.codehaus.mojo:exec-maven-plugin:1.2.1:exec - - - -ea -classpath %classpath mano.bootstrap.Bootstrap - java - - - - debug - - jar - - - process-classes - org.codehaus.mojo:exec-maven-plugin:1.2.1:exec - - - -Xdebug -Xrunjdwp:transport=dt_socket,server=n,address=${jpda.address} -ea -classpath %classpath ${packageClassName} - java - true - - - - profile - - jar - - - process-classes - org.codehaus.mojo:exec-maven-plugin:1.2.1:exec - - - -ea -classpath %classpath ${packageClassName} - java - - - diff --git a/del/mano-server-projects/mano-server/pom.xml b/del/mano-server-projects/mano-server/pom.xml deleted file mode 100644 index e35ab52..0000000 --- a/del/mano-server-projects/mano-server/pom.xml +++ /dev/null @@ -1,155 +0,0 @@ - - - 4.0.0 - com.diosay - mano-bootstrap - 1.4.0-BETA - jar - Mano :: Bootstrap - - - ${project.groupId} - mano - 1.4.0-BETA - - - ${project.groupId} - mano-service-http - ${project.version} - - - - UTF-8 - 1.8 - 1.8 - - - - - - - - org.apache.maven.plugins - maven-jar-plugin - 2.5 - - - - com.diosay.mano.server.Bootstrap - - - - ../lib/mano-1.0-SNAPSHOT.jar - - - - src/resources/*.* - - - - - - org.apache.maven.plugins - maven-dependency-plugin - - - - copy-dependencies - install - - copy-dependencies - - - ${basedir}/target/build/lib - true - true - true - - - - - - - maven-resources-plugin - 2.6 - - - - copy-resources-conf - validate - - copy-resources - - - ${basedir}/target/build/conf - - - src/resources/conf - - **/*.xml - **/*.xsd - - - - - - - - copy-resources script2bin - validate - - copy-resources - - - ${basedir}/target/build/bin - - - src/resources/bin - - **/*.bat - **/*.sh - - - - - - - - copy-resources-bootstrap2bin - install - - copy-resources - - - ${basedir}/target/build/bin - - - ${basedir}/target - - mano-*.jar - - - - - - - - - - \ No newline at end of file diff --git a/del/mano-server-projects/mano-server/src/main/java/com/diosay/mano/server/Bootstrap.java b/del/mano-server-projects/mano-server/src/main/java/com/diosay/mano/server/Bootstrap.java deleted file mode 100644 index c04080d..0000000 --- a/del/mano-server-projects/mano-server/src/main/java/com/diosay/mano/server/Bootstrap.java +++ /dev/null @@ -1,330 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Project. All rights reserved. - * - * See more http://mano.diosay.com/ - * - */ -package com.diosay.mano.server; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.NoSuchElementException; -import mano.ContextClassLoader; -import mano.Mano; -import mano.service.Intent; -import mano.service.IService; -import mano.service.ServiceManager; -import mano.service.ServiceProvider; -import mano.util.NameValueCollection; -import mano.util.ThreadPool; -import mano.util.Utility; -import mano.util.logging.LogService; -import mano.util.logging.Logger; -import mano.util.xml.XmlException; -import mano.util.xml.XmlHelper; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -/** - * 实现 Mano 服务容器的启动程序。 - * - * @author junhwong - */ -public class Bootstrap extends ServiceManager implements ServiceProvider { - - /** - * 临时 - */ - private NameValueCollection services; - - /** - * 使用指定加载器初始化。 - * @param loader - */ - public Bootstrap(ContextClassLoader loader) { - super(loader); - this.regisiter(new LogService()); - } - - /** - * 默认初始化。 - */ - public Bootstrap() { - this(null); - //this(new ContextClassLoader(null));//TODO: - } - - @Override - public T getService(Class serviceType) { - if (serviceType == null) { - return null; - } - if (Logger.class.getName().equals(serviceType.getName())) { - //return (T) getLogger(); - } else if (ContextClassLoader.class.getName().equals(serviceType.getName()) || ClassLoader.class.getName().equals(serviceType.getName())) { - return (T) getLoader(); - } - return null; - } - - /** - * 打印错误 - * - * @param message - * @param ex - */ - private void error(String message, Throwable ex) { - System.out.println(message); - if (ex != null) { - ex.printStackTrace(System.out); - } - } - - /** - * 载入配置文件 - * - * @throws XmlException - * @throws InstantiationException - * @throws ClassNotFoundException - */ - private void configure(String configPath, String serverDir) throws Exception { - - Mano.setProperty("user.dir", System.getProperty("user.dir")); - - File cfile; - if (configPath == null) { - cfile = Utility.toPath(Utility.toPath(Mano.getProperty("user.dir")).getParent().toString(), "conf/server.xml").toFile(); - } else { - cfile = new File(configPath); - } - - if (!cfile.exists() || !cfile.isFile()) { - throw new FileNotFoundException("配置文件未找到。"); - } - - XmlHelper helper = XmlHelper.load(cfile.toString()); - - NamedNodeMap attrs; - NodeList nodes; - Node node, root; - String s; - NameValueCollection params = new NameValueCollection<>(); - root = helper.selectNode("/configuration/server"); - if (root == null) { - throw new NoSuchElementException("丢失 [server] 节点"); - } - Mano.getProperties().setProperty("server.config", cfile.toString()); - - //加载属性 - nodes = helper.selectNodes(root, "settings/property"); - if (nodes != null) { - for (int i = 0; i < nodes.getLength(); i++) { - attrs = nodes.item(i).getAttributes(); - Mano.getProperties().setProperty(attrs.getNamedItem("name").getNodeValue(), nodes.item(i).getTextContent()); - } - } - - //预处理配置值。 - if (serverDir != null) { - Mano.setProperty("server.dir", serverDir); - } else { - if (Mano.getProperties().containsKey("server.dir")) { - Mano.setProperty("server.dir", Utility.getAndReplaceMarkup("server.dir", Mano.getProperties(), System.getProperties())); - } else { - Mano.setProperty("server.dir", Utility.toPath(Mano.getProperty("user.dir")).getParent().toString()); - } - } - - //加载依赖 - getLoader().register(Utility.toPath(Mano.getProperty("server.dir"), "lib").toString()); - - nodes = helper.selectNodes(root, "dependency/path"); - String[] arr; - if (nodes != null) { - for (int i = 0; i < nodes.getLength(); i++) { - attrs = nodes.item(i).getAttributes(); - try { - s = attrs.getNamedItem("value").getNodeValue().trim(); - if (s.startsWith("~/") || s.startsWith("~\\")) { - s = Utility.toPath(Mano.getProperty("server.dir"), s.substring(2)).toString(); - } else if (s.startsWith("/") || s.startsWith("\\")) { - s = Utility.toPath(Mano.getProperty("server.dir"), s.substring(1)).toString(); - } - getLoader().register(s); - } catch (Throwable ex) { - error(null, ex); - } - } - } - - //导出依赖 - nodes = helper.selectNodes(root, "dependency/export"); - if (nodes != null) { - for (int i = 0; i < nodes.getLength(); i++) { - attrs = nodes.item(i).getAttributes(); - try { - getLoader().registerExport(attrs.getNamedItem("name").getNodeValue().trim(), attrs.getNamedItem("class").getNodeValue().trim()); - } catch (Throwable ex) { - error(null, ex); - } - } - } - - //重置日志记录器 - node = helper.selectNode(root, "logger"); - if (node != null) { - - attrs = node.getAttributes(); - try { - s = attrs.getNamedItem("name").getNodeValue().trim(); - if (s == null || "".equals(s.trim())) { - throw new NoSuchElementException("丢失 Logger [name] 属性."); - } else { - //getLoader().setLogger(Logger.getLog()); - } - - nodes = helper.selectNodes(node, "handler"); - if (nodes != null) { - for (int i = 0; i < nodes.getLength(); i++) { - try { - s = nodes.item(i).getAttributes().getNamedItem("class").getNodeValue(); - Intent bag = Intent.create("mano.service.logging", "addhandler"); - bag.set("handler", getLoader().newInstance(s)); - bag.submit(); - } catch (Throwable ex) { - this.error(null, ex); - } - } - } - - } catch (Exception ignored) { - } - } - - //加载服务 - services = new NameValueCollection<>(); - NodeList nodes2; - nodes = helper.selectNodes(root, "services/service"); - if (nodes != null) { - for (int i = 0; i < nodes.getLength(); i++) { - attrs = nodes.item(i).getAttributes(); - - String name = attrs.getNamedItem("name").getNodeValue(); - String type = attrs.getNamedItem("class").getNodeValue(); - try { - IService service = (IService) getLoader().newInstance(type); - service.getProperties().setProperty("service_name", name); - nodes2 = helper.selectNodes(nodes.item(i), "property"); - if (nodes2 != null) { - for (int j = 0; j < nodes2.getLength(); j++) { - attrs = nodes2.item(j).getAttributes(); - try { - service.getProperties().setProperty(attrs.getNamedItem("name").getNodeValue().trim(), nodes2.item(j).getTextContent().trim()); - } catch (Exception ignored) { - this.error(null, ignored); - } - } - } - services.put(name, service); - } catch (Exception ignored) { - this.error(null,ignored); - } - } - } - } - - private void loop() { - while (true) { - try { - Thread.sleep(1000 * 1000); - } catch (InterruptedException e) { - this.error(null, e); - break; - } - } - } - - public void start(String configFile, String serverDir) { - - //getLogger().info("服务器启动中..."); - try { - - configure(configFile, serverDir); - - if (services.isEmpty()) { - //getLogger().fatal("服务列表为空,没有启动任何服务。"); - System.exit(0); - } else { - services.values().stream().forEach((service) -> { - try { - service.init(); - ThreadPool.execute((Runnable)service); - } catch (Exception ex) { - //getLogger().error(ex); - } - }); - //getLogger().info("服务器已经启动成功。"); - - } - - } catch (Exception ex) { - //getLogger().fatal(ex); - try { - Thread.sleep(1000); - } catch (InterruptedException ex1) { - } - System.exit(0); - } - } - - private static void debugStart(String configFile, String serverDir, ContextClassLoader loader) { - Bootstrap server = new Bootstrap(loader); - server.start(configFile, serverDir); - server.loop(); - } - - public void stop() { - //getLogger().info("服务器已经成功停止。"); - try { - Thread.sleep(1000); - } catch (InterruptedException ex1) { - } - System.exit(0); - } - - static void sss() throws FileNotFoundException, IOException{ - FileOutputStream out=new FileOutputStream("C:\\Users\\jun\\Desktop\\myos.img"); - byte[] b=new byte[1024]; - for(int i=0;i<1440;i++) - out.write(b); - out.close(); - } - - - public static void mainxxx(String[] args) { - -// try { -// sss(); -// } catch (IOException ex) { -// ex.printStackTrace(); -// } - - - Bootstrap server = new Bootstrap(); - // - String lib_path = "E:\\repositories\\java\\ifcc\\ecp-foreend\\ecp_webapp\\target\\build\\lib"; - String web_path = "E:\\repositories\\java\\ifcc\\ecp-foreend\\ecp_webapp\\src\\main\\webapp"; - - //lib_path="E:\\repositories\\java\\mano\\test-webapp-projects\\test-webapp\\target\\build\\lib"; - //web_path="E:\\repositories\\java\\mano\\test-webapp-projects\\test-webapp\\src\\main\\webapp"; - Mano.setProperty("manoserver.testing.test_webapp.config_file", web_path); - Mano.setProperty("manoserver.testing.test_webapp.ext_dependency", lib_path); - server.start("E:\\repositories\\java\\mano\\mano-server-projects\\mano-server\\src\\resources\\conf\\server.xml", "E:\\repositories\\java\\mano\\mano-server-projects\\mano-server\\target\\build"); - //server.start(null, null); - server.loop(); - } - -} diff --git a/del/mano-server-projects/mano-server/src/main/java/mano/bootstrap/Bootstrap.java b/del/mano-server-projects/mano-server/src/main/java/mano/bootstrap/Bootstrap.java deleted file mode 100644 index 2c08484..0000000 --- a/del/mano-server-projects/mano-server/src/main/java/mano/bootstrap/Bootstrap.java +++ /dev/null @@ -1,374 +0,0 @@ -/* - * Copyright (C) 2015 The MANO Project. All rights reserved. - * - * See more http://mano.diosay.com/ - * - */ -package mano.bootstrap; - -import java.io.File; -import java.util.Iterator; -import java.util.NoSuchElementException; -import mano.ContextClassLoader; -import mano.DateTime; -import mano.service.Service; -import mano.service.ServiceContainer; -import mano.util.Utility; -import mano.util.logging.ILogger; -import mano.util.logging.Log; -import mano.util.xml.XmlException; -import mano.util.xml.XmlHelper; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -/** - * - * @author johnwhang - */ -public final class Bootstrap { - - class ServiceContainerImpl implements ServiceContainer { - - java.util.LinkedList services = new java.util.LinkedList<>(); - - @Override - public void add(Service service) { - if (service == null) { - throw new NullPointerException("service"); - } - if (services.contains(service)) { - throw new IllegalStateException("The same service already exists in the container." + service); - } - services.add(service); - } - - @Override - public void remove(Service service) { - if (service == null) { - throw new NullPointerException("service"); - } - services.remove(service); - } - - @Override - public ServiceContainer run() { - throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. - } - - void runService(Service service) { - mano.util.ThreadPool.execute(service); - } - - void stop(Service service) { - service.stop(); - } - - @Override - public void await() { - Service service; - while (true) { - if (services.isEmpty()) { - break; - } - //启动未运行的服务 - Iterator iter = services.iterator(); - while (iter.hasNext()) { - service = iter.next(); - if (!service.isRunning()) { - runService(service); - } - //iter.remove(); - } - try { - Thread.sleep(100); - } catch (InterruptedException ex) { - ex.printStackTrace(); - break; - } - } - //结束所有服务 - Iterator iter = services.iterator(); - while (iter.hasNext()) { - stop(iter.next()); - iter.remove(); - } - } - - } - - static class TempLogger implements ILogger { - - @Override - public boolean isDebugEnabled() { - return true; - } - - @Override - public boolean isInfoEnabled() { - return true; - } - - @Override - public boolean isWarnEnabled() { - return true; - } - - @Override - public boolean isErrorEnabled() { - return true; - } - - @Override - public boolean isFatalEnabled() { - return true; - } - - @Override - public boolean isTraceEnabled() { - return true; - } - - @Override - public void debug(CharSequence message, Throwable... thrown) { - log(message, thrown); - } - - @Override - public void debug(Throwable thrown) { - throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. - } - - @Override - public void info(CharSequence message, Throwable... thrown) { - log(message, thrown); - } - - @Override - public void info(Throwable thrown) { - log("", thrown); - } - - @Override - public void warn(CharSequence message, Throwable... thrown) { - log(message, thrown); - } - - @Override - public void warn(Throwable thrown) { - log("", thrown); - } - - @Override - public void error(CharSequence message, Throwable... thrown) { - log(message, thrown); - } - - @Override - public void error(Throwable thrown) { - log("", thrown); - } - - @Override - public void fatal(CharSequence message, Throwable... thrown) { - log(message, thrown); - } - - @Override - public void fatal(Throwable thrown) { - log("", thrown); - } - - @Override - public void trace(CharSequence message, Throwable... causes) { - log(message, causes); - } - - @Override - public void trace(Throwable cause) { - log("", cause); - } - } - - - ContextClassLoader baseLoader; - ServiceContainer container = new ServiceContainerImpl(); - - /** - * 启动项配置 - * @param path - * @throws XmlException - */ - void configure(String path,String serviceConfigDir) throws XmlException { - baseLoader = new ContextClassLoader(new TempLogger()); - baseLoader.setProperties(System.getProperties()); - Node node, root, tmp; - NamedNodeMap attrs; - NodeList nodes; - String key, value; - StringBuilder sb; - XmlHelper helper = XmlHelper.load(path); - root = helper.selectNode("/configuration"); - if (root == null) { - throw new NoSuchElementException("Not define [configuration] root node."); - } - nodes = helper.selectNodes(root, "settings/property"); - if (nodes != null) { - for (int i = 0; i < nodes.getLength(); i++) { - node = nodes.item(i); - tmp = node.getAttributes().getNamedItem("name"); - if (tmp == null) { - throw new NoSuchElementException("Found property node,But not define [name] attribute."); - } - key = tmp.getNodeValue(); - if (key == null || "".equals(key)) { - throw new NoSuchElementException("Property name cannot be empty"); - } - value = node.getNodeValue(); - if (value == null) { - value = node.getTextContent(); - } - if (value == null || "".equals(value)) { - throw new NoSuchElementException("Property value cannot be empty"); - } - baseLoader.setProperty(key, Utility.replaceMarkup(new StringBuilder(value), key, baseLoader).toString()); - } - } - - nodes = helper.selectNodes(root, "dependency/path"); - if (nodes != null) { - //List list=new ArrayList<>(); - for (int i = 0; i < nodes.getLength(); i++) { - node = nodes.item(i); - tmp = node.getAttributes().getNamedItem("value"); - if (tmp == null) { - throw new NoSuchElementException("dependency/path not define [value] attribute."); - } - value = tmp.getNodeValue(); - if (value == null || "".equals(value)) { - throw new NoSuchElementException("Path value cannot be empty"); - } - - baseLoader.register(Utility.replaceMarkup(new StringBuilder(value), null, baseLoader).toString()); - } - } - baseLoader.setLogger(Log.get("root")); - - File serviceDir = new File(serviceConfigDir); - if (serviceDir.exists() && serviceDir.isDirectory()) { - for (File file : serviceDir.listFiles((f, n) -> { - System.out.println("" + n); - return n.toLowerCase().endsWith(".xml"); - })) { - try { - configureService(file); - } catch (Exception ex) { - if (baseLoader.getLogger().isErrorEnabled()) { - baseLoader.getLogger().error("Configuration XML file:" + file, ex); - } - } - } - } - - } - - /** - * 读取配置实例化服务 - */ - void configureService(File file) throws Exception { - XmlHelper helper = XmlHelper.load(file); - Node node, root, tmp; - NamedNodeMap attrs; - NodeList nodes; - String key, value; - StringBuilder sb; - - ContextClassLoader loader = new ContextClassLoader(baseLoader); - root = helper.selectNode("/service"); - if (root == null) { - throw new NoSuchElementException("Not define [service] root node."); - } - nodes = helper.selectNodes(root, "settings/property"); - if (nodes != null) { - for (int i = 0; i < nodes.getLength(); i++) { - node = nodes.item(i); - tmp = node.getAttributes().getNamedItem("name"); - if (tmp == null) { - throw new NoSuchElementException("Found property node,But not define [name] attribute."); - } - key = tmp.getNodeValue(); - if (key == null || "".equals(key)) { - throw new NoSuchElementException("Property name cannot be empty"); - } - value = node.getNodeValue(); - if (value == null) { - value = node.getTextContent(); - } - if (value == null || "".equals(value)) { - throw new NoSuchElementException("Property value cannot be empty"); - } - - loader.setProperty(key, Utility.replaceMarkup(new StringBuilder(value), key, loader).toString()); - } - } - - nodes = helper.selectNodes(root, "dependency/path"); - if (nodes != null) { - for (int i = 0; i < nodes.getLength(); i++) { - node = nodes.item(i); - tmp = node.getAttributes().getNamedItem("value"); - if (tmp == null) { - throw new NoSuchElementException("dependency/path not define [value] attribute."); - } - value = tmp.getNodeValue(); - if (value == null || "".equals(value)) { - throw new NoSuchElementException("Path value cannot be empty"); - } - - loader.register(Utility.replaceMarkup(new StringBuilder(value), null, loader).toString()); - } - } - loader.setProperty(Service.SERVICE_CONFIG_KEY, file.getCanonicalPath()); - Class clazz = loader.loadClass(loader.getProperty("service.class")); - if (Service.class.isAssignableFrom(clazz)) { - Service s = Service.class.cast(loader.newInstance(clazz)); - assert s != null; - s.init(loader, container); - } else { - throw new ClassCastException("Configuration service.class must be a subclass of Service." + loader.getProperty("service.class")); - } - } - - - - private static void log(CharSequence s, Throwable... err) { - System.out.println(DateTime.now() + " " + s); - if (err != null && err.length > 0) { - for (Throwable e : err) { - e.printStackTrace(System.out); - } - } - } - - public static void main(String[] args) { - //ByteBufferAllocator b=new ByteBufferAllocator(); - try { - if (args == null || args.length == 0) { - - Bootstrap boot = new Bootstrap(); - //TODO: - String manoConfig="E:\\repositories\\java\\mano\\mano-server-projects\\mano-server\\src\\main\\resources\\conf\\mano.xml"; - String serviceConfig="E:\\repositories\\java\\mano\\mano-server-projects\\mano-server\\src\\main\\resources\\conf\\service"; - //mano.util.Utility.toPath(System.getProperty("mano.dir"), "/conf/service").toFile(); - boot.configure(manoConfig,serviceConfig); - boot.container.await(); - System.out.println("done"); - System.exit(0); - } else { - - } - } catch (XmlException ex) { - log("configure error", ex); - } - } -} diff --git a/del/mano-server-projects/mano-server/src/main/java/mano/bootstrap/ConnectionManager.java b/del/mano-server-projects/mano-server/src/main/java/mano/bootstrap/ConnectionManager.java deleted file mode 100644 index a91304b..0000000 --- a/del/mano-server-projects/mano-server/src/main/java/mano/bootstrap/ConnectionManager.java +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright (C) 2014-2015 The MANO Project. All rights reserved. - * - * See more http://mano.diosay.com/ - * - */ - -package mano.bootstrap; - -/** - * - * @author johnwhang - */ -public class ConnectionManager { - -} diff --git a/del/mano-server-projects/mano-server/src/main/java/mano/bootstrap/DemoService.java b/del/mano-server-projects/mano-server/src/main/java/mano/bootstrap/DemoService.java deleted file mode 100644 index e7da133..0000000 --- a/del/mano-server-projects/mano-server/src/main/java/mano/bootstrap/DemoService.java +++ /dev/null @@ -1,258 +0,0 @@ -/* - * Copyright (C) 2014-2015 The MANO Project. All rights reserved. - * - * See more http://mano.diosay.com/ - * - */ -package mano.bootstrap; - -import java.nio.ByteBuffer; -import mano.DateTime; -import mano.io.ByteBufferPool; -import mano.io.ChannelContext; -import mano.io.ChannelException; -import mano.io.ChannelHandler; -import mano.io.ChannelHandlerChain; -import mano.io.ChannelListener; -import mano.io.ChannelListenerContext; -import mano.net.AIOSocketChannelListener; -import mano.net.SSLHandler; -import mano.service.Service; -import mano.util.CachedObjectRecyler; -import mano.util.Pool; -import mano.util.ThreadPool; - -/** - * - * @author johnwhang - */ -public class DemoService extends Service { - - private String serviceName; - - @Override - public String getServiceName() { - return serviceName; - } - - @Override - protected void onInit() throws Exception { - serviceName = this.getContext().getProperty("service.name"); - } - -// class HttpHandler implements ChannelHandler { -// -// ExecutorService executor; -// java.nio.charset.CharsetEncoder encoder = java.nio.charset.Charset.forName("utf-8").newEncoder(); -// -// @Override -// public void handleConnected(Channel channel) { -// try { -// Request req=new Request(); -// req.channel=channel; -// requests.put(channel, req); -// channel.read(); -// //channel.read(); -// } catch (ChannelException ex) { -// channel.close(); -// } -// } -// -// @Override -// public void handleDisconnected(Channel channel) { -// System.out.println("channel closed"); -// } -// -// @Override -// public ExecutorService getEexecutor() { -// return executor; -// } -// -// @Override -// public BufferAllocator getAllocator() { -// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. -// } -// -// class Request{ -// Channel channel; -// ByteBuffer buffer; -// java.util.LinkedList headers=new java.util.LinkedList<>(); -// boolean done; -// } -// java.util.HashMap requests=new java.util.HashMap<>(); -// -// int i=0; -// @Override -// public void handleReceived(Channel channel, ByteBuffer buffer) { -// -// Request req=requests.get(channel); -// if(!req.done){ -// -// if(req.buffer!=null){ -// -// if(req.buffer.remaining()>=buffer.remaining()){ -// req.buffer.put(buffer); -// req.buffer.flip(); -// }else{ -// while(req.buffer.hasRemaining()&&buffer.hasRemaining()){ -// req.buffer.put(buffer.get()); -// } -// req.buffer.flip(); -// -// } -// -// } -// -// -// -// } -// -// -// -// System.out.println("RECV:" + new String(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining())); -// -// byte[] hello = ("hello,world 你好世界 " + DateTime.now()).getBytes(); -// StringBuilder sb = new StringBuilder(); -// sb.append("HTTP/1.1 200 OK").append("\r\n"); -// sb.append("Date:").append(DateTime.now().toGMTString()).append("\r\n"); -// sb.append("Connection:").append("close").append("\r\n"); -// sb.append("Content-length:").append(hello.length).append("\r\n"); -// sb.append("\r\n"); -// -// try { -// channel.write(sb, encoder); -// -// channel.write(hello, 0, hello.length); -// -// channel.submit((ChanneFilterChainFactory factory, Channel channel1) -> { -// channel1.close(false); -// System.out.println("closing here"); -// }); -// } catch (ChannelException ex) { -// channel.close(); -// } -// -// } -// -// @Override -// public void handleError(Channel channel, Throwable cause) { -// cause.printStackTrace(); -// channel.close(); -// } -// } -// -// - class HttpHandler implements ChannelHandler { - - java.nio.charset.CharsetEncoder encoder = java.nio.charset.Charset.forName("utf-8").newEncoder(); - - @Override - public void handleConnected(ChannelContext context, ChannelHandlerChain chain) { - System.out.println("conn..."); - try { - context.channel().read(); - } catch (ChannelException ex) { - ex.printStackTrace(); - } - } - - @Override - public void handleDisconnected(ChannelContext context, ChannelHandlerChain chain) { - System.out.println("channel closed"); - } - - @Override - public void handleInbound(ChannelContext context, ChannelHandlerChain chain, ByteBuffer buffer) { - - System.out.println("RECV:" + new String(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining())); - - context.free(buffer); - - byte[] hello = ("hello,world 你好世界 " + DateTime.now()).getBytes(); - StringBuilder sb = new StringBuilder(); - sb.append("HTTP/1.1 200 OK").append("\r\n"); - sb.append("Date:").append(DateTime.now().toGMTString()).append("\r\n"); - sb.append("Connection:").append("close").append("\r\n"); - sb.append("Content-length:").append(hello.length).append("\r\n"); - sb.append("\r\n"); - - try { - context.channel().write(sb, encoder); - - context.channel().write(hello, 0, hello.length); - - context.channel().submit((ChannelContext channel1) -> { - System.out.println("response done.closing..."); - channel1.channel().close(false); - }); - } catch (ChannelException ex) { - context.channel().close(); - } - } - - @Override - public void handleOutbound(ChannelContext context, ChannelHandlerChain chain, ByteBuffer buffer) { - if (buffer.hasRemaining()) { - context.putOutbound(buffer); - } else { - context.free(buffer); - } - } - - @Override - public void handleError(ChannelContext context, ChannelHandlerChain chain, Throwable cause) { - System.out.println("ERR HANDING:"); - cause.printStackTrace(); - } - - @Override - public void setProperty(String property, Object value) { - throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. - } - - @Override - public void init() { - throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. - } - - @Override - public void destroy() { - throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. - } - - } - - Pool sslBufferPool = new CachedObjectRecyler() { - - @Override - protected ByteBuffer createNew() { - return ByteBuffer.allocate(1024 * 17);//SSLFilter.DEFAULT_BUFFER_SIZE - } - }; - - @Override - protected void onStart() throws Exception { - - //handler.executor = Executors.newFixedThreadPool(4);// Executors.newCachedThreadPool();//Executors.newFixedThreadPool(4); - System.out.println("CPUs:" + Runtime.getRuntime().availableProcessors()); - - ChannelListenerContext context = new ChannelListenerContext(ThreadPool.getService()); - - ChannelListener listener = new AIOSocketChannelListener(); - listener.addHandler(new SSLHandler()); - listener.addHandler(new HttpHandler()); - - listener.closedEvent().add((sender, e) -> { - - }); - listener.bind("localhost:443", 0); - listener.setContext(context); - listener.run(); - } - - @Override - protected void onStop() throws Exception { - - } - -} diff --git a/del/mano-server-projects/mano-server/src/main/resources/conf.apps/app.ref.xml b/del/mano-server-projects/mano-server/src/main/resources/conf.apps/app.ref.xml deleted file mode 100644 index 789f0a8..0000000 --- a/del/mano-server-projects/mano-server/src/main/resources/conf.apps/app.ref.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - diff --git a/del/mano-server-projects/mano-server/src/main/resources/conf/app.def.xml b/del/mano-server-projects/mano-server/src/main/resources/conf/app.def.xml deleted file mode 100644 index 398d0df..0000000 --- a/del/mano-server-projects/mano-server/src/main/resources/conf/app.def.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - diff --git a/del/mano-server-projects/mano-server/src/main/resources/conf/mano.web.xml b/del/mano-server-projects/mano-server/src/main/resources/conf/mano.web.xml deleted file mode 100644 index 2930796..0000000 --- a/del/mano-server-projects/mano-server/src/main/resources/conf/mano.web.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - default application - * - / - mano.web.WebAppcation - {application.name} - - - - get,post - - - - - - - - - - - - - - diff --git a/del/mano-server-projects/mano-server/src/main/resources/conf/mano.xml b/del/mano-server-projects/mano-server/src/main/resources/conf/mano.xml deleted file mode 100644 index 45c3535..0000000 --- a/del/mano-server-projects/mano-server/src/main/resources/conf/mano.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - {user.dir}/.. - mano.​supports.FastJsonConverter - true - true - true - true - true - true - - - - - - true - root - mano.util.logging.ConsoleHandler - mano.util.logging.SimpleFormatter - true - true - true - true - true - - \ No newline at end of file diff --git a/del/mano-server-projects/mano-server/src/main/resources/conf/service/http.xml b/del/mano-server-projects/mano-server/src/main/resources/conf/service/http.xml deleted file mode 100644 index 48304ef..0000000 --- a/del/mano-server-projects/mano-server/src/main/resources/conf/service/http.xml +++ /dev/null @@ -1,115 +0,0 @@ - - - - MANO HTTP Service - mano.service.http.HttpService - false - {mano.dir}/conf/webapp - 8k - 1024 - - - - - - - - - - - - - - / - - home - index - - - - - - - - - - text/html - text/html - text/plain - text/css - application/x-javascript - image/jpeg - image/jpeg - image/png - image/gif - image/bmp - image/x-icon - image/vnd.microsoft.icon - image/svg+xml - video/mp4 - video/x-m4v - audio/mpeg - flv-application/octet-stream - video/x-msvideo - video/quicktime - video/quicktime - application/x-font-woff - application/x-shockwave-flash - - application/msword - appication/powerpoint - application/vnd.ms-excel - application/msword - appication/powerpoint - application/vnd.ms-excel - - application/pdf - application/vnd.oasis.opendocument.spreadsheet - application/vnd.oasis.opendocument.graphics - application/vnd.oasis.opendocument.database - application/vnd.oasis.opendocument.text - - application/octet-stream - application/octet-stream - - - - text/html - utf-8 - {app.dir}/WEB-INF - {inf.dir}/tmp - {app.dir}/views - mano.web.OtplViewEngine - - - - - - - - d:\ssl\diosay.keystore - 123456 - SSLV2 - false - - - - - - - - - - - - - - - - - - ~/app/demo - - \ No newline at end of file diff --git a/del/mano-server-projects/mano-server/src/resources/bin/run.bat b/del/mano-server-projects/mano-server/src/resources/bin/run.bat deleted file mode 100644 index 4b02c00..0000000 --- a/del/mano-server-projects/mano-server/src/resources/bin/run.bat +++ /dev/null @@ -1,17 +0,0 @@ -@echo off -rem Copyright (C) 2014 The MANO Authors. -rem All rights reserved. Use is subject to license terms. -rem -rem http://mano.diosay.com/ -rem - -echo DIOSAY MANO Server (Version 1.1) -echo (C) 2014 The MANO Authors. All rights reserved. - - -setlocal -set "CURRENT_DIR=%~dp0" -set "DRIVER=%~d0" -cd "%CURRENT_DIR%" -%DRIVER% -java -jar mano-server-1.0-SNAPSHOT.jar -encoding utf-8 \ No newline at end of file diff --git a/del/mano-server-projects/mano-server/src/resources/conf/app.def.xml b/del/mano-server-projects/mano-server/src/resources/conf/app.def.xml deleted file mode 100644 index 398d0df..0000000 --- a/del/mano-server-projects/mano-server/src/resources/conf/app.def.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - diff --git a/del/mano-server-projects/mano-server/src/resources/conf/server.xml b/del/mano-server-projects/mano-server/src/resources/conf/server.xml deleted file mode 100644 index 7fc0cbb..0000000 --- a/del/mano-server-projects/mano-server/src/resources/conf/server.xml +++ /dev/null @@ -1,98 +0,0 @@ - - - - - {user.dir}/.. - {server.dir}/logs - com.diosay.tplib.FastJsonConverter - - - - - - - - - {server.dir}/conf/server.xml - 8k - 1024 - {server.dir}/conf/apps - httpsession.service - 0.0.0.0:9999 - false - - - - - - - - - - - - - - - - - - - - - text/html - text/html - text/plain - text/css - application/x-javascript - image/jpeg - image/jpeg - image/png - image/gif - image/bmp - image/x-icon - image/vnd.microsoft.icon - image/svg+xml - video/mp4 - video/x-m4v - audio/mpeg - flv-application/octet-stream - video/x-msvideo - video/quicktime - video/quicktime - application/x-font-woff - application/x-shockwave-flash - - application/msword - appication/powerpoint - application/vnd.ms-excel - application/msword - appication/powerpoint - application/vnd.ms-excel - - application/pdf - application/vnd.oasis.opendocument.spreadsheet - application/vnd.oasis.opendocument.graphics - application/vnd.oasis.opendocument.database - application/vnd.oasis.opendocument.text - - application/octet-stream - application/octet-stream - - - - text/html - utf-8 - {app.dir}/WEB-INF - {inf.dir}/tmp - {app.dir}/views - mano.web.OtplViewEngine - - - - - - - \ No newline at end of file diff --git a/del/mano-server-projects/mano-web/nb-configuration.xml b/del/mano-server-projects/mano-web/nb-configuration.xml deleted file mode 100644 index 99bddf6..0000000 --- a/del/mano-server-projects/mano-web/nb-configuration.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - ManoLicense - - diff --git a/del/mano-server-projects/mano-web/pom.xml b/del/mano-server-projects/mano-web/pom.xml deleted file mode 100644 index d03b343..0000000 --- a/del/mano-server-projects/mano-web/pom.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - 4.0.0 - com.diosay - mano-web - 1.0-SNAPSHOT - jar - - - - ${project.groupId} - mano - ${project.version} - - - ${project.groupId} - open-tpl - ${project.version} - - - - - UTF-8 - 1.8 - 1.8 - - \ No newline at end of file diff --git a/del/mano-server-projects/mano-web/src/main/java/java/lang/MANO_WEB_MACRO.java b/del/mano-server-projects/mano-web/src/main/java/java/lang/MANO_WEB_MACRO.java deleted file mode 100644 index 28f6e17..0000000 --- a/del/mano-server-projects/mano-web/src/main/java/java/lang/MANO_WEB_MACRO.java +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Project. All rights reserved. - * - * See more http://mano.diosay.com/ - * - */ -package java.lang; - -/** - * 项目宏 - * @author jun - */ -public class MANO_WEB_MACRO { - /** - * 是否开启 DEBUG 。 - */ - public static final boolean DEBUG = true; -} diff --git a/del/mano-server-projects/mano-web/src/main/java/mano/web/HttpSessionService.java b/del/mano-server-projects/mano-web/src/main/java/mano/web/HttpSessionService.java deleted file mode 100644 index 873de86..0000000 --- a/del/mano-server-projects/mano-web/src/main/java/mano/web/HttpSessionService.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Project. All rights reserved. - * - * See more http://mano.diosay.com/ - * - */ -package mano.web; - -import java.util.Map; -import mano.caching.CacheProvider; -import mano.caching.HashCacheProvider; -import mano.service.AbstractService; -import mano.service.ServiceContainer; -import mano.service.ServiceProvider; - -/** - * - * @author jun - */ -public class HttpSessionService extends AbstractService implements ServiceProvider { - - HashCacheProvider provider; - - @Override - public String getServiceName() { - return "cache.service"; - } - - @Override - public void run() { - provider = new HashCacheProvider(); - this.onStart(); - } - - @Override - public T getService(Class serviceType) { - if (CacheProvider.class.getName().equals(serviceType.getName())) { - return (T) provider; - } - return null; - } - -} diff --git a/del/mano-server-projects/mano-web/src/main/java/mano/web/OtplViewEngine.java b/del/mano-server-projects/mano-web/src/main/java/mano/web/OtplViewEngine.java deleted file mode 100644 index 45a3899..0000000 --- a/del/mano-server-projects/mano-web/src/main/java/mano/web/OtplViewEngine.java +++ /dev/null @@ -1,392 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Project. All rights reserved. - * - * See more http://mano.diosay.com/ - * - */ -package mano.web; - -import com.diosay.otpl.runtime.BuiltinFunctionInterface; -import com.diosay.otpl.runtime.CodeLoader; -import com.diosay.otpl.runtime.ExecutionContext; -import com.diosay.otpl.runtime.Interpreter; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.PrintStream; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.lang.reflect.Array; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.nio.charset.Charset; -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Stack; -import mano.http.HttpContext; -import mano.util.Utility; - -/** - * Open-TPL 视图引擎。 - * - * @author jun - */ -public class OtplViewEngine extends ViewEngine { - - private Interpreter interpreter = new Interpreter(); - - class SimpleExecutionContext extends ViewContext implements ExecutionContext { - - //private HashMap items = new HashMap<>(); - private Stack stack = new Stack<>(); - private HashMap loaders = new HashMap<>(); - - public SimpleExecutionContext(HttpContext c) { - super(c); - } - - @Override - public String getBasedir() { - return getViewdir(); - //return "E:\\repositories\\java\\mano\\mano-server-projects\\otpl4j\\demo"; - } - - @Override - public String getTempdir() { - return OtplViewEngine.this.getTempdir(); - //return "C:\\Users\\jun\\Desktop\\demo"; - } - -// @Override -// public void set(String key, Object value) { -// items.put(key, value); -// } -// -// @Override -// public Object get(String key) { -// if (items.containsKey(key)) { -// return items.get(key); -// } -// return null;//TODO:报错? -// } - @Override - public void push(Object value) { - stack.push(value); - } - - @Override - public Object pop() { - if (stack.isEmpty()) { - return null; - } - return stack.pop(); - } - - @Override - public void reset() { - throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. - } - - @Override - public Charset outputEncoding() { - return this.getEncoding(); - } - - @Override - public void write(boolean filtrable, Object obj) { - if (obj == null) { - return; - } - String s = obj.toString(); - write(filtrable, s, 0, s.length()); - } - - @Override - public void write(boolean filtrable, CharSequence cs, int start, int end) { - byte[] array = cs.subSequence(start, end).toString().getBytes(this.outputEncoding()); - write(filtrable, array, 0, array.length); - } - - @Override - public void write(boolean filtrable, byte[] array, int index, int count) { - if (filtrable) { - //TODO: - } - this.getContext().getResponse().write(array, index, count); - //System.out.write(array, index, count); - } - - @Override - public Charset inputEncoding() { - return Charset.forName("utf-8"); - } - - @Override - public Interpreter newInterpreter() { - return new Interpreter(); - } - - @Override - public void freeInterpreter(Interpreter interpreter) { - - } - - @Override - public CodeLoader getLoader(File source, Interpreter interpreter) throws Exception { - - String id = Integer.toHexString(source.toString().hashCode()); - if (loaders.containsKey(id)) { - return loaders.get(id); - } - - if (interpreter == null) { - interpreter = newInterpreter(); - loaders.put(id, interpreter.load(this, source)); - freeInterpreter(interpreter); - } else { - loaders.put(id, interpreter.load(this, source)); - } - return loaders.get(id); - } - - @Override - public Object peek() { - return this.stack.peek(); - } - private int lineNumber; - private BuiltinFunctionInterface bfi; - - @Override - public void setCurrentSourceLine(int line) { - lineNumber = line; - } - - @Override - public int getCurrentSourceLine() { - return lineNumber; - } - - @Override - public BuiltinFunctionInterface calls() { - if (bfi == null) { - bfi = new BFI(); - } - return bfi; - } - - @Override - public Object call(String funcName, Object[] args) { - - if ("str".equals(funcName)) { - return calls().str(args); - } else if ("len".equals(funcName)) { - if (args == null || args.length == 0 || args[0] == null) { - return -1; - } else if (args[0] instanceof CharSequence) { - return ((CharSequence) args[0]).length(); - } else if (args[0].getClass().isArray()) { - return Array.getLength(args[0]); - } else if (args[0] instanceof Collection) { - return ((Collection) args[0]).size(); - } else if (args[0] instanceof Map) { - return ((Map) args[0]).size(); - } - return -1; - } else if ("iterator".equals(funcName)) { - return calls().iterator(args[0]); - } else if ("iterator$hasNext".equals(funcName)) { - Iterator itor = (Iterator) args[0]; - return itor.hasNext(); - } else if ("iterator$next".equals(funcName)) { - Iterator itor = (Iterator) args[0]; - return !itor.hasNext()?null:itor.next(); - } else if ("indexer".equals(funcName)) { - if (args.length < 2) { - throw new UnsupportedOperationException("参数不匹配:" + funcName); - } - Object[] nargs = new Object[args.length - 1]; - System.arraycopy(args, 0, nargs, 0, args.length - 1); - return calls().indexer(args[args.length - 1], nargs); - } else { - Object obj = get(funcName); - if (obj == null || !(obj instanceof Method)) { - throw new UnsupportedOperationException("函数未定义:" + funcName); - } - Method method = (Method) obj; - method.setAccessible(true); - try { - - Class[] types = method.getParameterTypes(); - if (args.length < types.length) { - throw new UnsupportedOperationException("参数不匹配:" + funcName); - } - Object[] nargs = new Object[types.length]; - for (int i = 0; i < types.length; i++) { - Class clazz = types[i]; - - nargs[i] = Utility.cast(clazz, args[i]); - } - - return method.invoke(null, nargs); - } catch (IllegalAccessException | IllegalArgumentException ex) { - throw new RuntimeException(ex); - } catch (InvocationTargetException ex) { - if (ex.getTargetException() != null) { - throw new RuntimeException(ex.getTargetException()); - } - throw new RuntimeException(ex); - } - - } - } - - Object invokeMethod(Method method, Object instance, Object[] args) { - if (method == null) { - return null; - } - - try { - method.setAccessible(true); - - Class[] types = method.getParameterTypes(); - if (args.length < types.length) { - throw new UnsupportedOperationException("参数不匹配:" + method.getName()); - } - Object[] nargs = new Object[types.length]; - for (int i = 0; i < types.length; i++) { - Class clazz = types[i]; - - nargs[i] = Utility.cast(clazz, args[i]); - } - - return method.invoke(instance, nargs); - } catch (IllegalAccessException | IllegalArgumentException ex) { - throw new RuntimeException(ex); - } catch (InvocationTargetException ex) { - if (ex.getTargetException() != null) { - throw new RuntimeException(ex.getTargetException()); - } - throw new RuntimeException(ex); - } - } - - class BFI implements BuiltinFunctionInterface { - - @Override - public String str(Object[] args) { - if (args == null) { - return null; - } - StringBuilder sb = new StringBuilder(); - for (Object obj : args) { - sb.append(obj); - } - return sb.toString(); - } - - public int len(Object value) { - if (value == null) { - return -1; - } - - return 0; - } - - @Override - public Object iterator(Object obj) { - if (obj == null) { - obj = new Object[0]; - } - - if (obj instanceof Iterable) { - return ((Iterable) obj).iterator(); - } else if (obj instanceof Map) { - return ((Iterable) ((Map) obj).entrySet()).iterator(); - } else if (obj.getClass().isArray()) { - final Object array = obj; - final int size = Array.getLength(obj); - return new Iterator() { - int current = 0; - - @Override - public boolean hasNext() { - return current < size; - } - - @Override - public Object next() { - return Array.get(array, current++); - } - - }; - } - throw new RuntimeException("give object is a non-iterable object." + obj.getClass()); - } - - @Override - public Object indexer(Object obj, Object[] args) { - - if (obj == null) { - return null; - } else if (obj.getClass().isArray()) { - return Array.get(obj, Integer.parseInt(args[0].toString())); - } else { - Method method = null; - for (Method m : obj.getClass().getMethods()) { - if (m.getName().equals("get") && m.getParameterCount() == args.length) { - method = m; - break; - } - } - if (method == null) { - throw new UnsupportedOperationException("函数未定义:" + "get"); - } - return invokeMethod(method, obj, args); - } - } - } - - } - - @Override - public ViewContext createContext(HttpContext context) { - return new SimpleExecutionContext(context); - } - private void printRoot(StringWriter sb, Throwable t) { - if (t == null) { - return; - } - sb.append("root

");
-        StringWriter sw = new StringWriter();
-        try (PrintWriter pw = new PrintWriter(sw)) {
-            pw.println();
-            t.printStackTrace(pw);
-        }
-        sb.append(sw.toString());
-        sb.append("

"); - printRoot(sb, t.getCause()); - } - @Override - public void render(ViewContext context) { - try { - String file = context.getPath(); - if (file.startsWith("~/") || file.startsWith("~\\")) { - file = Utility.toPath(this.getViewdir(), file.substring(1)).toString(); - } - interpreter.exec((ExecutionContext) context, new File(file)); - } catch (Exception ex) { - StringWriter sw = new StringWriter(); - sw.append("
");
-            try (PrintWriter pw = new PrintWriter(sw)) {
-                pw.println();
-                ex.printStackTrace(pw);
-            }
-            sw.append("
"); - printRoot(sw,ex.getCause()); - context.getContext().getResponse().write(sw.toString()); - } - } - -} diff --git a/del/mano-server-projects/mano-web/src/main/java/mano/web/modules/StaticFileModule.java b/del/mano-server-projects/mano-web/src/main/java/mano/web/modules/StaticFileModule.java deleted file mode 100644 index 17e98ee..0000000 --- a/del/mano-server-projects/mano-web/src/main/java/mano/web/modules/StaticFileModule.java +++ /dev/null @@ -1,225 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Project. All rights reserved. - * - * See more http://mano.diosay.com/ - * - */ -package mano.web.modules; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.nio.channels.FileChannel; -import java.util.Map.Entry; -import java.util.Properties; -import mano.DateTime; -import mano.InvalidOperationException; -import mano.http.HttpContext; -import mano.http.HttpHeaderCollection; -import mano.http.HttpModule; -import mano.http.HttpStatus; -import mano.util.NameValueCollection; -import mano.util.Utility; -import mano.web.WebApplication; - -/** - * - * @author jun - */ -public class StaticFileModule implements HttpModule { - - private NameValueCollection mappings; - - @Override - public void init(WebApplication app, Properties params) { - mappings = new NameValueCollection<>(); - for (Entry entry : params.entrySet()) { - String[] arr = entry.getKey().toString().toLowerCase().split(":"); - if (arr.length > 1) { - if ("ext".equals(arr[0])) { - mappings.put(arr[1], entry.getValue().toString()); - } - } - } - } - - private boolean process(HttpContext context, String path, String mime) { - - //context.getApplication().getLogger().debug("process static path:" + path); - - File file = new File(path); - if (!file.exists() || !file.isFile()) { - return false; - } - boolean range = false; - String etag = "\"" + Integer.toHexString((file.lastModified() + "" + file.length() + path).hashCode()) + ":df3\""; - HttpHeaderCollection headers = context.getRequest().headers(); - long since, start = 0, end = 0, len = -1; - try { - since = DateTime.parseTime(headers.get("If-Modified-Since").value(), DateTime.FORMAT_GMT); - } catch (Exception e) { - since = 0; - } - - //TODO: ETag 未生效 - //Expires、Cache-Control和Vary - //If-Modified-Since: Fri, 12 May 2006 18:53:33 GMT - //If-None-Match: W/"50b1c1d4f775c61:df3" - //http://www.cnblogs.com/tyb1222/archive/2011/12/24/2300246.html - boolean done = true; - try { - long size; - try (FileChannel chan = new FileInputStream(file).getChannel()) { - size = chan.size(); - } - context.getResponse().setContentType(mime); - - if (file.lastModified() == since - || (headers.containsKey("If-None-Match") - && etag.equalsIgnoreCase(headers.get("If-None-Match").value()))) { - - context.getResponse().status(HttpStatus.NotModified.getStatus()); - - } else if (headers.containsKey("Range")) { - if (headers.containsKey("If-Range") && !etag.equalsIgnoreCase(headers.get("If-Range").value())) { - context.getResponse().setContentLength(size); - context.getResponse().status(HttpStatus.OK.getStatus()); - done = false; - } else { - String[] arr = headers.get("Range").value().split("=");//bytes=0- - if (arr.length != 2 || !"bytes".equalsIgnoreCase(arr[0])) { - context.getResponse().status(HttpStatus.NotAcceptable.getStatus()); - } else { - //http://blog.csdn.net/shuimuniao/article/details/8086438 - int state = 0; - - //不接受多个范围 - arr = Utility.split(arr[1], ",", true); - if (arr.length != 1) { - context.getResponse().status(HttpStatus.RequestedRangeNotSatisfiable.getStatus()); - } else { - arr = (" " + arr[0] + " ").split("-"); - if (arr.length != 2) { - context.getResponse().status(HttpStatus.BadRequest.getStatus()); - } else { - - try { - if ("".equals(arr[0].trim())) { - start = -1; - } else { - start = Long.parseUnsignedLong(arr[0].trim()); - } - } catch (NumberFormatException e) { - state = 1; - start = -1; - } - try { - if ("".equals(arr[1].trim())) { - end = -1; - } else { - end = Long.parseUnsignedLong(arr[1].trim()); - } - } catch (NumberFormatException e) { - end = -1; - state = 1; - } - if (state == 0) { - if (start == 0 && end == 0) { - len = 1; - } else if (start == -1 && end > 0) { - start = 0; - len = end + 1; - - } else if (start >= 0 && end < 0) { - end = size - 1; - len = size - start; - } else if (start > 0 && end > 0) { - len = end - start + 1; - } else { - len = -1; - state = 1; - } - } - - if (state != 0) { - context.getResponse().status(HttpStatus.BadRequest.getStatus()); - } else { - if (start == 0 && end == size - 1) { - context.getResponse().setContentLength(size); - context.getResponse().status(HttpStatus.OK.getStatus()); - } else { - range = true; - context.getResponse().setContentLength(len); - context.getResponse().status(HttpStatus.PartialContent.getStatus()); - } - context.getResponse().setHeader("Content-Range", "bytes " + start + "-" + end + "/" + size); - done = false; - } - } - } - } - } - } else { - context.getResponse().setContentLength(size); - context.getResponse().status(HttpStatus.OK.getStatus()); - done = false; - } - - if (!done) { - - context.getResponse().setHeader("Accept-Ranges", "bytes"); - context.getResponse().setHeader("ETag", etag); - context.getResponse().setHeader("Last-Modified", new DateTime(file.lastModified()).toGMTString()); - switch (context.getRequest().getMethod().name()) { - case "GET": - if (range) { - context.getResponse().transmit(path, start, len); - } else { - context.getResponse().transmit(path); - } - break; - case "HEAD": - //nothing - break; - default: - context.getResponse().status(HttpStatus.MethodNotAllowed.getStatus()); - } - - } - } catch (IOException | InvalidOperationException | NullPointerException ex) { - context.getResponse().write(ex.getMessage()); - context.getResponse().end(); - } - - return true; - } - - @Override - public boolean handle(HttpContext context, String tryPath) { - tryPath = (tryPath == null) ? "" : tryPath.toLowerCase().trim(); - if (tryPath == null) { - return false;//http://www.cnblogs.com/ghfsusan/archive/2010/06/01/1749607.html http://www.open-open.com/lib/view/open1342064478859.html - } - boolean result = false; - for (Entry entry : mappings.entrySet()) { - if (tryPath.endsWith("." + entry.getKey())) { - result = this.process(context, context.getServer().mapPath(tryPath), entry.getValue()); - if (result) { - break; - } - } - } - return result; - } - - @Override - public boolean handle(HttpContext context) { - return this.handle(context, context.getRequest().url().getPath()); - } - - @Override - public void dispose() { - mappings.clear(); - } - -} diff --git a/del/mano-server-projects/mano-web/src/main/java/mano/web/modules/UrlRoutingModule.java b/del/mano-server-projects/mano-web/src/main/java/mano/web/modules/UrlRoutingModule.java deleted file mode 100644 index 2542783..0000000 --- a/del/mano-server-projects/mano-web/src/main/java/mano/web/modules/UrlRoutingModule.java +++ /dev/null @@ -1,753 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Project. All rights reserved. - * - * See more http://mano.diosay.com/ - * - */ -package mano.web.modules; - -import java.io.File; -import java.io.FilenameFilter; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.lang.annotation.Annotation; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.JarURLConnection; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLDecoder; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.LinkedHashSet; -import java.util.Map; -import java.util.Properties; -import java.util.Set; -import java.util.jar.JarEntry; -import java.util.jar.JarFile; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import mano.caching.LruCacheProvider; -import mano.http.HttpContext; -import mano.http.HttpMethod; -import mano.http.HttpModule; -import mano.util.Utility; -import mano.web.ActionFilter; -import mano.web.ActionHandler; -import mano.web.ActionResult; -import mano.web.CookieParam; -import mano.web.Filter; -import mano.web.FilterGroup; -import mano.web.Module; -import mano.web.Named; -import mano.web.PathParam; -import mano.web.RequestParam; -import mano.web.SessionParam; -import mano.web.UrlMapping; -import mano.web.ViewContext; -import mano.web.ViewEngine; -import mano.web.ViewResult; -import mano.web.WebApplication; - -/** - * 通过 URL路由并调用 java 类和方法的模块。 - * - * @author jun - */ -public class UrlRoutingModule implements HttpModule { - - private class JarScanner { - - public void scan(URL url) { - String protocol = url.getProtocol().toLowerCase(); - if ("file".equals(protocol)) { - try { - this.scanFile(new File(URLDecoder.decode(url.getFile(), "UTF-8"))); - } catch (UnsupportedEncodingException ex) { - if (java.lang.MANO_WEB_MACRO.DEBUG) { - app.getLogger().debug(null, ex); - } - } - } else if ("jar".equals(protocol)) { - scanJar(url, null); - } - } - - public void scanJar(URL url, String libname) { - JarFile jar; - try { - jar = ((JarURLConnection) url.openConnection()).getJarFile(); - } catch (IOException ex) { - app.getLogger().debug("URL:" + url.toString(), ex); - return; - } - Enumeration entries = jar.entries(); - JarEntry entry; - String name; - while (entries.hasMoreElements()) { - entry = entries.nextElement(); - name = entry.getName(); - - if (!entry.isDirectory() && name.endsWith(".class") && name.indexOf("$") < 1) {// - name = (name.substring(0, name.length() - 6)).replace('/', '.'); - try { - resolveRoute(app.getLoader().loadClass(name)); - } catch (Throwable ex) { - if (java.lang.MANO_WEB_MACRO.DEBUG) { - app.getLogger().debug(null, ex); - } - } - } - } - } - - public void scanFile(File dir) { - //获取此包的目录 建立一个File - //File dir = new File(path); - //如果不存在或者 也不是目录就直接返回 - if (!dir.exists()) { - return; - } else if (dir.isFile() && dir.getName().toLowerCase().endsWith(".jar")) { - try { - if (File.separator.equals("\\")) { - scanJar(new URL("jar:file:/" + dir.toString() + "!/"), dir.getName().substring(0, dir.getName().length() - 4)); - } else { - scanJar(new URL("jar:file://" + dir.toString() + "!/"), dir.getName().substring(0, dir.getName().length() - 4)); - } - } catch (MalformedURLException ex) { - if (java.lang.MANO_WEB_MACRO.DEBUG) { - app.getLogger().debug(null, ex); - } - } - } else if (dir.isFile() && dir.getName().toLowerCase().endsWith(".class")) { - //如果是java类文件 去掉后面的.class 只留下类名 - String className = dir.getName().substring(0, dir.getName().length() - 6); - try { - resolveRoute(app.getLoader().loadClass(className)); - } catch (Throwable ex) { - if (java.lang.MANO_WEB_MACRO.DEBUG) { - app.getLogger().debug(null, ex); - } - } - } else if (dir.isDirectory()) { - dir.listFiles((file) -> { - scanFile(file); - return false; - }); - } - } -// -// final Class foundClass(String type) { -// try { -// return app.getLoader().loadClass(type); -// } catch (Throwable ex) { -// if (java.lang.MANO_WEB_MACRO.DEBUG) { -// app.getLogger().debug(null, ex); -// } -// } -// return null; -// } - - //final Pattern pattern = Pattern.compile("\\{\\s*(\\w+)\\s*\\}"); -// public void onFoundClass(Class clazz) { -// if (clazz == null) { -// return; -// } -// //.*/controller/action/(\w*)/(\w*).* -// //\{(\w+)(\?){0,1}\} -// //{?name} -// //default +1000 -// UrlMapping mapping; -// String url = null; -// int verb = 0; -// boolean pojo = false; -// Annotation[][] ps; -// String pname; -// Map map = new HashMap<>(); -// String part; -// ArrayList list = new ArrayList<>(); -// final StringBuilder sb = new StringBuilder(); -// Matcher matcher = pattern.matcher(sb); -// Route route; -// -// //查找类,获取第1部分URL -// if (Controller.class.isAssignableFrom(clazz)) { -// mapping = clazz.getAnnotation(UrlMapping.class); -// if (mapping != null) { -// url = mapping.value(); -// } -// if (url == null || "".equals(url.trim())) { -// url = clazz.getSimpleName().toLowerCase(); -// if (url.endsWith("controller")) { -// url = url.substring(0, url.length() - 10); -// } -// } -// } else { -// mapping = clazz.getAnnotation(UrlMapping.class); -// if (mapping == null) { -// return; -// } -// try { -// clazz.getMethod("setService", ViewContext.class); -// } catch (Throwable ex) { -// return; -// } -// url = mapping.value(); -// //verb = mapping.verb(); -// pojo = true; -// if (url == null || "".equals(url.trim())) { -// url = clazz.getSimpleName().toLowerCase(); -// if (url.endsWith("controller")) { -// url = url.substring(0, url.length() - 10); -// } -// } -// } -// if (!url.startsWith("/")) { -// url = "/" + url; -// } -// if (!url.endsWith("/")) { -// url += "/"; -// } -// -// //查找方法,获取第2部分URL 和签名参数 -// for (Method method : clazz.getDeclaredMethods()) { -// map.clear(); -// mapping = method.getAnnotation(UrlMapping.class); -// if (mapping == null) { -// continue; -// } -// -//// if (mapping.verb() > 0) { -//// verb = mapping.verb(); //重写父级定义 -//// } -// part = mapping.value(); -// -// if (part == null || "".equals(part.trim())) { -// part = method.getName(); -// } -// if (part.startsWith("/")) { -// part = part.substring(1); -// } -// -// list.clear(); -// sb.setLength(0); -// sb.append(url); -// sb.append(part); -// matcher = pattern.matcher(sb); -// while (matcher.find()) { -// String name = matcher.group(1); -// list.add(name); -// sb.replace(matcher.start(), matcher.end(), "(?<" + name + ">\\w+)"); -// } -// //解决最后一个元素不能被替换的BUG -// matcher = pattern.matcher(sb); -// while (matcher.find()) { -// String name = matcher.group(1); -// list.add(name);//{1}{2} -// sb.replace(matcher.start(), matcher.end(), "(?<" + name + ">\\w+)"); -// } -// -// //http://blog.sina.com.cn/s/blog_72827fb10101pl9i.html -// //http://blog.sina.com.cn/s/blog_72827fb10101pl9j.html -// if (sb.charAt(sb.length() - 1) != '$') { -// if (sb.charAt(sb.length() - 1) == '/') { -// sb.append("{0,1}$"); -// } else { -// sb.append("/{0,1}$"); -// } -// } -// if (sb.charAt(0) != '^') { -// sb.insert(0, "^"); -// } -// -// //参数映射集合 -// ps = method.getParameterAnnotations(); -// for (int i = 0; i < ps.length; i++) { -// for (int j = 0; j < ps[i].length; j++) { -// if (ps[i][j] instanceof PathParam) { -// pname = ((PathParam) ps[i][j]).value(); -// } else { -// pname = ""; -// } -// if ("".equals(pname) || !list.contains(pname)) { -// continue; -// } -// if (map.containsKey(i)) { -// //map.put(i, map.get(i) + "," + pname); -// } else { -// map.put(i, pname); -// } -// break; -// } -// } -// -// route = new Route(); -// method.setAccessible(true); -// route.call = method; -// route.clazz = clazz; -// //route.paramsMapping.putAll(map); -// route.patten = sb.toString(); -// route.controller = clazz.getSimpleName().toLowerCase(); -// -// if (route.controller.endsWith("controller")) { -// route.controller = route.controller.substring(0, route.controller.length() - 10); -// } -// -// route.action = method.getName().toLowerCase(); -// routeTable.add(route); -// } -// -// //PathMapping() -// //Routing(x,0); -// //clazz.getInterfaces() -// //System.out.println(clazz); -// } - } - - private class Route { - - Class clazz; - //boolean isPOJO; - String patten; - Method call; - String module; - String controller; - String action; - //String setServiceMethod; - HttpMethod httpMethod; - Map paramsMapping; - ActionFilter[] filters; - - public ActionFilter[] getActionFilters() throws Exception { - if (filters == null) { - ArrayList> tmp = new ArrayList<>(); - FilterGroup group = call.getAnnotation(FilterGroup.class); - if (group != null && group.value() != null && group.value().length > 0) { - for (Filter f : group.value()) { - if (!tmp.contains(f.value())) { - tmp.add(f.value()); - } - } - } else { - Filter[] tmps = call.getAnnotationsByType(Filter.class); - if (tmps != null) { - for (Filter f : tmps) { - if (!tmp.contains(f.value())) { - tmp.add(f.value()); - } - } - } - } - - group = clazz.getAnnotation(FilterGroup.class); - if (group != null && group.value() != null && group.value().length > 0) { - for (Filter f : group.value()) { - if (!tmp.contains(f.value())) { - tmp.add(f.value()); - } - } - } else { - Filter[] tmps = clazz.getAnnotationsByType(Filter.class); - if (tmps != null) { - for (Filter f : tmps) { - if (!tmp.contains(f.value())) { - tmp.add(f.value()); - } - } - } - } - - - ArrayList tmp2 = new ArrayList<>(); - ActionFilter filter; - for (Class c2 : tmp) { - filter = (ActionFilter) app.getLoader().newInstance(c2); - tmp2.add(filter); - } - - filters = tmp2.toArray(new ActionFilter[0]); - } - return filters; - } - Pattern test = null; - Matcher matcher; - - public boolean test(HttpContext context, String tryPath) { - if (httpMethod != HttpMethod.ALL && !context.getRequest().getMethod().equalWith(httpMethod)) { - return false; - } - if (test == null) { - try { - test = Pattern.compile(patten, Pattern.CASE_INSENSITIVE); - } catch (Throwable ex) { - if (java.lang.MANO_WEB_MACRO.DEBUG) { - app.getLogger().debug("patten error:" + patten, ex); - } - return false; - } - } - matcher = test.matcher(tryPath); - return matcher.matches(); - } -// Method m; -// -// private Method getMethod(Class type) throws Exception { -// try { -// return type.getDeclaredMethod("setService", ViewContext.class); -// } catch (NoSuchMethodException ex) { -// if (type.getSuperclass() != null) { -// return getMethod(type.getSuperclass()); -// } else { -// throw ex; -// } -// } catch (SecurityException ex) { -// throw ex; -// } -// } - -// public void setContext(ActionHandler instance, ViewContext context) throws Exception { -// ((ActionHandler) instance).init(context); -//// if (m == null) { -//// m = getMethod(clazz); -//// m.setAccessible(true); -//// } -//// m.invoke(instance, context); -// } - public Object getPathValue(HttpContext ctx, String name, Class type) { - return Utility.cast(type, matcher.group(name)); - } - - public Object getSessionValue(HttpContext ctx, String name, Class type) { - return Utility.cast(type, ctx.getSession().get(name)); - } - - public Object getCookieValue(HttpContext ctx, String name, Class type) { - return Utility.cast(type, ctx.getRequest().getCookie().get(name)); - } - - //TODO: - public Object getQueryValue(HttpContext ctx, String name, Class type) { - if (ctx.getRequest().query().containsKey(name)) { - return Utility.cast(type, ctx.getRequest().query().get(name)); - } - return Utility.cast(type, ctx.getRequest().form().get(name)); - } - - public Object getFormValue(HttpContext ctx, String name, Class type) { - return Utility.cast(type, ctx.getRequest().form().get(name)); - } - } - - private interface GetValue { - - Object value(Route r, HttpContext ctx); - } - - private ViewEngine viewEngine; - private Set routeTable = new LinkedHashSet<>(); - private WebApplication app; - private HashMap, ActionFilter> actionFilters = new HashMap<>(); - private LruCacheProvider cache = new LruCacheProvider(); - private final Pattern pattern = Pattern.compile("\\{\\s*(\\w+)\\s*\\}"); - private ArrayList> htypes = new ArrayList<>(); - - //http://www.cnblogs.com/Ghost-Draw-Sign/articles/1428174.html - @Override - public void init(WebApplication app, Properties params) { - this.app = app; - JarScanner scanner = new JarScanner(); - if (java.lang.MANO_WEB_MACRO.DEBUG) { - app.getLogger().info("scanning action handlers..."); - } - - app.getActionHandlers().forEach(tp -> { - try { - resolveRoute(tp); - } catch (Throwable ex) { - if (java.lang.MANO_WEB_MACRO.DEBUG) { - app.getLogger().info(ex); - } - } - }); - - URL[] urls = app.getActionHandlerJarUrls(); - if (urls != null) { - for (URL url : urls) { - try { - scanner.scan(url); - } catch (Throwable ex) { - if (java.lang.MANO_WEB_MACRO.DEBUG) { - app.getLogger().info("scanning jar:" + url, ex); - } - } - } - } - htypes = null; - try { - viewEngine = (ViewEngine) app.getLoader().newInstance(params.getProperty("view.engine")); - viewEngine.setTempdir(Utility.toPath(app.getApplicationPath(), "WEB-INF/tmp").toString()); - viewEngine.setViewdir(Utility.toPath(app.getApplicationPath(), "views").toString()); - } catch (Throwable ex) { - if (java.lang.MANO_WEB_MACRO.DEBUG) { - app.getLogger().info("failed to initialization module:", ex); - } - } - } - - public void resolveRoute(Class clazz) { - if (clazz == null || !ActionHandler.class.isAssignableFrom(clazz)) { - return; - } - - String module; - String controller; - String action; - StringBuilder sb = new StringBuilder(); - Module tmpModule = clazz.getAnnotation(Module.class); - if (tmpModule != null) { - module = tmpModule.value(); - } else { - module = ""; - } - Named named = clazz.getAnnotation(Named.class); - if (named != null) { - controller = named.value(); - } else { - controller = clazz.getSimpleName().toLowerCase(); - if (controller.endsWith("controller")) { - controller = controller.substring(0, controller.length() - 10); - } - } - UrlMapping mapping = clazz.getAnnotation(UrlMapping.class); - if (mapping != null) { - sb.append(mapping.value()); - if (sb.charAt(sb.length() - 1) != '/') { - sb.append('/'); - } - } else { - sb.append(controller).append('/'); - } - StringBuilder url; - Matcher matcher; - ArrayList list = new ArrayList<>(); - for (Method method : clazz.getDeclaredMethods()) { - mapping = method.getAnnotation(UrlMapping.class); - if (mapping == null) { //TODO:确认? - continue; - } - - named = method.getAnnotation(Named.class); - if (named != null) { - action = named.value(); - } else { - action = method.getName().toLowerCase(); - } - url = new StringBuilder(sb); - url.append(mapping.value().charAt(0) == '/' ? mapping.value().substring(1) : mapping.value()); - if (url.charAt(url.length() - 1) != '/') { - url.append('/'); - } - matcher = pattern.matcher(url); - list.clear(); - while (matcher.find()) { - String name = matcher.group(1); - list.add(name);//{1}{2} - try { - url.replace(matcher.start(), matcher.end(), "(?<" + name + ">\\w+)"); - } catch (Throwable ex) { - if (java.lang.MANO_WEB_MACRO.DEBUG) { - app.getLogger().info(sb, ex); - } - } - //matcher = pattern.matcher(url); - } - Map map = new HashMap<>(); - Class[] types = method.getParameterTypes(); - Annotation[][] ps = method.getParameterAnnotations(); - boolean bk = false; - for (int i = 0; i < ps.length; i++) { - - for (Annotation item : ps[i]) { - if (item instanceof PathParam) { - final String name = ((PathParam) item).value(); - if (!list.contains(name)) { - bk = true; - break; - } - final Class ptype = types[i]; - map.put(i, (r, ctx) -> { - return r.getPathValue(ctx, name, ptype); - }); - break; - } else if (item instanceof RequestParam) { - final String name = ((RequestParam) item).value(); - final Class ptype = types[i]; - map.put(i, (r, ctx) -> { - return r.getQueryValue(ctx, name, ptype); - }); - break; - } else if (item instanceof SessionParam) { - final String name = ((SessionParam) item).value(); - final Class ptype = types[i]; - map.put(i, (r, ctx) -> { - return r.getSessionValue(ctx, name, ptype); - }); - break; - } else if (item instanceof CookieParam) { - final String name = ((CookieParam) item).value(); - final Class ptype = types[i]; - map.put(i, (r, ctx) -> { - return r.getCookieValue(ctx, name, ptype); - }); - break; - } else { - bk = true; - } - } - if (bk) { - break; - } - } - // - if (bk) { - return; - } - - if (url.charAt(url.length() - 1) != '$') { - if (url.charAt(url.length() - 1) == '/') { - url.append("?$"); - } else { - url.append("/?$"); - } - } - if (url.charAt(0) != '^') { - if (url.charAt(0) != '/') { - url.insert(0, '/'); - } - url.insert(0, '^'); - } - method.setAccessible(true); - Route route = new Route(); - route.paramsMapping = map; - route.action = action; - route.call = method; - route.clazz = (Class) clazz; - route.controller = controller; - route.patten = url.toString(); - route.httpMethod = mapping.verb(); - route.module = module; - htypes.add(clazz); - routeTable.add(route); - } - - } - - @Override - public boolean handle(HttpContext context) throws Exception { - return this.handle(context, context.getRequest().url().getPath()); - } - - @Override - public boolean handle(HttpContext context, String tryPath) throws Exception { - if (viewEngine == null) { - return false; - } else if (!context.getRequest().isConnected()) { - return false; - } - - String key = context.getRequest().getMethod() + ":" + context.getRequest().url().toString(); - Route route = null; - try { - if (cache.get(key) == null) { - - for (Route r : routeTable) { - if (r.patten.startsWith("res") || r.patten.startsWith("^/res") || r.patten.startsWith("^/res")) { - int x = 0; - } - if (r.test(context, tryPath)) { - route = r; - cache.set(key, r, 1000 * 60 * 10, true, null); - break; - } - } - } else { - route = (Route) (cache.get(key).getValue()); - } - } catch (Throwable ex) { - if (java.lang.MANO_WEB_MACRO.DEBUG) { - app.getLogger().info("matching route error", ex); - } - return false; - } - - if (route == null) { - if (java.lang.MANO_WEB_MACRO.DEBUG) { - app.getLogger().info("no matching: " + " url:" + tryPath); - } - return false; - } - - Object[] params = new Object[route.call.getParameterCount()]; - try { - route.test(context, tryPath); - for (int i = 0; i < params.length; i++) { - params[i] = route.paramsMapping.get(i).value(route, context); - } - } catch (Throwable ex) { - if (java.lang.MANO_WEB_MACRO.DEBUG) { - app.getLogger().info("Failed to convert parameters: " + route.patten, ex); - } - return false; - } - finally{ - route.matcher=null; - } - ViewContext vc; - ActionHandler obj = app.getLoader().newInstance(route.clazz); - vc = viewEngine.createContext(context); - vc.setController(route.controller); - vc.setAction(route.action); - obj.init(vc); - for (ActionFilter filter : route.getActionFilters()) { - filter.onActionExecuting(vc); - } - route.call.invoke(obj, params); - for (ActionFilter filter : route.getActionFilters()) { - filter.onActionExecuted(vc); - } -// try { -// -// } catch (Throwable ex) { -// Throwable err = ex instanceof InvocationTargetException ? ((InvocationTargetException) ex).getTargetException() : ex; -// if (java.lang.MANO_WEB_MACRO.DEBUG) { -// app.getLogger().info("failed to execute handler:", err); -// } -// context.getResponse().write(err.getClass() + ":" + err.getMessage()); -// return true; -// } - if (!context.getRequest().isConnected()) { - throw new java.nio.channels.ClosedChannelException(); - } - ActionResult result = vc.getResult(); - if (result == null) { - return true; - } - if (result instanceof ViewResult) { - ((ViewResult) result).init(viewEngine); - } - - result.execute(vc); - return true; - } - - @Override - public void dispose() { - viewEngine = null; - app = null; - routeTable = null; - cache = null; - actionFilters = null; - } - -} diff --git a/del/mano-server-projects/mano-web/src/main/java/mano/web/runtime/HttpChannel.java b/del/mano-server-projects/mano-web/src/main/java/mano/web/runtime/HttpChannel.java deleted file mode 100644 index aaf21ef..0000000 --- a/del/mano-server-projects/mano-web/src/main/java/mano/web/runtime/HttpChannel.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Project. All rights reserved. - * - * See more http://mano.diosay.com/ - * - */ -package mano.web.runtime; - -import com.diosay.mano.io.AioSocketChannel; -import com.diosay.mano.io.ChannelBuffer; -import com.diosay.mano.io.Listener; -import java.nio.channels.AsynchronousSocketChannel; -import java.nio.charset.Charset; -import mano.caching.CacheProvider; -import mano.http.HttpContext; -import mano.http.HttpRequest; -import mano.http.HttpResponse; -import mano.http.HttpServer; -import mano.service.Service; -import mano.service.ServiceManager; -import mano.service.ServiceProvider; -import mano.web.HttpSession; -import mano.web.WebApplication; -import mano.web.WebApplicationStartupInfo; - -/** - * HTTP协议通道。 - * - * @author jun - */ -public class HttpChannel extends AioSocketChannel implements HttpContext { - - HttpChannel(AsynchronousSocketChannel channel, Listener listener) { - super(channel, listener); - } - - Charset inputEncoding = Charset.forName("utf-8"); - - /** - * 获取输入编码。 - * - * @return - */ - public Charset getInputEncoding() { - return inputEncoding; - } - - public static final int IDLE = 0; - public static final int REQUEST_LINE = 1; - public static final int LOAD_HEADER = 2; - public static final int RESPONSE = 3; - int phase; - ChannelBuffer buffer; - HttpRequestImpl request; - HttpResponseImpl response; - HttpServer server; - WebApplication application; - HttpSession session; - boolean isCompleted; - - void start() { - buffer.clear(); - request = null; - phase = REQUEST_LINE; - } - - boolean postResponse() { - HttpService service = (HttpService) this.getListener().getGroup(); - String host = request.headers.get("Host").value(); - WebApplicationStartupInfo info = null; - - for (WebApplicationStartupInfo i : service.appInfos.values()) { - if (i.matchHost(host)) { - info = i; - break; - } - } - - if (info == null) { - service.appInfos.get("*"); - } - - if (info == null) { - return false; - } - //info.serviceLoader=((HttpService)this.getListener().getGroup()).loader; - info.service=(Service)this.getListener().getGroup(); - WebApplication app = info.getInstance(); - if (app == null) { - return false; - } - application = app; - server = info.getServerInstance(); - response = new HttpResponseImpl(); - response.channel = this; - - //build session - Service svc = ServiceManager.get("cache.service"); - if (svc != null && svc instanceof ServiceProvider) { - CacheProvider provider = ((ServiceProvider) svc).getService(CacheProvider.class);//TODO: 指定实例服务 - if (provider != null) { - String sid = request.getCookie().get(HttpSession.COOKIE_KEY); - session = HttpSession.getSession(sid, provider); - - if (session.isNewSession()) { - //req.url().getHost() - response.getCookie().set(HttpSession.COOKIE_KEY, session.getSessionId(), 0, "/", null, false, false); - } - } else { - //logger.error("CacheProvider not found."); - } - } else { - //logger.error("cache.service not found."); - } - response.setHeader("Server", server.getVersion()); - //context.response.setHeader("X-Powered-By", "mano/1.1,java/1.8"); - - app.processRequest(this); - - return true; - } - - @Override - public WebApplication getApplication() { - return this.application; - } - - @Override - public boolean isCompleted() { - return isCompleted; - } - - @Override - public HttpRequest getRequest() { - return request; - } - - @Override - public HttpResponse getResponse() { - return response; - } - - @Override - public HttpServer getServer() { - return server; - } - - @Override - public HttpSession getSession() { - return session; - } - -} diff --git a/del/mano-server-projects/mano-web/src/main/java/mano/web/runtime/HttpListener.java b/del/mano-server-projects/mano-web/src/main/java/mano/web/runtime/HttpListener.java deleted file mode 100644 index e01e647..0000000 --- a/del/mano-server-projects/mano-web/src/main/java/mano/web/runtime/HttpListener.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Project. All rights reserved. - * - * See more http://mano.diosay.com/ - * - */ -package mano.web.runtime; - -import com.diosay.mano.io.Channel; -import com.diosay.mano.io.Listener; -import java.nio.channels.AsynchronousSocketChannel; - -/** - * - * @author jun - */ -public class HttpListener extends Listener{ - - @Override - protected Channel create(AsynchronousSocketChannel remote) { - return new HttpChannel(remote,this); - } - -} diff --git a/del/mano-server-projects/mano-web/src/main/java/mano/web/runtime/HttpProtocol11.java b/del/mano-server-projects/mano-web/src/main/java/mano/web/runtime/HttpProtocol11.java deleted file mode 100644 index 1561078..0000000 --- a/del/mano-server-projects/mano-web/src/main/java/mano/web/runtime/HttpProtocol11.java +++ /dev/null @@ -1,261 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Project. All rights reserved. - * - * See more http://mano.diosay.com/ - * - */ -package mano.web.runtime; - -import com.diosay.mano.io.ByteArrayMessage; -import com.diosay.mano.io.ChannelBuffer; -import com.diosay.mano.io.ChannelCloseingMessage; -import com.diosay.mano.io.ChannelHanlder; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.nio.channels.ClosedChannelException; -import java.nio.channels.InterruptedByTimeoutException; -import mano.DateTime; -import mano.http.HttpException; -import mano.http.HttpHeader; -import mano.http.HttpMethod; -import mano.http.HttpStatus; -import mano.http.HttpVersion; - -/** - * HTTP 1.1协议。 - * - * @author jun - */ -public class HttpProtocol11 implements ChannelHanlder { - - @Override - public void connected(HttpChannel channel) throws Exception { - //channel.handler = this; - channel.buffer = channel.getListener().getGroup().allocate(); - channel.start(); - channel.read(channel.buffer); - } - - @Override - public void closed(HttpChannel channel) { - channel.getListener().getGroup().free(channel.buffer); - channel.buffer=null; - } - - @Override - public void read(ChannelBuffer buffer, Integer reads, HttpChannel channel) throws Exception { - String line = null; - if (channel.phase == HttpChannel.LOAD_HEADER || channel.phase == HttpChannel.REQUEST_LINE) { - HttpHeader header; - boolean done; - while ((line = buffer.readln(channel.getInputEncoding())) != null) { - if (channel.phase == HttpChannel.REQUEST_LINE) { - channel.request = new HttpRequestImpl(); - channel.request.channel = channel; - String[] arr = line.split(" "); - channel.request.method = HttpMethod.valueOf(arr[0]); - channel.request.rawUrl = arr[1]; - channel.request.version = HttpVersion.valueOf(arr[2]); - channel.phase = HttpChannel.LOAD_HEADER; - } else if ("".equals(line)) { - channel.phase = HttpChannel.RESPONSE; - if (!channel.postResponse()) { - throw new HttpException(HttpStatus.BadRequest, "Bad Request(Invalid Hostname)"); - } - return; - } else { - header = HttpHeader.prase(line); - channel.request.headers.put(header); - } - } - if (!buffer.buffer.hasRemaining()) { - failed(new IllegalArgumentException("缓冲区已满,请求头太大"), channel); - } else { - channel.read(buffer); - } - } else if (channel.phase == HttpChannel.RESPONSE) { - if (channel.request == null || channel.request.decoder == null) { - throw new IllegalStateException("未设置处理程序"); - } - - int pos = buffer.position(); - channel.request.decoder.onRead(buffer, channel.request); - channel.request.remaining -= buffer.position() - pos; - - if (channel.request.loadedFlag.get() && (channel.request.remaining > 0 || buffer.hasRemaining())) { - channel.request.remaining -= buffer.remaining(); - buffer.position(buffer.limit());//TODO - } - - if (channel.request.remaining > 0) { - if (!buffer.hasRemaining()) { - buffer.clear(); - } else { - buffer.compact(); - } - channel.read(buffer); - } - } else { - //error - throw new IllegalStateException("未定义的处理阶段"); - } - - } - - @Override - public void written(ChannelBuffer buffer, Integer reads, HttpChannel channel) { - } - - @Override - public void failed(Throwable exc, HttpChannel channel) { - - if (exc instanceof InterruptedByTimeoutException) { - channel.close(); - return; - } else if (exc instanceof ClosedChannelException) { - channel.close(); - return; - }else if(exc.getMessage()!=null && exc.getMessage().indexOf("connection was aborted")>0){ - channel.close(); - return; - }else if(!channel.isOpen()){ - channel.close(); - return; - } - System.err.println("ERR:"); - exc.printStackTrace(System.err); - this.responseError(exc, channel); - } - - private void printRoot(StringBuilder sb, Throwable t) { - if (t == null) { - return; - } - sb.append("root

");
-        StringWriter sw = new StringWriter();
-        try (PrintWriter pw = new PrintWriter(sw)) {
-            pw.println();
-            t.printStackTrace(pw);
-        }
-        sb.append(sw.toString());
-        sb.append("

"); - printRoot(sb, t.getCause()); - } - - public void responseError(Throwable t, HttpChannel channel) { - HttpStatus status; - StringBuilder sb = new StringBuilder(); - if (t instanceof HttpException) { - HttpException ex = (HttpException) t; - status = ex.getHttpStatus(); - sb.append("") - .append(ex.getHttpStatus().getStatus()) - .append(" Error") - .append(""); - if (ex.getMessage() != null) { - sb.append("message") - .append(ex.getMessage()) - .append(""); - } - if (ex.getCause() != null) { - sb.append("exception

");
-                StringWriter sw = new StringWriter();
-                try (PrintWriter pw = new PrintWriter(sw)) {
-                    pw.println();
-                    ex.getCause().printStackTrace(pw);
-                }
-                sb.append(sw.toString());
-                sb.append("

"); - printRoot(sb, ex.getCause().getCause()); - } - sb.append("
") - .append("Mano Server");//context.getServer().getVersion() - } else { - status = HttpStatus.InternalServerError; - sb.append("") - .append(HttpStatus.InternalServerError.getStatus()) - .append(" Error") - .append(""); - if (t.getMessage() != null) { - sb.append("message") - .append(t.getMessage()) - .append(""); - } - if (t.getCause() != null) { - sb.append("exception

");
-                StringWriter sw = new StringWriter();
-                try (PrintWriter pw = new PrintWriter(sw)) {
-                    pw.println();
-                    t.getCause().printStackTrace(pw);
-                }
-                sb.append(sw.toString());
-                sb.append("

"); - printRoot(sb, t.getCause().getCause()); - } - sb.append("
") - .append("Mano Server");//context.getServer().getVersion() - } - sb.append(""); - byte[] response = sb.toString().getBytes(channel.getInputEncoding()); - sb = new StringBuilder("HTTP/1.1 "); - sb.append(status.getStatus()).append(" ").append(status.getDescription()).append("\r\n"); - sb.append("Content-Length:").append(response.length).append("\r\n"); - sb.append("Connection:close").append("\r\n"); - sb.append("Date:").append(DateTime.now().toGMTString()).append("\r\n"); - sb.append("\r\n"); - - byte[] bytes = sb.toString().getBytes(channel.getInputEncoding()); - ByteArrayMessage msg = new ByteArrayMessage(); - msg.handler = this; - msg.array = bytes; - msg.offset = 0; - msg.length = bytes.length; - channel.enqueue(msg); - - msg = new ByteArrayMessage(); - msg.handler = this; - msg.array = response; - msg.offset = 0; - msg.length = response.length; - channel.enqueue(msg); - - ChannelCloseingMessage msg2 = new ChannelCloseingMessage(); - msg2.handler = this; - channel.enqueue(msg2); - } - -// public void responseError(HttpException ex, HttpChannel channel) { -// StringWriter sw = new StringWriter(); -// try (PrintWriter pw = new PrintWriter(sw)) { -// pw.println(); -// ex.printStackTrace(pw); -// } -// byte[] response = String.format("HTTP %s Error%s", ex.getHttpCode(), sw.toString()).getBytes(); -// StringBuilder sb = new StringBuilder("HTTP/1.1 "); -// sb.append(ex.getHttpCode()).append(" ").append(HttpStatus.getKnowDescription(ex.getHttpCode())).append("\r\n"); -// sb.append("Content-Length:").append(response.length).append("\r\n"); -// sb.append("Connection:close").append("\r\n"); -// sb.append("Date:").append(DateTime.now().toGMTString()).append("\r\n"); -// sb.append("\r\n"); -// -// byte[] bytes = sb.toString().getBytes(channel.getInputEncoding()); -// ByteArrayMessage msg = new ByteArrayMessage(); -// msg.handler = this; -// msg.array = bytes; -// msg.offset = 0; -// msg.length = bytes.length; -// channel.enqueue(msg); -// -// msg = new ByteArrayMessage(); -// msg.handler = this; -// msg.array = response; -// msg.offset = 0; -// msg.length = response.length; -// channel.enqueue(msg); -// -// ChannelCloseingMessage msg2 = new ChannelCloseingMessage(); -// msg2.handler = this; -// channel.enqueue(msg2); -// -// } -} diff --git a/del/mano-server-projects/mano-web/src/main/java/mano/web/runtime/HttpRequestImpl.java b/del/mano-server-projects/mano-web/src/main/java/mano/web/runtime/HttpRequestImpl.java deleted file mode 100644 index 99756b0..0000000 --- a/del/mano-server-projects/mano-web/src/main/java/mano/web/runtime/HttpRequestImpl.java +++ /dev/null @@ -1,254 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Project. All rights reserved. - * - * See more http://mano.diosay.com/ - * - */ -package mano.web.runtime; - -import java.nio.charset.Charset; -import java.util.Map; -import java.util.concurrent.atomic.AtomicBoolean; -import mano.InvalidOperationException; -import mano.http.HttpEntityBodyAppender; -import mano.http.HttpEntityBodyDecoder; -import mano.http.HttpFormUrlEncodedDecoder; -import mano.http.HttpHeaderCollection; -import mano.http.HttpMethod; -import mano.http.HttpMultipartDecoder; -import mano.http.HttpPostFile; -import mano.http.HttpRequest; -import mano.http.HttpVersion; -import mano.util.NameValueCollection; - -/** - * - * @author jun - */ -public class HttpRequestImpl extends HttpRequest implements HttpEntityBodyAppender { - - HttpMethod method; - String rawUrl; - HttpVersion version; - HttpHeaderCollection headers = new HttpHeaderCollection(); - final AtomicBoolean postLoadedFlag = new AtomicBoolean(false); - final AtomicBoolean loadedFlag = new AtomicBoolean(false); - Map form; - Map files; - long contentLength; - long remaining; - boolean hasEntityBody; - boolean isChunked; - boolean isFormUrlEncoded; - boolean isFormMultipart; - String boundary; - HttpChannel channel; - HttpEntityBodyDecoder decoder; - boolean pred; - private synchronized void pre(){ - if(pred){ - return; - } - pred=true; - form = new NameValueCollection<>(); - files = new NameValueCollection<>(); - if (headers.containsKey("Content-length")) { - remaining = contentLength = Long.parseLong(headers.get("Content-Length").value()); - } - - if (contentLength >= 0 && (HttpMethod.POST.equals(method) || HttpMethod.PUT.equals(method))) { - hasEntityBody = true; - if (headers.containsKey("Transfer-Encoding") - && "chunked".equalsIgnoreCase(headers.get("Transfer-Encoding").value())) { - isChunked = true; - } - - if (headers.containsKey("Content-Type")) { - - if ("application/x-www-form-urlencoded".equalsIgnoreCase(headers.get("Content-Type").value())) { - isFormUrlEncoded = true; - } else if ("multipart/form-data".equalsIgnoreCase(headers.get("Content-Type").value())) { - isFormMultipart = true; - boundary = "--" + headers.get("Content-Type").attr("boundary"); - } - } - } - } - - private synchronized void doLoadEntityBody(boolean auto) { - postLoadedFlag.set(true); - - if (isChunked) { - throw new UnsupportedOperationException("Not supported chunked encoding."); - } else if (auto && isFormUrlEncoded) { - try { - postLoadedFlag.set(false); - loadEntityBody(new HttpFormUrlEncodedDecoder()); - } catch (Exception ex) { - throw new InvalidOperationException(ex); - } - } else if (auto && isFormMultipart) { - try { - postLoadedFlag.set(false); - loadEntityBody(new HttpMultipartDecoder()); - } catch (Exception ex) { - throw new InvalidOperationException(ex); - } - } - } - - private void waitLoadEntityBody() { - try { - synchronized (loadedFlag) { - if (!loadedFlag.get()) { - loadedFlag.wait(1000 * 60 * 30);//30m - } - } - } catch (InterruptedException ex) { - throw new InvalidOperationException(ex); - } - } - - public boolean keepAlive() { - return false; - } - - @Override - public String method() { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public String version() { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public String protocol() { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public HttpHeaderCollection headers() { - return headers; - } - - @Override - public String rawUrl() { - return rawUrl; - } - - @Override - public long getContentLength() { - return contentLength; - } - - @Override - public Map form() { - loadEntityBody(); - return form; - } - - @Override - public Map files() { - loadEntityBody(); - return files; - } - - @Override - public boolean isSecure() { - return false; - } - - @Override - public boolean isConnected() { - return channel.isOpen(); - } - - @Override - public boolean canLoadEntityBody() { - pre(); - return hasEntityBody && !postLoadedFlag.get(); - } - - @Override - public void loadEntityBody(HttpEntityBodyDecoder decoder) throws Exception { - if (!canLoadEntityBody()) { - return; - } - doLoadEntityBody(false); - postLoadedFlag.set(true); - this.decoder = decoder; - int pos = channel.buffer.position(); - if (channel.buffer.hasRemaining()) { - decoder.onRead(channel.buffer, this); - this.remaining -= channel.buffer.position() - pos; - } - - if(loadedFlag.get() && (this.remaining >0 || channel.buffer.hasRemaining())){ - this.remaining-=channel.buffer.remaining(); - channel.buffer.position(channel.buffer.limit());//TODO - } - - if (this.remaining > 0) { - if (!channel.buffer.hasRemaining()) { - channel.buffer.clear(); - } else { - channel.buffer.compact(); - } - channel.read(channel.buffer); - } - waitLoadEntityBody(); - } - - @Override - public void loadEntityBody() throws InvalidOperationException { - if (!canLoadEntityBody()) { - return; - } - doLoadEntityBody(true); - } - - @Override - public void Abort() { - channel.close(); - } - - @Override - public HttpVersion getVersion() { - return version; - } - - @Override - public HttpMethod getMethod() { - return method; - } - - @Override - public String getBoundary() { - return this.boundary; - } - - @Override - public void appendPostFile(HttpPostFile file) { - files.put(file.getName(), file); - } - - @Override - public void appendFormItem(String name, String value) { - form.put(name, value); - } - - @Override - public void notifyDone() { - synchronized (loadedFlag) { - this.loadedFlag.set(true); - this.loadedFlag.notify(); - } - } - - @Override - public Charset getEncoding() { - return channel.inputEncoding; - } -} diff --git a/del/mano-server-projects/mano-web/src/main/java/mano/web/runtime/HttpResponseImpl.java b/del/mano-server-projects/mano-web/src/main/java/mano/web/runtime/HttpResponseImpl.java deleted file mode 100644 index 3c15add..0000000 --- a/del/mano-server-projects/mano-web/src/main/java/mano/web/runtime/HttpResponseImpl.java +++ /dev/null @@ -1,289 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Project. All rights reserved. - * - * See more http://mano.diosay.com/ - * - */ -package mano.web.runtime; - -import com.diosay.mano.io.ByteArrayMessage; -import com.diosay.mano.io.ByteBufferMessage; -import com.diosay.mano.io.Channel; -import com.diosay.mano.io.ChannelCloseingMessage; -import com.diosay.mano.io.ChannelHanlder; -import com.diosay.mano.io.FileReginMessage; -import com.diosay.mano.io.Message; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.channels.FileChannel; -import java.util.Map; -import mano.DateTime; -import mano.InvalidOperationException; -import mano.http.HttpCookieCollection; -import mano.http.HttpHeader; -import mano.http.HttpHeaderCollection; -import mano.http.HttpResponse; -import mano.util.LockState; - -/** - * 当前HTTP请求的响应。 - * - * @author jun - */ -public class HttpResponseImpl extends HttpResponse { - - HttpChannel channel; - ByteBuffer buffer; - boolean headerSent = false; - boolean chunked = false; - boolean endFlush = false; - long contentLength = 0; - boolean auto = true; - static final String CRLF = "\r\n"; - HttpHeaderCollection headers = new HttpHeaderCollection(); - public HttpResponseImpl(){ - this.buffering(false); - } - private void writeHeaders() { - checkAndThrowHeaderSent(); - - - StringBuilder sb = new StringBuilder(); - sb.append(String.format("%s %s %s%s", "HTTP/1.1", this.status(), this.statusDescription(), CRLF)); - - if (!headers.containsKey("Date")) { - this.setHeader("Date", DateTime.now().toGMTString()); - } - - if (!headers.containsKey("Connection")) { - this.setHeader("Connection", channel.request.keepAlive() ? "keep-alive" : "close"); - } - - if (!headers.containsKey("Content-Type")) { - this.setHeader("Content-Type", "text/html;charset=utf-8"); - } - - if (!this.chunked || this.endFlush) { - this.setHeader("Content-Length", this.contentLength + ""); - } else { - this.setHeader("Transfer-Encoding", "chunked"); - } - - /*if (connection.context != null) { - if (connection.context.session != null && connection.context.session.isNewSession()) { - this.getCookie().set(HttpSession.COOKIE_KEY, connection.context.session.getSessionId(), 0, null, null, true, false); - } - this.setHeader("Server", connection.context.getServer().getVersion()); - this.setHeader("X-Powered-By", "mano/1.1,java/1.8"); - }*/ - for (Map.Entry entry : headers.entrySet()) { - sb.append(String.format("%s%s", entry.getValue().toString(), CRLF)); - } - - for (HttpCookieCollection.CookieEntry entry : this.getCookie().iterator()) { - sb.append(String.format("%s%s%s", "Set-Cookie:", entry.toString(), CRLF)); - } - - sb.append(CRLF); - - ByteArrayMessage msg = new ByteArrayMessage(); - msg.array = sb.toString().getBytes(this.charset()); - msg.offset = 0; - msg.length = msg.array.length; - //msg.handler = channel.handler; - channel.enqueue(msg); - headerSent = true; - } - - private synchronized void transferFile(String filename, long position, long length) throws IOException { - this.flush(); - - if (endFlush) { - throw new IOException("错误的传输方式"); - } else if (chunked) { - contentLength += length; - ByteArrayMessage msg = new ByteArrayMessage(); - msg.array = String.format("%s %s", Long.toHexString(length), CRLF).getBytes(this.charset()); - msg.offset = 0; - msg.length = msg.array.length; - //msg.handler = channel.handler; - channel.enqueue(msg); - - FileReginMessage fmsg = new FileReginMessage(); - //fmsg.handler = channel.handler; - fmsg.filename = filename; - fmsg.position = position; - fmsg.length = length; - channel.enqueue(fmsg); - - msg = new ByteArrayMessage(); - msg.array = String.format("%s", CRLF).getBytes(this.charset()); - msg.offset = 0; - msg.length = msg.array.length; - //msg.handler = channel.handler; - channel.enqueue(msg); - - } else { - contentLength -= length; - FileReginMessage fmsg = new FileReginMessage(); - //fmsg.handler = channel.handler; - fmsg.filename = filename; - fmsg.position = position; - fmsg.length = length; - channel.enqueue(fmsg); - } - - } - - @Override - public HttpHeaderCollection headers() { - return headers; - } - - @Override - public void setHeader(String name, String text) throws InvalidOperationException { - checkAndThrowHeaderSent(); - if (headers.containsKey(name)) { - headers.get(name).text(text); - } else { - headers.put(new HttpHeader(name, text)); - } - } - - @Override - public void setHeader(HttpHeader header) throws InvalidOperationException { - checkAndThrowHeaderSent(); - if (headers.containsKey(header.name())) { - this.setHeader(header.name(), header.text()); - } else { - headers.put(header); - } - } - - @Override - public void setContentLength(long length) throws InvalidOperationException { - checkAndThrowHeaderSent(); - auto = false; - contentLength = length; - chunked = false; - } - - @Override - public boolean headerSent() { - return headerSent; - } - - @Override - public boolean isConnected() { - return channel.isOpen(); - } - - @Override - public void write(byte[] array, int offset, int length) { - if(length==0){ - return; - } - if (!this.buffering()) { - buffer = ByteBuffer.wrap(array, offset, length); - this.flush(); - - } else { - if (buffer != null) { - int remaining = buffer.remaining() - length; - if (remaining >= 0) { - buffer.put(array, offset, length); - } else { - int len=buffer.remaining(); - buffer.put(array, offset, len); - flush(); - this.write(array, offset + len, length-len); - } - - } else { - contentLength += length; - buffer=ByteBuffer.allocate(1024>length?1024:length); - buffer.put(array, offset, length); - } - } - - } - - @Override - public void transmit(String filename) throws FileNotFoundException, IOException { - try (FileChannel chan = new FileInputStream(filename).getChannel()) { - this.transferFile(filename, 0, chan.size()); - } - } - - @Override - public void transmit(String filename, long position, long length) throws FileNotFoundException, IOException { - this.transferFile(filename, position, length); - } - - @Override - public void flush() { - if (!headerSent) { - if (!endFlush && auto) { - chunked = true; - } - writeHeaders(); - } - - if (buffer != null && this.buffering()) { - buffer.flip(); - } - - if (chunked) { - ByteArrayMessage msg; - if (buffer != null) { - contentLength += buffer.limit(); - msg = new ByteArrayMessage(); - msg.array = String.format("%s %s", Long.toHexString(buffer.limit()), CRLF).getBytes(this.charset()); - msg.offset = 0; - msg.length = msg.array.length; - //msg.handler = channel.handler; - channel.enqueue(msg); - - ByteBufferMessage msg2 = new ByteBufferMessage(); - msg2.buffer = buffer; - //msg2.handler = channel.handler; - channel.enqueue(msg2); - - msg = new ByteArrayMessage(); - msg.array = String.format("%s", CRLF).getBytes(this.charset()); - msg.offset = 0; - msg.length = msg.array.length; - //msg.handler = channel.handler; - channel.enqueue(msg); - } - - if (endFlush) { - msg = new ByteArrayMessage(); - msg.array = String.format("0%s%s", CRLF, CRLF).getBytes(this.charset()); - msg.offset = 0; - msg.length = msg.array.length; - //msg.handler = channel.handler; - channel.enqueue(msg); - } - - } else if (buffer != null) { - contentLength -= buffer.limit(); - ByteBufferMessage msg2 = new ByteBufferMessage(); - msg2.buffer = buffer; - //msg2.handler = channel.handler; - channel.enqueue(msg2); - } - - buffer = null; - } - - @Override - public void end() { - endFlush = true; - flush(); - channel.enqueue(new ChannelCloseingMessage()); - } - -} diff --git a/del/mano-server-projects/mano-web/src/main/java/mano/web/runtime/HttpService.java b/del/mano-server-projects/mano-web/src/main/java/mano/web/runtime/HttpService.java deleted file mode 100644 index 3425e0d..0000000 --- a/del/mano-server-projects/mano-web/src/main/java/mano/web/runtime/HttpService.java +++ /dev/null @@ -1,487 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ -package mano.web.runtime; - -import com.diosay.mano.io.AbstractChannelGroup; -import com.diosay.mano.io.ChannelBuffer; -import com.diosay.mano.io.Listener; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.net.InetSocketAddress; -import java.nio.channels.AsynchronousChannelGroup; -import java.util.Map; -import java.util.Properties; -import java.util.concurrent.Executors; -import mano.ContextClassLoader; -import mano.Mano; -import mano.http.HttpModuleSettings; -import mano.service.Service; -import mano.service.ServiceManager; -import mano.util.NameValueCollection; -import mano.util.Pool; -import mano.util.Utility; -import mano.util.logging.ILogger; -import mano.util.logging.Logger; -import mano.util.xml.XmlException; -import mano.util.xml.XmlHelper; -import mano.web.WebApplicationStartupInfo; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -/** - * HTTP服务。 - * - * @author jun - */ -public class HttpService extends AbstractChannelGroup implements Service,Runnable { - - private Properties properties = new Properties(); - private int maxConnections; - private int bufferSize; - ContextClassLoader loader; - private ILogger logger; - private String name; - Pool bufferPool; - WebApplicationStartupInfo machine; - NameValueCollection appInfos; - private NameValueCollection infos; - - @Override - public Properties getProperties() { - return properties; - } - - @Override - public String getName() { - return name; - } - - - @Override - public void run() { - this.start(); - } - - @Override - public void init() throws Exception { - configure(); - AsynchronousChannelGroup group = AsynchronousChannelGroup.withThreadPool(this.getExecutorService()); - for (ConnectionInfo conn : infos.values()) { - if (conn.disabled) { - continue; - } - this.regsister(new HttpListener()) - .init(group, conn.address, 32); - - } - this.setHandler(HttpProtocol11.class); - } - - private long parseSize(String size) { - long result; - if (size.endsWith("M") || size.endsWith("m")) { - result = Long.parseUnsignedLong(size.substring(0, size.length() - 1)) * (1024 * 1024); - } else if (size.endsWith("K") || size.endsWith("k")) { - result = Long.parseUnsignedLong(size.substring(0, size.length() - 1)) * 1024; - } else if (size.endsWith("B") || size.endsWith("b")) { - result = Long.parseUnsignedLong(size.substring(0, size.length() - 1)); - } else { - result = Long.parseUnsignedLong(size); - } - return result; - } - - private void configure() throws Exception { - - loader = ServiceManager.getLoader(); - logger = loader.getLogger(); - - //预处理配置值。 - if (this.getProperties().containsKey("config_file")) { - this.getProperties().setProperty("config_file", Utility.getAndReplaceMarkup("config_file", this.getProperties(), Mano.getProperties(), System.getProperties())); - } else { - throw new java.lang.IllegalArgumentException("未设置配置文件。"); - } - - if (this.getProperties().containsKey("webapp.config_path")) { - this.getProperties().setProperty("webapp.config_path", Utility.getAndReplaceMarkup("webapp.config_path", this.getProperties(), Mano.getProperties(), System.getProperties())); - } else { - this.getProperties().setProperty("webapp.config_path", Utility.toPath(Mano.getProperty("server.dir"), "conf/apps").toString()); - } - - if (this.getProperties().containsKey("service_name")) { - this.name = this.getProperties().getProperty("service_name"); - } else { - this.name = this.getClass().getName(); - } - - String s; - - //缓冲区池 - if (this.getProperties().containsKey("buffer_size")) { - s = this.getProperties().getProperty("buffer_size"); - if (s != null && !"".equals(s.trim())) { - bufferSize = (int) parseSize(s.trim()); - } - } - - if (bufferSize == 0) { - bufferSize = 1024 * 8; - } - - bufferPool = new Pool<>(() -> { - return new ChannelBuffer(bufferSize); - }, 8); - - //最大连接数 - s = this.getProperties().getProperty("max_connections"); - if (s != null && !"".equals(s.trim())) { - maxConnections = Integer.parseUnsignedInt(s.trim()); - } else { - maxConnections = 1024; - } - - //服务配置 - s = this.getProperties().getProperty("config_file"); - File cfile = new File(s); - if (!cfile.exists() || !cfile.isFile()) { - throw new FileNotFoundException("Configuration file not found:" + s); - } - - XmlHelper helper = XmlHelper.load(cfile.toString()); - Node node, attr, root = helper.selectNode("/configuration/http.service"); - - //获取机器配置 - machine = new WebApplicationStartupInfo(); - this.parseApplication(machine, helper, helper.selectNode(root, "machine")); - - //web应用的配置文件地址 - s = this.getProperties().getProperty("webapp.config_path"); - cfile = new File(s); - appInfos = new NameValueCollection<>(); - infos = new NameValueCollection<>(); - if (cfile.exists() && cfile.isDirectory()) { - cfile.listFiles((File child) -> { - if (child.getName().toLowerCase().endsWith(".xml")) { - try { - loadApp(child.toString(), false); - } catch (Throwable ex) { - logger.error(ex); - } - } - return false; - }); - } - - //mano服务器测试专用 - s = Mano.getProperty("manoserver.testing.test_webapp.config_file"); - try { - if (s != null && !"".equals(s)) { - loadApp(s, true); - } - } catch (Throwable ex) { - // - } - - //解析连接地址 - this.getProperties().entrySet().stream().forEach(item -> { - parseConns(item.getKey().toString(), item.getValue()); - }); - - } - - private void parseConns(String name, Object value) { - String[] arr = Utility.split(name, ":", true); - if (arr.length > 2) { - if ("connection".equalsIgnoreCase(arr[0])) { - ConnectionInfo info; - if (infos.containsKey(arr[1])) { - info = infos.get(arr[1]); - } else { - info = new ConnectionInfo(); - infos.put(arr[1], info); - } - - if ("address".equalsIgnoreCase(arr[2])) { - String addr = value == null ? "" : value.toString().trim(); - int index = addr.lastIndexOf(":"); - if (index < 0) { - return; - } - info.address = new InetSocketAddress(addr.substring(0, index), Integer.parseInt(addr.substring(index + 1))); - } else if ("disabled".equalsIgnoreCase(arr[2])) { - info.disabled = "true".equalsIgnoreCase(value == null ? "" : value.toString().trim()); - } - } - } - } - - private void loadApp(String filename, boolean setable) throws XmlException { - XmlHelper helper = null; - Node root = null; - NamedNodeMap attrs = null; - Node attr = null; - if (!setable) { - helper = XmlHelper.load(filename); - root = helper.selectNode("/application"); - if (root == null) { - return; - } - attrs = root.getAttributes(); - if (attrs == null) { - return; - } - attr = attrs.getNamedItem("path"); - if (attr == null) { - throw new XmlException("miss attribute [path]"); - } - } - - WebApplicationStartupInfo info = new WebApplicationStartupInfo(); - if (!setable) { - info.rootdir = attr.getNodeValue(); - } else { - info.rootdir = filename; - } - //info.service = this; - info.serviceLoader = loader; - info.modules.putAll(machine.modules); - info.settings.putAll(machine.settings); - info.exports.putAll(machine.exports); - info.documents.addAll(machine.documents); - info.ignoreds.addAll(machine.ignoreds); - info.action = machine.action; - info.controller = machine.controller; - info.disabledEntityBody = machine.disabledEntityBody; - info.maxEntityBodySize = machine.maxEntityBodySize; - info.serverPath = this.getProperties().getProperty("server.dir"); - String s; - if (!setable) { - NodeList nodes = helper.selectNodes(root, "dependency"); - if (nodes != null) { - Node node; - - for (int i = 0; i < nodes.getLength(); i++) { - node = nodes.item(i); - attr = node.getAttributes().getNamedItem("path"); - if (attr != null) { - s = attr.getNodeValue(); - if (s != null && !"".equals(s) && !info.dependencyExt.contains(s)) { - info.dependencyExt.add(s); - - } - } - } - } - } else { - //mano服务器测试专用 - s = Mano.getProperty("manoserver.testing.test_webapp.ext_dependency"); - try { - if (s != null && !"".equals(s)) { - info.dependencyExt.add(s); - } - } catch (Throwable ex) { - // - } - } - - File file = new File(info.rootdir + "/WEB-INF/mano.web.xml"); - if (!file.exists() || !file.getName().toLowerCase().endsWith(".xml")) { - throw new XmlException("Nonreadable file:" + file); - } - helper = XmlHelper.load(file.toString()); - root = helper.selectNode("/application"); - if (root == null) { - throw new XmlException("无效的应用配置文件"); - } - parseApplication(info, helper, root); - appInfos.put(info.host, info); - } - - private void parseApplication(WebApplicationStartupInfo info, XmlHelper helper, Node root) throws XmlException { - NamedNodeMap attrs; - String s; - NodeList nodes; - Node attr; - //base - attrs = root.getAttributes(); - attr = attrs.getNamedItem("name"); - if (attr != null) { - info.name = attr.getNodeValue(); - } - attr = attrs.getNamedItem("host"); - if (attr != null) { - info.host = attr.getNodeValue(); - } - attr = attrs.getNamedItem("class"); - if (attr != null) { - info.type = attr.getNodeValue(); - } - attr = attrs.getNamedItem("vpath"); - if (attr != null) { - info.path = attr.getNodeValue(); - } - - //配置 - nodes = helper.selectNodes(root, "settings/property"); - if (nodes != null) { - for (int i = 0; i < nodes.getLength(); i++) { - attrs = nodes.item(i).getAttributes(); - info.settings.setProperty(attrs.getNamedItem("name").getNodeValue(), nodes.item(i).getTextContent()); - } - } - - //request - Node node = helper.selectNode(root, "request"); - if (node != null) { - attrs = node.getAttributes(); - attr = attrs.getNamedItem("action"); - if (attr != null) { - info.action = attr.getNodeValue(); - } - attr = attrs.getNamedItem("controller"); - if (attr != null) { - info.controller = attr.getNodeValue(); - } - attr = attrs.getNamedItem("maxEntityBodySize"); - if (attr != null) { - info.maxEntityBodySize = this.parseSize(attr.getNodeValue().trim()); - } - attr = attrs.getNamedItem("maxEntityBodySize"); - if (attr != null) { - info.disabledEntityBody = Utility.cast(Boolean.class, attr.getNodeValue().trim()); - } - - //文档 - nodes = helper.selectNodes(node, "document/add"); - if (nodes != null) { - for (int i = 0; i < nodes.getLength(); i++) { - try { - attrs = nodes.item(i).getAttributes(); - attr = attrs.getNamedItem("value"); - s = attr == null ? "" : attr.getNodeValue().trim().toLowerCase(); - if ("".equals(s) || info.documents.contains(s)) { - continue; - } - info.documents.add(s); - } catch (Exception ignored) { - } - } - } - - //忽略 - nodes = helper.selectNodes(node, "ignored/add"); - if (nodes != null) { - for (int i = 0; i < nodes.getLength(); i++) { - try { - attrs = nodes.item(i).getAttributes(); - attr = attrs.getNamedItem("value"); - s = attr == null ? "" : attr.getNodeValue().trim().toLowerCase(); - if ("".equals(s) || info.ignoreds.contains(s)) { - continue; - } - info.ignoreds.add(s); - } catch (Exception ignored) { - } - } - } - } - - //依赖 - nodes = helper.selectNodes(root, "dependency/path"); - for (int i = 0; i < nodes.getLength(); i++) { - attrs = nodes.item(i).getAttributes(); - try { - s = attrs.getNamedItem("value").getNodeValue().trim(); - } catch (Exception ignored) { - s = ""; - } - if (!"".equals(s) && !info.dependency.contains(s)) { - info.dependency.add(s); - } - } - - //导出 - nodes = helper.selectNodes(root, "dependency/export"); - if (nodes != null) { - for (int i = 0; i < nodes.getLength(); i++) { - attrs = nodes.item(i).getAttributes(); - try { - info.exports.put(attrs.getNamedItem("name").getNodeValue().trim(), attrs.getNamedItem("class").getNodeValue().trim()); - } catch (Exception ex) { - logger.debug(ex); - } - } - } - - //模块 - HttpModuleSettings module; - nodes = helper.selectNodes(root, "modules/add");//remove clear - for (int i = 0; i < nodes.getLength(); i++) { - attrs = nodes.item(i).getAttributes(); - attr = attrs.getNamedItem("name"); - s = (attr == null) ? "" : attr.getNodeValue().trim(); - if ("".equals(s) || info.modules.containsKey(s)) { - logger.warn("module exists:" + s); - continue; - } - - module = new HttpModuleSettings(); - module.name = s; - module.type = attrs.getNamedItem("class").getNodeValue(); - NodeList params = helper.selectNodes(nodes.item(i), "property"); - for (int j = 0; j < params.getLength(); j++) { - attrs = params.item(j).getAttributes(); - module.settings.setProperty(attrs.getNamedItem("name").getNodeValue(), params.item(j).getTextContent()); - } - info.modules.put(s, module); - } - } - - @Override - public ChannelBuffer allocate() { - ChannelBuffer buffer = bufferPool.get(); - buffer.buffer.clear(); - return buffer; - } - - @Override - public void free(ChannelBuffer buffer) { - if (buffer == null || buffer.buffer.capacity() != bufferSize) { - return; - } - bufferPool.put(buffer); - } - - private class ConnectionInfo { - - public InetSocketAddress address; - public boolean disabled = false; - } - - - - - - public static void mainXXX(String[] args) throws Exception { - HttpService service=new HttpService(); - service.getProperties().setProperty("config_file", "E:\\repositories\\java\\mano\\mano-server-projects\\mano-server\\src\\resources\\conf\\server.xml"); - service.getProperties().setProperty("buffer_size", "8k"); - service.getProperties().setProperty("max_connections", "1024"); - service.getProperties().setProperty("webapp.config_path", ""); - service.getProperties().setProperty("max_connections", "1024"); - service.getProperties().setProperty("connection:http:address", "0.0.0.0:9999"); - service.getProperties().setProperty("connection:http:disabled", "false"); - service.init(); - service.run(); - Thread.sleep(1000 * 60 * 20); - } - -} diff --git a/del/mano-server-projects/open-tpl/demo/each.html b/del/mano-server-projects/open-tpl/demo/each.html deleted file mode 100644 index 64b85c2..0000000 --- a/del/mano-server-projects/open-tpl/demo/each.html +++ /dev/null @@ -1,5 +0,0 @@ -{{each:item list}} - {{item.name}} -{{else}} -no loop2 -{{/each}} \ No newline at end of file diff --git a/del/mano-server-projects/open-tpl/demo/for.html b/del/mano-server-projects/open-tpl/demo/for.html deleted file mode 100644 index 69e5f52..0000000 --- a/del/mano-server-projects/open-tpl/demo/for.html +++ /dev/null @@ -1,19 +0,0 @@ -{{for:i 5,2,1}} - {{i}} -{{/for}}sdd -{{for:i 10}} - {{i}} -{{/for}} -============== -{{for:i 2}} - {{for:j 2}} - {{i}}:{{j}} - {{/for}} -{{/for}} -============== -{{for:i 10}} - {{i}} - {{if i>=4}} - {{break}} - {{/if}} -{{/for}} \ No newline at end of file diff --git a/del/mano-server-projects/open-tpl/demo/func.html b/del/mano-server-projects/open-tpl/demo/func.html deleted file mode 100644 index 39ca6a8..0000000 --- a/del/mano-server-projects/open-tpl/demo/func.html +++ /dev/null @@ -1,2 +0,0 @@ -{{str('hello',' ','world')}} -{{substr('你好world',3)}} \ No newline at end of file diff --git a/del/mano-server-projects/open-tpl/demo/if.html b/del/mano-server-projects/open-tpl/demo/if.html deleted file mode 100644 index 708af83..0000000 --- a/del/mano-server-projects/open-tpl/demo/if.html +++ /dev/null @@ -1,25 +0,0 @@ -{{var:i 1}} -{{if i>10}} -A:val1 -{{/if}} -====================== -{{if i>10}} -B:val1 -{{else}} -B:val3 -{{/if}} -====================== -{{if i>10}} -C:val1 -{{elif i<2}} -C:val2 -{{/if}} -====================== -{{if i>10}} -D:val1 -{{elif i<2}} -D:val2 -{{else}} -D:val3 -{{/if}} -====================== \ No newline at end of file diff --git a/del/mano-server-projects/open-tpl/demo/master.html b/del/mano-server-projects/open-tpl/demo/master.html deleted file mode 100644 index 45bb1bc..0000000 --- a/del/mano-server-projects/open-tpl/demo/master.html +++ /dev/null @@ -1,27 +0,0 @@ - - - - - title - - - - - -
你好, {{name}}
- {{body}} - - - -我是正文。 - -abc -{{section:style}} -块内容。 -{{/section}} \ No newline at end of file diff --git a/del/mano-server-projects/open-tpl/demo/page.html b/del/mano-server-projects/open-tpl/demo/page.html deleted file mode 100644 index b336c90..0000000 --- a/del/mano-server-projects/open-tpl/demo/page.html +++ /dev/null @@ -1,3 +0,0 @@ -{{arr[1]}} -{{item['abc']}} -{{item2.inner['akl']}} \ No newline at end of file diff --git a/del/mano-server-projects/open-tpl/nb-configuration.xml b/del/mano-server-projects/open-tpl/nb-configuration.xml deleted file mode 100644 index 99bddf6..0000000 --- a/del/mano-server-projects/open-tpl/nb-configuration.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - ManoLicense - - diff --git a/del/mano-server-projects/open-tpl/pom.xml b/del/mano-server-projects/open-tpl/pom.xml deleted file mode 100644 index 4fbea01..0000000 --- a/del/mano-server-projects/open-tpl/pom.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - 4.0.0 - com.diosay - open-tpl - 1.0-SNAPSHOT - jar - Mano :: Open-TPL for Java - - - ${project.groupId} - mano - ${project.version} - - - - UTF-8 - 1.8 - 1.8 - - \ No newline at end of file diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/Block.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/Block.java deleted file mode 100644 index a922a99..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/Block.java +++ /dev/null @@ -1,177 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ -package com.diosay.otpl; - -import java.util.LinkedList; -import mano.InvalidOperationException; - -/** - * 表示一个块节点。 - * - * @author jun - */ -public class Block extends Node { - - /** - * 获取当前节点的所有子节点集合。 - */ - public final LinkedList children = new LinkedList<>(); - private boolean closed; - private Document dom; - private CharSequence source; - private int start; - private int end; - private int line; - private Compiler compiler; - private String name; - - public Block(Document dom, String name) { - this.name = name; - this.dom = dom; - } - - @Override - public final boolean isBlock() { - return true; - } - - @Override - public final boolean isText() { - return false; - } - - @Override - public boolean isDocument() { - return false; - } - - @Override - public String getName() { - return name; - } - - @Override - public int getNodeType() { - return Node.BLOCK; - } - private String[] closes; - - public void setCloseName(String... closes) { - this.closes = closes; - } - - /** - * 使用给定的节点确定是否可以关闭当前节点。 - * - * @param node - * @return - */ - protected boolean canClose(Node node) { - if (this.getName().equalsIgnoreCase(node.getName()) && node.isEndBlock()) { - return true; - } else if (closes != null) { - for (String s : closes) { - if (node.getName().equalsIgnoreCase(s)) { - return true; - } - } - } - return false; - } - - /** - * 向当前节点的dom树附加一个节点。 - * - * @param node - * @return - */ - public Block append(Node node) { - if (closed) { - throw new InvalidOperationException("block has been closed."); - } else if (canClose(node)) { - closed = true; - this.dom.current = this.getParent();//fix self-call - if (node.isEndBlock()) { - return this.getParent(); - } else { - - node.associate(getParent(), getParent().children.isEmpty() ? null : getParent().children.getLast()); - getParent().children.add(node); - if (node.isBlock()) { - //this.getParent().append(node); - return (Block) node; - } else { - return getParent(); - } - } - } - - node.associate(this, children.isEmpty() ? null : children.getLast()); - children.add(node); - if (node.isBlock()) { - //this.getParent().append(node); - return (Block) node; - } else { - return this; - } - } - - @Override - public Document getOwnerDocument() { - return dom; - } - - /** - * 设置编译器 - * - * @param compiler - */ - public void setCompiler(Compiler compiler) { - this.compiler = compiler; - } - - @Override - public Compiler getCompiler() { - return this.compiler; - } - - @Override - public final boolean isEndBlock() { - return false; - } - - /** - * 设置行号 - * - * @param line - */ - public void setLineNumber(int line) { - this.line = line; - } - - /** - * 设置源码 - * - * @param source - * @param start - * @param end - */ - public void setSource(CharSequence source, int start, int end) { - this.source = source.subSequence(start, end); - } - - @Override - public CharSequence getSource() { - return source; - } - - @Override - public int getLineNumber() { - return this.line; - } -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/CompileException.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/CompileException.java deleted file mode 100644 index f595c07..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/CompileException.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ - -package com.diosay.otpl; - -/** - * 编译异常。 - * @author jun - */ -public class CompileException extends RuntimeException { - public CompileException(){ - super(); - } - - public CompileException(String message) { - super(message); - } - - public CompileException(String message, Throwable cause) { - super(message, cause); - } - - public CompileException(Throwable cause) { - super(cause); - } -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/Compiler.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/Compiler.java deleted file mode 100644 index b0e0358..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/Compiler.java +++ /dev/null @@ -1,1179 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ -package com.diosay.otpl; - -import com.diosay.otpl.runtime.OpCode; -import com.diosay.otpl.runtime.OpcodeType; -import com.diosay.otpl.runtime.opcodes.*; -import java.util.ArrayList; -import java.util.UUID; - -/** - * 编译器 - * - * @author jun - */ -public abstract class Compiler { - - public static final ArrayList keywords = new ArrayList<>(); - - static { - - keywords.add("false"); - keywords.add("true"); - keywords.add("null"); - keywords.add("nil"); - keywords.add("this"); - keywords.add("str");//$otpl_func_str - } - - /** - * 是否是关键词 - * - * @param id - * @return - */ - public boolean isKeyword(String id) { - for (String s : keywords) { - if (s.equalsIgnoreCase(id)) { - return true; - } - } - return false; - } - - /** - * 生成一个随机名称。 - * - * @return - */ - public String randomName() { - return Integer.toHexString(UUID.randomUUID().hashCode()); - } - - /** - * 编译 - * - * @param node - */ - public abstract void compile(Node node, ArrayList list); - - /** - * 获取一个块结束节点的索引 - * - * @param list - * @param index - * @param start - * @param end - * @return - */ - protected int lastOf(ArrayList list, int index, int start, int end) { - - int ms = 1; - int result = -1; - for (int i = index; i < list.size(); i++) { - if (list.get(i).type == start) { - ms++; - } else if (list.get(i).type == end) { - ms--; - if (ms == 0) { - result = i; - return i; - } - } - } - return result; - } - - /** - * 语法分析 - * - * @param list - */ - protected void grammar(ArrayList list) { - Token token; - boolean done; - - //第1级:解决小括号(函数或块域)与中括号(索引)。 - do { - done = false; - for (int i = 0; i < list.size(); i++) { - if (list.get(i).type == Token.OP) { - token = new Token(); - token.line = list.get(i).line; - token.type = Token.BLK; - if (i > 0 && list.get(i - 1).type == Token.ID) { - token.code = "call-fn"; - } else { - token.code = "("; - } - int index = lastOf(list, i + 1, Token.OP, Token.CP); - if (index < 0) { - throw new mano.InvalidOperationException("括号不匹配"); - } - for (int j = i + 1; j < index; j++) { - token.add(list.get(j)); - } - list.add(i, token); - i++; - list.remove(i);//( - for (int j = 0; j < token.size(); j++) { - list.remove(i); - } - list.remove(i);//) - grammar(token); - done = true; - break; - } else if (list.get(i).type == Token.OB) { - token = new Token(); - token.line = list.get(i).line; - token.type = Token.BLK; - if (i > 0 && list.get(i - 1).type == Token.ID) { - token.code = "call-idx"; - } else { - token.code = "["; - } - int index = lastOf(list, i + 1, Token.OB, Token.CB); - if (index < 0) { - throw new mano.InvalidOperationException("括号不匹配"); - } - for (int j = i + 1; j < index; j++) { - token.add(list.get(j)); - } - list.add(i, token); - i++; - list.remove(i);//[ - for (int j = 0; j < token.size(); j++) { - list.remove(i); - } - list.remove(i);//] - grammar(token); - done = true; - break; - } - } - } while (done); - - //第3级:合并函数与索引。 - do { - done = false; - for (int i = 0; i < list.size(); i++) { - if (list.get(i).type == Token.BLK && list.get(i).code.equals("call-fn")) { - token = new Token(); - token.line = list.get(i).line; - token.type = Token.BLK; - token.code = "call"; - token.add(list.get(i - 1)); - token.add(list.get(i)); - token.get(1).code = "params"; //解决函数无限递归 - list.add(i - 1, token); - - for (int j = 0; j < token.size(); j++) { - list.remove(i); - } - grammar(token); - done = true; - break; - } else if (list.get(i).type == Token.BLK && list.get(i).code.equals("call-idx")) { - token = new Token(); - token.line = list.get(i).line; - token.type = Token.BLK; - token.code = "indexer"; - token.add(list.get(i - 1)); - token.add(list.get(i)); - token.get(1).code = "params"; //解决函数无限递归 - list.add(i - 1, token); - - for (int j = 0; j < token.size(); j++) { - list.remove(i); - } - grammar(token); - done = true; - break; - } - } - } while (done); - - //第2级:解决对象成员访问。 - do { - done = false; - for (int i = 0; i < list.size(); i++) { - if (list.get(i).type == Token.DOT) { - token = new Token(); - token.line = list.get(i).line; - token.type = Token.BLK; - token.code = "dot"; - token.add(list.get(i - 1)); - //token.children.add(list.get(i)); - token.add(list.get(i + 1)); - list.add(i - 1, token); - list.remove(i);//. - for (int j = 0; j < token.size(); j++) { - list.remove(i); - } - if (token.get(0).type == Token.LONG && token.get(1).type == Token.LONG) {//小数 - token.type = Token.REAL; - token.code = token.get(0).code.trim() + "." + token.get(1).code.trim(); - token.clear(); - } else if (token.get(0).type == Token.LONG || token.get(1).type == Token.LONG) { - throw new mano.InvalidOperationException("无效的属性名称。"); - } - grammar(token); - done = true; - break; - } - } - } while (done); - - //第4级:解决非、负运算。 - do { - done = false; - for (int i = 0; i < list.size(); i++) { - if (list.get(i).type == Token.EM) {//非 - token = new Token(); - token.line = list.get(i).line; - token.type = Token.BLK; - token.code = "opp"; - token.add(list.get(i + 1)); - list.add(i, token); - list.remove(i);//! - for (int j = 0; j < token.size(); j++) { - list.remove(i); - } - grammar(token); - done = true; - break; - } else if (list.get(i).type == Token.SUB) { - if (i - 1 >= 0 && !(list.get(i - 1).type == Token.ID || list.get(i - 1).type == Token.BLK)) { - - } else { - continue; - } - token = new Token(); - token.line = list.get(i).line; - token.type = Token.BLK; - token.code = "neg";//负 - token.add(list.get(i + 1)); - - list.remove(i);//- - for (int j = 0; j < token.size(); j++) { - list.remove(i); - } - list.add(i, token); - grammar(token); - done = true; - break; - } - } - } while (done); - - //第5级:解决乘、除、模运算。 - do { - done = false; - for (int i = 0; i < list.size(); i++) { - if (list.get(i).type == Token.MUL) { - token = new Token(); - token.line = list.get(i).line; - token.type = Token.BLK; - token.code = "mul"; - token.add(list.get(i - 1)); - token.add(list.get(i + 1)); - list.add(i - 1, token); - list.remove(i);//* - for (int j = 0; j < token.size(); j++) { - list.remove(i); - } - grammar(token); - done = true; - break; - } else if (list.get(i).type == Token.DIV) { - token = new Token(); - token.line = list.get(i).line; - token.type = Token.BLK; - token.code = "div"; - token.add(list.get(i - 1)); - token.add(list.get(i + 1)); - list.add(i - 1, token); - list.remove(i);/// - for (int j = 0; j < token.size(); j++) { - list.remove(i); - } - grammar(token); - done = true; - break; - } else if (list.get(i).type == Token.MOD) { - token = new Token(); - token.line = list.get(i).line; - token.type = Token.BLK; - token.code = "mod"; - token.add(list.get(i - 1)); - token.add(list.get(i + 1)); - list.add(i - 1, token); - list.remove(i);//% - for (int j = 0; j < token.size(); j++) { - list.remove(i); - } - grammar(token); - done = true; - break; - } - } - } while (done); - - //第6级:解决加、减运算。 - do { - done = false; - for (int i = 0; i < list.size(); i++) { - if (list.get(i).type == Token.ADD) { - token = new Token(); - token.line = list.get(i).line; - token.type = Token.BLK; - token.code = "add"; - token.add(list.get(i - 1)); - token.add(list.get(i + 1)); - list.add(i - 1, token); - list.remove(i);//+ - for (int j = 0; j < token.size(); j++) { - list.remove(i); - } - grammar(token); - done = true; - break; - } else if (list.get(i).type == Token.SUB) { - token = new Token(); - token.line = list.get(i).line; - token.type = Token.BLK; - token.code = "sub"; - token.add(list.get(i - 1)); - token.add(list.get(i + 1)); - list.add(i - 1, token); - list.remove(i);//- - for (int j = 0; j < token.size(); j++) { - list.remove(i); - } - grammar(token); - done = true; - break; - } - } - } while (done); - - //第7级:解决大于、大于等于、小于、小于等于运算。 - do { - done = false; - for (int i = 0; i < list.size(); i++) { - if (list.get(i).type == Token.GT) { - token = new Token(); - token.line = list.get(i).line; - token.type = Token.BLK; - token.code = "gt"; - token.add(list.get(i - 1)); - token.add(list.get(i + 1)); - list.add(i - 1, token); - list.remove(i);//+ - for (int j = 0; j < token.size(); j++) { - list.remove(i); - } - grammar(token); - done = true; - break; - } else if (list.get(i).type == Token.GTE) { - token = new Token(); - token.line = list.get(i).line; - token.type = Token.BLK; - token.code = "ge"; - token.add(list.get(i - 1)); - token.add(list.get(i + 1)); - list.add(i - 1, token); - list.remove(i);//- - for (int j = 0; j < token.size(); j++) { - list.remove(i); - } - grammar(token); - done = true; - break; - } else if (list.get(i).type == Token.LT) { - token = new Token(); - token.line = list.get(i).line; - token.type = Token.BLK; - token.code = "lt"; - token.add(list.get(i - 1)); - token.add(list.get(i + 1)); - list.add(i - 1, token); - list.remove(i);//- - for (int j = 0; j < token.size(); j++) { - list.remove(i); - } - grammar(token); - done = true; - break; - } else if (list.get(i).type == Token.LTE) { - token = new Token(); - token.line = list.get(i).line; - token.type = Token.BLK; - token.code = "le"; - token.add(list.get(i - 1)); - token.add(list.get(i + 1)); - list.add(i - 1, token); - list.remove(i);//- - for (int j = 0; j < token.size(); j++) { - list.remove(i); - } - grammar(token); - done = true; - break; - } - } - } while (done); - - //第8级:解决等于、不等于运算。 - do { - done = false; - for (int i = 0; i < list.size(); i++) { - if (list.get(i).type == Token.EQ) { - token = new Token(); - token.line = list.get(i).line; - token.type = Token.BLK; - token.code = "eq"; - token.add(list.get(i - 1)); - token.add(list.get(i + 1)); - list.add(i - 1, token); - list.remove(i);//+ - for (int j = 0; j < token.size(); j++) { - list.remove(i); - } - grammar(token); - done = true; - break; - } else if (list.get(i).type == Token.NEQ) { - token = new Token(); - token.line = list.get(i).line; - token.type = Token.BLK; - token.code = "ne"; - token.add(list.get(i - 1)); - token.add(list.get(i + 1)); - list.add(i - 1, token); - list.remove(i);//- - for (int j = 0; j < token.size(); j++) { - list.remove(i); - } - grammar(token); - done = true; - break; - } - } - } while (done); - - //第9级:解决与、或运算。 - do { - done = false; - for (int i = 0; i < list.size(); i++) { - if (list.get(i).type == Token.AND) { - token = new Token(); - token.line = list.get(i).line; - token.type = Token.BLK; - token.code = "and"; - token.add(list.get(i - 1)); - token.add(list.get(i + 1)); - list.add(i - 1, token); - list.remove(i);//+ - for (int j = 0; j < token.size(); j++) { - list.remove(i); - } - grammar(token); - done = true; - break; - } else if (list.get(i).type == Token.OR) { - token = new Token(); - token.line = list.get(i).line; - token.type = Token.BLK; - token.code = "or"; - token.add(list.get(i - 1)); - token.add(list.get(i + 1)); - list.add(i - 1, token); - list.remove(i);//- - for (int j = 0; j < token.size(); j++) { - list.remove(i); - } - grammar(token); - done = true; - break; - } - } - } while (done); - - //第10级:解决空、三目运算。 - do { - done = false; - for (int i = 0; i < list.size(); i++) { - if (list.get(i).type == Token.NC) { //?? - token = new Token(); - token.line = list.get(i).line; - token.type = Token.BLK; - token.code = "nc"; - token.add(list.get(i - 1)); - token.add(list.get(i + 1)); - list.add(i - 1, token); - list.remove(i);//?? - for (int j = 0; j < token.size(); j++) { - list.remove(i); - } - grammar(token); - done = true; - break; - } else if (list.get(i).type == Token.QM) { //? - token = new Token(); - token.line = list.get(i).line; - token.type = Token.BLK; - token.code = "qm"; - token.add(list.get(i - 1)); - token.add(list.get(i + 1)); - token.add(list.get(i + 3)); - list.add(i - 1, token); - list.remove(i);//? - list.remove(i);//: - for (int j = 0; j < token.size(); j++) { - list.remove(i); - } - grammar(token); - done = true; - break; - } - } - } while (done); - - //第11级:解决赋值运算。 - do { - done = false; - for (int i = 0; i < list.size(); i++) { - if (list.get(i).type == Token.ASSIGN) { - token = new Token(); - token.line = list.get(i).line; - token.type = Token.BLK; - token.code = "assign";//= - token.add(list.get(i - 1)); - token.add(list.get(i + 1)); - list.add(i - 1, token); - list.remove(i);//+ - for (int j = 0; j < token.size(); j++) { - list.remove(i); - } - grammar(token); - done = true; - break; - } - } - } while (done); - - //第12级:解决参数(列表)运算。 - do { - done = false; - for (int i = 0; i < list.size(); i++) { - if (list.get(i).type == Token.COMMA) { - if (i - 1 > -1 && list.get(i - 1).type == Token.BLK && "comma".equals(list.get(i - 1).code)) { - token = list.get(i - 1); - token.add(list.get(i + 1)); - list.remove(i); - list.remove(i); - grammar(token); - } else { - token = new Token(); - token.line = list.get(i).line; - token.type = Token.BLK; - token.code = "comma";//, - token.add(list.get(i - 1)); - token.add(list.get(i + 1)); - list.add(i - 1, token); - list.remove(i); - list.remove(i); - list.remove(i); - - grammar(token); - } - done = true; - break; - } - } - } while (done); - } - - /** - * 词法分析 - * - * @param source - * @param start - * @param end - * @return - */ - protected ArrayList scan(CharSequence source, int start, int end, int line) { - ArrayList list = new ArrayList<>(); - Token token; - char c; - int index; - String s = null; - for (; start < end && start < source.length() && start < end; start++) { - c = source.charAt(start); - if (StringUtil.isWhitespace(c)) {//空白 - continue; - } else if (StringUtil.isAlphanumeric(c) || '_' == c) {//字符串或数字标识 - if (StringUtil.isDigital(c) && (index = StringUtil.parseNumber(source, start, end)) > -1) { - token = new Token(); - token.type = Token.LONG; - token.code = source.subSequence(start, index).toString(); - token.line = line; - list.add(token); - start = index - 1; - } else if ((index = StringUtil.findIdentifier(source, start, end)) > -1) { - token = new Token(); - token.type = Token.ID; - token.code = source.subSequence(start, index).toString(); - token.line = line; - list.add(token); - start = index - 1; - } else { - throw new UnsupportedOperationException("非法字符 " + c + " ,col:" + start); - } - } else if ('(' == c) { - token = new Token(); - token.type = Token.OP; - token.line = line; - list.add(token); - } else if (')' == c) { - token = new Token(); - token.type = Token.CP; - token.line = line; - list.add(token); - } else if ('[' == c) { - token = new Token(); - token.type = Token.OB; - token.line = line; - list.add(token); - } else if (']' == c) { - token = new Token(); - token.type = Token.CB; - token.line = line; - list.add(token); - } else if ('+' == c) { - token = new Token(); - token.type = Token.ADD; - token.line = line; - list.add(token); - } else if ('-' == c) { - token = new Token(); - token.type = Token.SUB; - token.line = line; - list.add(token); - } else if ('*' == c) { - token = new Token(); - token.type = Token.MUL; - token.line = line; - list.add(token); - } else if ('/' == c) { - token = new Token(); - token.type = Token.DIV; - token.line = line; - list.add(token); - } else if ('%' == c) { - token = new Token(); - token.type = Token.MOD; - token.line = line; - list.add(token); - } else if ('.' == c) { - token = new Token(); - token.type = Token.DOT; - token.line = line; - list.add(token); - } else if (',' == c) { - token = new Token(); - token.type = Token.COMMA; - token.line = line; - list.add(token); - } else if (':' == c) { - token = new Token(); - token.type = Token.COLON; - token.line = line; - list.add(token); - } else if ('|' == c) { - token = new Token(); - if (source.charAt(start + 1) == '|') { //|| - token.type = Token.OR; - start++; - } else { - token.type = Token.VL; - } - token.line = line; - list.add(token); - } else if ('&' == c) { - token = new Token(); - if (start + 1 < end && source.charAt(start + 1) == '&') { //&& - token.type = Token.AND; - start++; - } else { - throw new UnsupportedOperationException("非法操作符 & 。"); - } - token.line = line; - list.add(token); - } else if ('=' == c) { - token = new Token(); - if (source.charAt(start + 1) == '=') { //== - token.type = Token.EQ; - start++; - } else { - token.type = Token.ASSIGN; - } - token.line = line; - list.add(token); - } else if ('?' == c) { - token = new Token(); - if (source.charAt(start + 1) == '?') { //++ - token.type = Token.NC; - start++; - } else { - token.type = Token.QM; - } - token.line = line; - list.add(token); - } else if ('!' == c) { - token = new Token(); - if (source.charAt(start + 1) == '=') { //!= - token.type = Token.NEQ; - start++; - } else { - token.type = Token.EM; - } - token.line = line; - list.add(token); - } else if ('>' == c) { - token = new Token(); - if (source.charAt(start + 1) == '=') { //++ - token.type = Token.GTE; - start++; - } else { - token.type = Token.GT; - } - token.line = line; - list.add(token); - } else if ('<' == c) { - token = new Token(); - if (source.charAt(start + 1) == '=') { //++ - token.type = Token.LTE; - start++; - } else { - token.type = Token.LT; - } - token.line = line; - list.add(token); - } else if ('=' == c) { - token = new Token(); - if (source.charAt(start + 1) == '=') { //++ - token.type = Token.EQ; - start++; - } else { - token.type = Token.ASSIGN; - } - token.line = line; - list.add(token); - } else if ('"' == c) { - if ((index = StringUtil.findString(source, start + 1, end)) < 0) { - throw new UnsupportedOperationException("非法字符"); - } - token = new Token(); - token.type = Token.STR; - token.code = source.subSequence(start + 1, index).toString(); - token.line = line; - list.add(token); - start = index; - } else if ('\'' == c) { - if ((index = StringUtil.findStringEx(source, start + 1, end)) < 0) { - throw new UnsupportedOperationException("非法字符"); - } - token = new Token(); - token.type = Token.STR; - token.code = source.subSequence(start + 1, index).toString(); - token.line = line; - list.add(token); - start = index; - } else { - throw new UnsupportedOperationException("非法字符:" + c); - } - } - return list; - } - - /** - * 获取参数个数 - * - * @param token - * @return - */ - static int getCount(Token token) { - if (token.type != Token.BLK) { - return 1; - } else if (token.code.equals("params")) { - //return 1; - } - else if (!token.code.equals("comma")) { - return 1; - } - // - int count = 0; - for (Token sub : token) { - if (sub.type == Token.BLK && sub.code.equals("comma")) { - count += getCount(sub); - } else { - count++; - } - } - return count; - } - - /** - * 访问语法树,并生成中间代码 - * - * @param token - */ - protected void visit(Token token, ArrayList list) { - switch (token.type) { - case Token.ID: { - if ("null".equalsIgnoreCase(token.code)) { - LoadConst code = new LoadConst(); - code.setValue(LoadConst.NULL); - list.add(code); - } else if ("false".equalsIgnoreCase(token.code)) { - LoadConst code = new LoadConst(); - code.setValue(LoadConst.FALSE); - list.add(code); - } else if ("true".equalsIgnoreCase(token.code)) { - LoadConst code = new LoadConst(); - code.setValue(LoadConst.TRUE); - list.add(code); - } else { - LoadVariable code = new LoadVariable(); - code.setName(token.code); - list.add(code); - } - break; - } - case Token.LONG: { - LoadLong code = new LoadLong(); - code.setValue(Long.parseLong(token.code)); - list.add(code); - break; - } - case Token.REAL: { - LoadReal code = new LoadReal(); - code.setValue(Double.parseDouble(token.code)); - list.add(code); - break; - } - case Token.STR: { - LoadString code = new LoadString(); - code.setContent(token.code); - list.add(code); - break; - } - case Token.BLK: - final String b = token.code; - switch (b) { - case "dot"://成员 - visit(token.get(0), list); - - System.out.println("->");//neg - - if (token.get(1).type == Token.BLK && "call".equals(token.get(1).code)) { - if (token.get(1).get(0).type == Token.ID) { - int len = getCount(token.get(1).get(1)); - list.add(new Peek()); //peek - list.add(new LoadMember().setName(token.get(1).get(0).code).setArgLength(len));//ldm - visit(token.get(1).get(1), list); - list.add(new Call().setArgLength(len)); - } else { - visit(token.get(1), list); - } - } else if (token.get(1).type == Token.BLK && "indexer".equals(token.get(1).code)) { - if (token.get(1).get(0).type == Token.ID) { - int len = getCount(token.get(1).get(1)); - visit(token.get(1).get(1), list); - list.add(new Callvri().setName("indexer").setArgLength(len + 1)); - } else { - visit(token.get(1), list); - } - } else if (token.get(1).type == Token.ID) { - list.add(new Peek()); //peek - list.add(new LoadMember().setName(token.get(1).code).setArgLength(0));//ldm - list.add(new Call().setArgLength(0)); - } else { - visit(token.get(1), list); - } - break; - case "neg"://负数 - visit(token.get(0), list); - list.add(new Operator().setOperator(Operator.NEG)); - break; - case "call"://调用 - if (token.get(0).type != Token.ID) { - throw new UnsupportedOperationException("语法错误"); - } - visit(token.get(1), list);//参数 - list.add(new Callvri().setName(token.get(0).code).setArgLength(getCount(token.get(1).get(0)))); - break; - case "indexer"://索引 - if (token.get(0).type != Token.ID) { - throw new UnsupportedOperationException("语法错误"); - } - int len = getCount(token.get(1)); - visit(token.get(1), list);//参数 - //array - //obj list.add(new LoadMember().setName(token.get(0).code).setArgLength(len)); - list.add(new LoadVariable().setName(token.get(0).code)); - list.add(new Callvri().setName("indexer").setArgLength(len + 1)); - - break; - case "add": { - visit(token.get(0), list); - visit(token.get(1), list); - Operator code = new Operator(); - code.setOperator(Operator.ADD); - list.add(code); - break; - } - case "sub": { - visit(token.get(0), list); - visit(token.get(1), list); - Operator code = new Operator(); - code.setOperator(Operator.SUB); - list.add(code); - break; - } - case "mul": { - visit(token.get(0), list); - visit(token.get(1), list); - Operator code = new Operator(); - code.setOperator(Operator.MUL); - list.add(code); - break; - } - case "div": { - visit(token.get(0), list); - visit(token.get(1), list); - Operator code = new Operator(); - code.setOperator(Operator.DIV); - list.add(code); - break; - } - case "mod": { - visit(token.get(0), list); - visit(token.get(1), list); - Operator code = new Operator(); - code.setOperator(Operator.MOD); - list.add(code); - break; - } - case "and": {//&& - //Nop case1 = new Nop(); - Nop case2 = new Nop(); - visit(token.get(0), list); - list.add(new Peek()); - list.add(new LoadConst().setValue(LoadConst.TRUE)); - list.add(new Operator().setOperator(Operator.EQ));//? !=null - list.add(OpCode.makeBreakFalse(case2));//if false then left - visit(token.get(1), list); - //Operator code = new Operator(); - //code.setOperator(Operator.AND); - list.add(new Operator().setOperator(Operator.AND)); - list.add(case2); - break; - } - case "or": {//|| - //Nop case1 = new Nop(); - Nop case2 = new Nop(); - visit(token.get(0), list); - list.add(new Peek()); - list.add(new LoadConst().setValue(LoadConst.TRUE)); - list.add(new Operator().setOperator(Operator.EQ));//? !=null - list.add(OpCode.makeBreakTrue(case2));//if false then left - visit(token.get(1), list); - //Operator code = new Operator(); - //code.setOperator(Operator.OR); - //list.add(code); - list.add(new Operator().setOperator(Operator.OR)); - list.add(case2); - break; - } - case "eq": {//== - visit(token.get(0), list); - visit(token.get(1), list); - Operator code = new Operator(); - code.setOperator(Operator.EQ); - list.add(code); - break; - } - case "ne": {//!= - visit(token.get(0), list); - visit(token.get(1), list); - Operator code = new Operator(); - code.setOperator(Operator.NE); - list.add(code); - break; - } - case "gt": {//> - visit(token.get(0), list); - visit(token.get(1), list); - Operator code = new Operator(); - code.setOperator(Operator.GT); - list.add(code); - break; - } - case "ge": {//>= - visit(token.get(0), list); - visit(token.get(1), list); - Operator code = new Operator(); - code.setOperator(Operator.GE); - list.add(code); - break; - } - case "lt": {//< - visit(token.get(0), list); - visit(token.get(1), list); - Operator code = new Operator(); - code.setOperator(Operator.LT); - list.add(code); - break; - } - case "le": {//<= - visit(token.get(0), list); - visit(token.get(1), list); - Operator code = new Operator(); - code.setOperator(Operator.LE); - list.add(code); - break; - } - case "nc": {//?? - Nop case1 = new Nop(); - Nop case2 = new Nop(); - visit(token.get(0), list); - list.add(new Peek()); - list.add(new LoadNull()); - list.add(new Operator().setOperator(Operator.NE));//? !=null - list.add(OpCode.makeBreakFalse(case1));//if false then left - list.add(OpCode.makeBreak(case2)); - list.add(case1); - visit(token.get(1), list); - list.add(case2); - break; - } - case "qm": {//?: - Nop case1 = new Nop(); - Nop case2 = new Nop(); - visit(token.get(0), list); - list.add(OpCode.makeBreakFalse(case1));//if false then left - visit(token.get(1), list); - list.add(OpCode.makeBreak(case2)); - list.add(case1); - visit(token.get(2), list); - list.add(case2); - break; - } - default: - for (Token sub : token) { - visit(sub, list); - } - } - break; - default: - throw new UnsupportedOperationException("语法错误 " + token.type + " " + token.code); - } - } - - /** - * 编译源码 - * - * @param source - * @param list - */ - protected int compile(CharSequence source, ArrayList list, int line) { - ArrayList tokens = this.scan(source, 0, source.length(), line); - this.grammar(tokens); - for (Token sub : tokens) { - this.visit(sub, list); - } - return tokens.size(); - } - - protected void adjustFor(ArrayList list, int start, int end) { - int tmp; - OpCode code; - BreakDescriptor brk; - for (; start < end; start++) { - code = list.get(start); - if (code.getType().equals(OpcodeType.nop) && "for".equals(code.tag)) { //loop - tmp = findMark(list, code, start + 1, end); - if (tmp < 0) { - throw new mano.InvalidOperationException("for 未结束"); - } - adjustFor(list, start + 1, tmp);//嵌套 - for (int i = start + 1; i <= tmp; i++) { - if (!(list.get(i) instanceof BreakDescriptor)) { - continue; - } - brk = (BreakDescriptor) list.get(i); - if (brk.target != null) { - //nothing - } else if (brk.blocked) { - brk.target = list.get(tmp); - } else { - brk.target = code; - } - } - start = tmp; - } - } - } - - protected void adjustEach(ArrayList list, int start, int end) { - int tmp; - OpCode code; - BreakDescriptor brk; - for (; start < end; start++) { - code = list.get(start); - if (code.getType().equals(OpcodeType.nop) && "each".equals(code.tag)) { //loop - tmp = findMark(list, code, start + 1, end); - if (tmp < 0) { - throw new mano.InvalidOperationException("each 未结束"); - } - adjustEach(list, start + 1, tmp);//嵌套 - for (int i = start + 1; i <= tmp; i++) { - if (!(list.get(i) instanceof BreakDescriptor)) { - continue; - } - brk = (BreakDescriptor) list.get(i); - if (brk.target != null) { - //nothing - } else if (brk.blocked) { - brk.target = list.get(tmp); - } else { - brk.target = code; - } - } - start = tmp; - } - } - } - - int findMark(ArrayList list, OpCode in, int start, int end) { - int tmp; - OpCode code; - for (; start < list.size(); start++) { - code = list.get(start); - if (in.tag.equals(code.tag) && in.mark.equals(code.mark)) { - return start; - } - } - return -1; - } -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/Document.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/Document.java deleted file mode 100644 index 6d75508..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/Document.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ -package com.diosay.otpl; - -import java.util.ArrayList; -import java.util.HashMap; - -/** - * 表示一个文档 - * - * @author jun - */ -public class Document extends Block { - - Block current; - public Node layout; - public Node body; - public ArrayList blocks; - private Compiler compiler; - private String file; - - public Document(Compiler compiler, String filename) { - super(null, "dom"); - this.compiler = compiler; - this.file = filename; - this.current = this; - this.blocks = new ArrayList<>(); - } - - @Override - public Block append(Node node) { - if ("layout".equalsIgnoreCase(node.getName())) { - if (layout != null) { - throw new mano.InvalidOperationException("layout 标签在行 " + layout.getLineNumber() + " 已经定义,不能重复定义。"); - } - layout = node; - } else if ("body".equalsIgnoreCase(node.getName())) { - if (body != null) { - throw new mano.InvalidOperationException("body 标签在行 " + body.getLineNumber() + " 已经定义,不能重复定义。"); - } - body = node; - if (current != this) { - current = current.append(node); - } else { - current = super.append(node); - } - } else if ("section".equalsIgnoreCase(node.getName())) { - if (!node.isEndBlock()) { - if (current.isBlock() && "section".equalsIgnoreCase(current.getName())) { - throw new mano.InvalidOperationException("section 标签不支持嵌套。"); - } - node.associate(this, blocks.isEmpty() ? null : blocks.get(blocks.size() - 1)); - blocks.add(node); - current = (Block) node; - } else { - current = current.append(node); - } - } else { - if (current != this) { - current = current.append(node); - } else { - current = super.append(node); - } - } - return current; - } - - @Override - protected final boolean canClose(Node node) { - return false; - } - - @Override - public final Compiler getCompiler() { - return compiler; - } - - @Override - public final Document getOwnerDocument() { - return null; - } - - @Override - public final boolean isDocument() { - return true; - } - - /** - * 获取源文件的全限定名称。 - * - * @return - */ - public final String getSourceFile() { - return file; - } - - /** - * 创建一个块结束节点。 - * - * @param name - * @return - */ - public EndBlock createEndBlock(String name, int line) { - return new EndBlock(this, name, line); - } - - /** - * 创建一个块节点。 - * - * @param name - * @return - */ - public Block createBlock(String name) { - return new Block(this, name); - } - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/EndBlock.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/EndBlock.java deleted file mode 100644 index 36566b0..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/EndBlock.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ -package com.diosay.otpl; - -import com.diosay.otpl.runtime.OpCode; -import java.util.ArrayList; - -/** - * 表示一个块的结束。 - * - * @author jun - */ -public class EndBlock extends Node { - - private String name; - private Document dom; - private int line; - - protected EndBlock() { - } - - EndBlock(Document dom, String name, int line) { - this.dom = dom; - this.name = name; - this.line = line; - } - - @Override - public boolean isBlock() { - return false; - } - - @Override - public boolean isText() { - return false; - } - - @Override - public boolean isDocument() { - return false; - } - - @Override - public final boolean isEndBlock() { - return true; - } - - @Override - public String getName() { - return this.name; - } - - @Override - public final int getNodeType() { - return Node.END_BLOCK; - } - - @Override - public Document getOwnerDocument() { - return dom; - } - - @Override - public Compiler getCompiler() { - return dc; - } - static cc dc = new cc(); - - static class cc extends com.diosay.otpl.Compiler { - - @Override - public void compile(Node node, ArrayList list) { - System.out.println("WARNING: 结束标签不应该被编译。name:" + node != null ? node.getName() : ""); - } - - } - - @Override - public int getLineNumber() { - return line; - } - - @Override - public CharSequence getSource() { - return ""; - } -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/Lexer.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/Lexer.java deleted file mode 100644 index a4f191e..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/Lexer.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ -package com.diosay.otpl; - -/** - * 表示一个语法词条。 - * - * @author jun - */ -public interface Lexer { - - /** - * 获取标识 - * - * @return - */ - String getToken(); - - /** - * 是否是块语法 - * - * @return - */ - boolean isBlock(); - - /** - * 解析 - * - * @param source - * @param start - * @param end - * @param line - */ - void parse(Document dom,CharSequence source, int start, int end, int line); - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/Node.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/Node.java deleted file mode 100644 index c859303..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/Node.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ -package com.diosay.otpl; -//http://msdn.microsoft.com/zh-cn/library/system.xml.xmlnode(v=vs.110).aspx - -/** - * 表示 OTPL 文档中的单个节点。 - * - * @author jun - */ -public abstract class Node { - - public static final int UNDEFINED = 0; - /** - * 作为文档树的根的文档对象提供对整个 OTPL 文档的访问。 - */ - public static final int DOCUMENT = 1; - /** - * 表示一个独立的节点,它不能含有子节点。 - */ - public static final int SPAN = 2; - /** - * 表示一个块节点,它必须使用一对{node}{/node} 来指示完整的块。 - */ - public static final int BLOCK = 3; - /** - * 表示文本节点。 它是一个特殊的 SPAN 节点,唯一不同是因为它不能被语法解析。 - */ - public static final int TEXT = 4; - - /** - * 表示块节点的结束。 - */ - public static final int END_BLOCK = 5; - - private Block parent; - private Node prev; - private Node next; - - /** - * 获取一个值,以指示当前节点是否是块结点。 - * - * @return - */ - public abstract boolean isBlock(); - - /** - * 获取一个值,以指示当前节点是否是文本结点。 - * - * @return - */ - public abstract boolean isText(); - - /** - * 获取一个值,以指示当前文档的根类型。 - * - * @return - */ - public abstract boolean isDocument(); - - /** - * 获取一个值,以指示当前文档的根类型。 - * - * @return - */ - public abstract boolean isEndBlock(); - - /** - * 获取当前节点的名称。 - * - * @return - */ - public abstract String getName(); - - /** - * 获取当前节点的类型。 - * - * @return - */ - public abstract int getNodeType(); - - /** - * 获取该节点(对于可以具有父级的节点)的父级。 - * - * @return - */ - public Block getParent() { - return parent; - } - - /** - * 获取紧接在该节点之后的节点。 - * - * @return - */ - public final Node getNext() { - return next; - } - - /** - * 获取紧接在该节点之前的节点。 - * - * @return - */ - public final Node getPrev() { - return prev; - } - - /** - * 获取所属的文档。 - * - * @return - */ - public abstract Document getOwnerDocument(); - - /** - * 获取编译器 - * - * @return - */ - public abstract Compiler getCompiler(); - - /** - * 关联节点。 - *

- * 注意:该方法只应在append方法中调用。 - * - * @param parent 父级 - * @param prev 上个节点 - */ - public final void associate(Block parent, Node prev) { - this.parent = parent; - this.prev = prev; - if (prev != null) { - prev.next = this; - } - } - - /** - * 获取行号 - * @return - */ - public abstract int getLineNumber(); - - /** - * 获取未解析的源码 - * @return - */ - public abstract CharSequence getSource(); - - /** - * 一个临时标记 - */ - public boolean marked; -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/Parser.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/Parser.java deleted file mode 100644 index abc9141..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/Parser.java +++ /dev/null @@ -1,388 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ -package com.diosay.otpl; - -import com.diosay.otpl.lexers.BodyLexer; -import com.diosay.otpl.lexers.BreakLexer; -import com.diosay.otpl.lexers.ContinueLexer; -import com.diosay.otpl.lexers.EachLexer; -import com.diosay.otpl.lexers.ElifLexer; -import com.diosay.otpl.lexers.ElseLexer; -import com.diosay.otpl.lexers.ForLexer; -import com.diosay.otpl.lexers.IfLexer; -import com.diosay.otpl.lexers.IncludeLexer; -import com.diosay.otpl.lexers.LayoutLexer; -import com.diosay.otpl.lexers.PlaceLexer; -import com.diosay.otpl.lexers.PrintLexer; -import com.diosay.otpl.lexers.SectionLexer; -import com.diosay.otpl.lexers.TextLexer; -import com.diosay.otpl.lexers.VariableLexer; -import com.diosay.otpl.runtime.OpCode; -import com.diosay.otpl.runtime.opcodes.*; -import java.io.BufferedReader; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.ArrayList; -import java.util.HashMap; - -/** - * 实现OTPL解析器与DOM编译器 - * - * @author jun - */ -public class Parser extends Compiler { - - int line; - Document document; - boolean inLiteral = false; - boolean inComment = false; - - /** - * 打开文件,并尝试移除UTF BOM。 - * - * @param file - * @return - * @throws FileNotFoundException - * @throws IOException - */ - public static BufferedReader open(String file) throws FileNotFoundException, IOException { - FileInputStream input = new FileInputStream(file); - String encoding = "UTF-8"; - byte bom[] = new byte[4]; - - int removed; - try { - input.read(bom, 0, bom.length); - } catch (Throwable ex) { - //ignored - } - - if ((bom[0] == (byte) 0x00) && (bom[1] == (byte) 0x00) - && (bom[2] == (byte) 0xFE) && (bom[3] == (byte) 0xFF)) { - encoding = "UTF-32BE"; - removed = 4; - } else if ((bom[0] == (byte) 0xFF) && (bom[1] == (byte) 0xFE) - && (bom[2] == (byte) 0x00) && (bom[3] == (byte) 0x00)) { - encoding = "UTF-32LE"; - removed = 4; - } else if ((bom[0] == (byte) 0xEF) && (bom[1] == (byte) 0xBB) - && (bom[2] == (byte) 0xBF)) { - encoding = "UTF-8"; - removed = 3; - } else if ((bom[0] == (byte) 0xFE) && (bom[1] == (byte) 0xFF)) { - encoding = "UTF-16BE"; - removed = 2; - } else if ((bom[0] == (byte) 0xFF) && (bom[1] == (byte) 0xFE)) { - encoding = "UTF-16LE"; - removed = 2; - } else { - removed = 0; - } - input.close(); - input = new FileInputStream(file); - if (removed > 0) { - input.read(bom, 0, removed); - } - return new BufferedReader(new InputStreamReader(input, encoding)); - } - - /** - * 解析一个OTPL流,并构建一个 Document。 - * - * @param input 输入流。 - * @param basedir 用于查找源文件的根目录。 - * @param encoding 用于解析源文件的编码。 - * @param sourceFile 全限定路径源文件,可空。 - * @return - */ - public static Document parsexxxxx(BufferedReader reader, String basedir, String sourceFile) throws Exception { - - String line; - StringBuilder sb; - Parser parser = new Parser(); - parser.line = 0; //reset - parser.document = new Document(parser, sourceFile); - parser.regsisterLexer(new IfLexer()); - int index; - int end; - int[] arr; - while ((line = reader.readLine()) != null) { - parser.line++; - sb = new StringBuilder(line); - sb.append('\r').append('\n'); - end = sb.length(); - index = 0; - - do { - - if ((arr = StringUtil.findSegment(sb, "{{", "}}", index, end)) != null) { - - } else if ((arr = StringUtil.findSegment(sb, "", index, end)) != null) { - - } else { - break; - } - - if (arr[0] - index - 2 != 0) { - parser.onText(sb, index, arr[0] - 2); - } - parser.onMarkup(sb, arr[0], arr[1]); - index = arr[1] + 2; - - } while (true); - - if (index < end) { - parser.onText(sb, index, end); - } - } - return null; - } - - /** - * 解析一个OTPL流,并构建一个 Document。 - * - * @param input 输入流。 - * @param basedir 用于查找源文件的根目录。 - * @param encoding 用于解析源文件的编码。 - * @param sourceFile 全限定路径源文件,可空。 - * @return - */ - public Document parse(BufferedReader reader, String sourceFile) throws Exception { - - String line; - StringBuilder sb; - this.line = 0; //reset - this.document = new Document(this, sourceFile); - this.regsisterLexer(new IfLexer()); - this.regsisterLexer(new ElifLexer()); - this.regsisterLexer(new ElseLexer()); - this.regsisterLexer(new EachLexer()); - this.regsisterLexer(new PrintLexer()); - this.regsisterLexer(new TextLexer()); - this.regsisterLexer(new BodyLexer()); - this.regsisterLexer(new LayoutLexer()); - this.regsisterLexer(new SectionLexer()); - this.regsisterLexer(new PlaceLexer()); - this.regsisterLexer(new ForLexer()); - this.regsisterLexer(new VariableLexer()); - this.regsisterLexer(new BreakLexer()); - this.regsisterLexer(new ContinueLexer()); - this.regsisterLexer(new IncludeLexer()); - int index; - int end; - int[] arr; - while ((line = reader.readLine()) != null) { - this.line++; - sb = new StringBuilder(line); - sb.append('\r').append('\n'); - end = sb.length(); - index = 0; - - do { - - if ((arr = StringUtil.findSegment(sb, "{{", "}}", index, end)) != null) { - boolean lft = false; - boolean rgt = false; - int tmp = 0; - int tmp2 = 0; - for (int i = arr[0] - 3; i >= index; i--) { - if (StringUtil.isWhitespace(sb.charAt(i))) { - continue; - } else if (i - 3 >= index && sb.charAt(i - 3) == '<' && sb.charAt(i - 2) == '!' && sb.charAt(i - 1) == '-' && sb.charAt(i) == '-') { - // - rgt = true; - tmp2 = i + 2; - - for (; tmp2 < end; tmp2++) { - if (!(StringUtil.isWhitespace(sb.charAt(tmp2)) || sb.charAt(tmp2) == '\r' || sb.charAt(tmp2) == '\n')) { - break; - } - } - break; - } else { - break; - } - } - } - - if (lft && rgt) { - if (tmp - index > 0) { - this.onText(sb, index, tmp); - } - this.onMarkup(sb, arr[0], arr[1]); - index = tmp2 + 1; - } else { - if (arr[0] - index - 2 != 0) { - this.onText(sb, index, arr[0] - 2); - } - this.onMarkup(sb, arr[0], arr[1]); - index = arr[1] + 2; - } - } else { - break; - } - - } while (true); - - if (index < end) { - this.onText(sb, index, end); - } - } - return this.document; - } - - /** - * 当发现文本时。 - */ - protected void onText(CharSequence source, int start, int end) { - if(inComment){ - return; - } - Text text = new Text(this.document, this.line); - text.setCompiler((Compiler) lexers.get("text")); - text.setSource(source, start, end); - this.document.append(text); - //System.out.println(source.subSequence(index, end).toString()); - } - - protected void reportError(String msg) { - throw new mano.InvalidOperationException("行 " + this.line + " 有语法错误:" + msg); - } - - /** - * 注册一个词条。 - */ - public void regsisterLexer(Lexer lexer) { - lexers.put(lexer.getToken(), lexer); - } - - private HashMap lexers = new HashMap<>(); - - /** - * 当解析到标记时。 - */ - protected void onMarkup(CharSequence source, int start, int end) { - start = StringUtil.trimLeftWhitespace(source, start, end);//移除开始的线性空白 - int tmp; - if ((tmp = StringUtil.findKeyword(source, "/literal", start, end)) != -1 - && !StringUtil.isAlphanumeric(source, tmp + 1, end)) { //原样输出结束 - if (!inComment) { - if (!inLiteral) { - reportError("错误的原样结束标签"); - inLiteral = true; //修正错误继续解析 - } - inLiteral = false; - } - - } else if (inLiteral) { - this.onText(source, start - 2, end + 2); - } else if ((tmp = StringUtil.findKeyword(source, "*/", start, end)) != -1) { //块注释结束 - this.inComment = false; - } else if ((tmp = StringUtil.findKeyword(source, "/*", start, end)) != -1) {//块注释开始 - this.inComment = true; - } else if (inComment || (tmp = StringUtil.findKeyword(source, "//", start, end)) != -1) { //当前为注释中 - //ignored - } else if ((tmp = StringUtil.findKeyword(source, "literal", start, end)) != -1 - && !StringUtil.isAlphanumeric(source, tmp + 1, end)) { //原样输出开始 - inLiteral = true; - } else { - final int tmpstart = start; - final int tmpend = end; - if (!lexers.values().stream().anyMatch(lexer -> { - if (!lexer.isBlock()) { - return false; - } - int tmp2; - if ((tmp2 = StringUtil.findKeyword(source, "/" + lexer.getToken(), tmpstart, tmpend)) != -1 - && StringUtil.isEnd(source, tmp2 + 1, tmpend)) { - document.append(document.createEndBlock(source.subSequence(tmpstart + 1, tmp2).toString(), line)); - //System.out.println("find end=====" + source.subSequence(tmpstart, tmp2)); - return true; - } - return false; - })) { - tmp = StringUtil.findIdentifier(source, start, end); - if (tmp != -1 && this.tryLex(source.subSequence(start, tmp).toString(), source, tmp, end)) { - //nothing - } else { //打印 - Lexer lexer = lexers.get("print"); - if (lexer == null) { - reportError("print 词条未定义"); - } - lexer.parse(document, source, start, end, line); - //System.out.println(source.subSequence(start, end)); - } - } - } - } - - protected boolean tryLex(String token, CharSequence source, int start, int end) { - if (lexers.values().stream().anyMatch(lexer -> { - - if (!lexer.getToken().equalsIgnoreCase(token)) { - return false; - } - lexer.parse(document, source, start, end, line); - return true; - })) { - return true; - } - //reportError("词条 " + token + " 未定义"); - //System.out.println("TOKEN====" + token); - return false; - } - - /** - * 编译dom - * - * @param node - * @param list - */ - @Override - public void compile(Node node, ArrayList list) { - - Document dom = (Document) node; - - //TODO - for (Node sub : dom.blocks) { - sub.getCompiler().compile(sub, list); - } - - list.add(new EndHeader()); - - if (dom.layout != null) { - dom.layout.getCompiler().compile(dom.layout, list); - } - - for (Node sub : dom.children) { - sub.getCompiler().compile(sub, list); - } - } -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/Span.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/Span.java deleted file mode 100644 index 07af675..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/Span.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ -package com.diosay.otpl; - -/** - * 表示一个单节点。 - * - * @author jun - */ -public class Span extends Node { - - private String name; - - public Span(String name) { - this.name = name; - } - - @Override - public final boolean isBlock() { - return false; - } - - @Override - public final boolean isText() { - return false; - } - - @Override - public final boolean isDocument() { - return false; - } - - @Override - public final boolean isEndBlock() { - return false; - } - - @Override - public String getName() { - return this.name; - } - - @Override - public int getNodeType() { - return Node.SPAN; - } - - @Override - public Document getOwnerDocument() { - return dom; - } - - @Override - public Compiler getCompiler() { - return compiler; - } - - private Compiler compiler; - private Document dom; - private CharSequence source; - private int start; - private int end; - private int line; - - /** - * 设置编译器 - * - * @param compiler - */ - public void setCompiler(Compiler compiler) { - this.compiler = compiler; - } - - /** - * 设置行号 - * - * @param line - */ - public void setLineNumber(int line) { - this.line = line; - } - - /** - * 设置源码 - * - * @param source - * @param start - * @param end - */ - public void setSource(CharSequence source, int start, int end) { - for (; start < end && start < source.length(); start++) { - if (!StringUtil.isWhitespace(source.charAt(start))) { - break; - } - } - this.source = source.subSequence(start, end); - } - - @Override - public int getLineNumber() { - return this.line; - } - - @Override - public CharSequence getSource() { - return this.source; - } - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/StringUtil.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/StringUtil.java deleted file mode 100644 index 3f82b0c..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/StringUtil.java +++ /dev/null @@ -1,333 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ -package com.diosay.otpl; - -/** - * 字符串工具类。 - * - * @author jun - */ -public class StringUtil { - - /** - * 判断是否是数字。 - * - * @param c - * @return - */ - public static boolean isDigital(char c) { - return (c >= 48 && c <= 57); - } - - /** - * 判断是否是字母 - * - * @param c - * @return - */ - public static boolean isLetter(char c) { - return (c >= 65 && c <= 90 || c >= 97 && c <= 122); - } - - /** - * 判断是否是字母或数字 - * - * @param c - * @return - */ - public static boolean isAlphanumeric(char c) { - return isDigital(c) || isLetter(c); - } - - /** - * 判断索引处是否是字母或数字。 - * - * @param source - * @param start - * @param end - * @return - */ - public static boolean isAlphanumeric(CharSequence source, int start, int end) { - if (start >= end || start >= source.length()) { - return false; - } - return isAlphanumeric(source.charAt(start)); - } - - /** - * 是否是空白字符 - * - * @param c - * @return - */ - public static boolean isWhitespace(char c) { - return (c == ' ' || c == '\t'); - } - - /** - * 是否是空白字符 - * - * @param c - * @return - */ - public static int trimLeftWhitespace(CharSequence source, int start, int end) { - if (source == null || start < 0 || start >= end || start >= source.length()) {//标准 - return start; - } - for (; start < end && start < source.length(); start++) { - if (!isWhitespace(source.charAt(start))) { - return start; - } - } - return start; - } - - public static int findIdentifier(CharSequence source, int start, int end) { - if (source == null || start < 0 || start > source.length() || !isLetter(source.charAt(start))) { - return -1; - } - int ori = start; - for (; start < end && start < source.length(); start++) { - if (!isAlphanumeric(source.charAt(start))) { - break; - } - } - return ori == start ? -1 : start; - } - - public static int parseNumber(CharSequence source, int start, int end) { - if (source == null || start < 0 || start > source.length()) { - return -1; - } - int ori = start; - for (; start < end && start < source.length(); start++) { - if (!isDigital(source.charAt(start))) { - //bounds - break; - } - } - return ori == start ? -1 : start; - } - - /** - * 查找双引号字符串 - * - * @param source - * @param start - * @param end - * @return - */ - public static int findString(CharSequence source, int start, int end) { - if (source == null || start < 0 || start > source.length()) { - return -1; - } - - for (; start < end && start < source.length(); start++) { - if ('\\' == source.charAt(start) && start + 1 < end && '"' == source.charAt(start + 1)) { - - } else if ('"' == source.charAt(start)) { - return start; - } - } - return -1; - } - - /** - * 查找单引号字符串 - * - * @param source - * @param start - * @param end - * @return - */ - public static int findStringEx(CharSequence source, int start, int end) { - if (source == null || start < 0 || start > source.length()) { - return -1; - } - - for (; start < end && start < source.length(); start++) { - if ('\\' == source.charAt(start) && start + 1 < end && '\'' == source.charAt(start + 1)) { - - } else if ('\'' == source.charAt(start)) { - return start; - } - } - return -1; - } - - /** - * 查找一个片段。 - * - * @param source - * @param left - * @param right - * @param start - * @param end - * @param ignores 主要用途是忽略内部字符串。 - * @return 成功返回结束的索引对,否则返回 null. - */ - public static int[] findSegment(CharSequence source, CharSequence left, CharSequence right, int start, int end) { - - if (source == null || left == null || right == null || start < 0 || end < 0 || end - start > source.length() || left.length() == 0 || right.length() == 0) { - return null; - } - boolean like = left.equals(right); - int index = -1; - int matches = 0; - for (; start < end && start < source.length(); start++) { - if (source.charAt(start) == '\\') {//转义 - start++; - } else if (!like && source.charAt(start) == left.charAt(0)) {//确定开始 - boolean tmp = true; - for (int i = 0; i < left.length(); i++) { - if (i + start > end || source.charAt(start + i) != left.charAt(i)) { - tmp = false; - break; - } - } - if (tmp) { - if (index == -1) { - index = start + left.length(); - } - start += left.length(); - matches++; - } - } else if (source.charAt(start) == right.charAt(0)) {//确定结束 - boolean tmp = true; - for (int i = 0; i < right.length(); i++) { - if (i + start > end || source.charAt(start + i) != right.charAt(i)) { - tmp = false; - break; - } - } - if (tmp) { - if (like && index == -1) { - index = start + left.length(); - } - matches--; - if (index > 0 && matches == 0) { - return new int[]{index, start}; - } - start += right.length(); - } - } - } - - return null; - } - - /** - * 查找子字符序列的首次出现位置。 - * - * @param source - * @param sub - * @param start - * @param end - * @param ignores - * @return 成功返回结束的索引,否则返回 -1. - */ - public static int indexOf(CharSequence source, CharSequence sub, int start, int end, char... ignores) { - if (source == null || sub == null || start < 0 || end < 0 || end - start > source.length() || sub.length() == 0) { - return -1; - } - char c; - boolean tmp; - for (; start < end && start < source.length(); start++) { - c = source.charAt(start); - - if (ignores != null) { - tmp = false; - for (int k = 0; k < ignores.length; k++) {//避免字符复制 - if (ignores[k] == c) { - tmp = true; - break; - } - } - if (tmp) { - continue; - } - } - if ('\\' == c) { - //nothing - } else if (sub.charAt(0) == c) { - tmp = true; - for (int k = 1; k < sub.length(); k++) { - if (k + start > end || source.charAt(start + k) != sub.charAt(k)) { - tmp = false; - break; - } - } - if (tmp) { - return start; - } - } - } - return -1; - } - - public boolean inCharArray(char c, char... array) { - if (array == null) { - return false; - } - for (int k = 0; k < array.length; k++) { - if (array[k] == c) { - return true; - } - } - return false; - } - - /** - * 判断start是否是索引的结束。 - * - * @param c - * @return - */ - public static boolean isEnd(CharSequence source, int start, int end) { - if (start >= end || start >= source.length()) { - return true; - } - return false; - } - - public static int findKeyword(CharSequence source, CharSequence key, int index, int end) { - if (key == null || key.length() == 0 || source == null || source.length() == 0) { - return -1; - } - boolean tmp = false; - for (; index < end && index < source.length(); index++) { //移除空白字符 - if (!isWhitespace(source.charAt(index))) { - break; - } - } - - for (; index < end && index < source.length(); index++) { - if (source.charAt(index) == key.charAt(0)) { - tmp = true; - for (int i = 0; i < key.length(); i++) { - if (index + i >= end || source.charAt(index + i) != key.charAt(i)) { - tmp = false; - break; - } - } - if (tmp) { - break; - } else { - index++; - } - } else { - return -1; - } - } - if (tmp) { - return index + key.length(); - } - return -1; - } - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/Text.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/Text.java deleted file mode 100644 index ca51627..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/Text.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ - -package com.diosay.otpl; - -/** - * 纯文本。 - * @author jun - */ -public class Text extends Node { - - public Text(Document dom,int line){ - this.dom=dom; - this.line=line; - } - - @Override - public boolean isBlock() { - return false; - } - - @Override - public boolean isText() { - return true; - } - - @Override - public boolean isDocument() { - return false; - } - - @Override - public boolean isEndBlock() { - return false; - } - - @Override - public String getName() { - return "text"; - } - - @Override - public int getNodeType() { - return Node.TEXT; - } - - @Override - public Document getOwnerDocument() { - return dom; - } - - @Override - public Compiler getCompiler() { - return compiler; - } - private Compiler compiler; - private Document dom; - private CharSequence source; - private int start; - private int end; - private int line; - /** - * 设置编译器 - * - * @param compiler - */ - public void setCompiler(Compiler compiler) { - this.compiler=compiler; - } - /** - * 设置行号 - * @param line - */ - public void setLineNumber(int line){ - this.line=line; - } - /** - * 设置源码 - * @param source - * @param start - * @param end - */ - public void setSource(CharSequence source, int start, int end){ - this.source=source.subSequence(start, end); - } - - @Override - public int getLineNumber() { - return this.line; - } - - @Override - public CharSequence getSource() { - return this.source; - } -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/Token.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/Token.java deleted file mode 100644 index daecb12..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/Token.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ - -package com.diosay.otpl; - -import java.util.ArrayList; - -/** - * 表示一个词法元素。 - * @author jun - */ -public class Token extends ArrayList{ - - public static final int ID = 1; - public static final int REAL = 2; - public static final int LONG = 3; - public static final int STR = 4; - public static final int BLK = 5; - - public static final int MUL = 6; // * - public static final int DIV = 7; // / - public static final int MOD = 8; // % - - public static final int ADD = 9; // + - public static final int SUB = 10; // - - - public static final int ASSIGN = 11; // = - - public static final int OR = 12; // || - public static final int AND = 13; // && - - public static final int GT = 14; // > - public static final int GTE = 15; // >= - public static final int LT = 16; // < - public static final int LTE = 17; // <= - - public static final int EQ = 18; // == - public static final int NEQ = 19; // != - - public static final int QM = 20; // ? - public static final int DOT = 21; // . - public static final int COMMA = 22; // , - public static final int COLON = 23; // : - public static final int EM = 24; // ! - public static final int NC = 25; // ?? - - - public static final int OP = 26; // ( - public static final int CP = 27; // ) - public static final int OB = 28; // [ - public static final int CB = 29; // ] - - public static final int VL = 31; // | - - - public int type; - public String code; - public int line; - //public ArrayList children = new ArrayList<>(); - - @Override - public String toString(){ - return super.toString()+" type="+type+" code="+code; - } -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/BodyLexer.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/BodyLexer.java deleted file mode 100644 index 8e09782..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/BodyLexer.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ - -package com.diosay.otpl.lexers; - -import com.diosay.otpl.Document; -import com.diosay.otpl.Lexer; -import com.diosay.otpl.Node; -import com.diosay.otpl.Span; -import com.diosay.otpl.runtime.OpCode; -import com.diosay.otpl.runtime.opcodes.Body; -import com.diosay.otpl.runtime.opcodes.Layout; -import java.util.ArrayList; - -/** - * - * @author jun - */ -public class BodyLexer extends com.diosay.otpl.Compiler implements Lexer{ - - @Override - public void compile(Node node, ArrayList list) { - //清理参数 - Body code = new Body(); - list.add(code); - } - - @Override - public String getToken() { - return "body"; - } - - @Override - public boolean isBlock() { - return false; - } - - @Override - public void parse(Document dom, CharSequence source, int start, int end, int line) { - Span node=new Span(this.getToken()); - node.setCompiler(this); - node.setLineNumber(line); - - node.setSource("", 0, 0); - - dom.append(node); - - } - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/BreakLexer.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/BreakLexer.java deleted file mode 100644 index bea9d0e..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/BreakLexer.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ -package com.diosay.otpl.lexers; - -import com.diosay.otpl.Document; -import com.diosay.otpl.Lexer; -import com.diosay.otpl.Node; -import com.diosay.otpl.Span; -import com.diosay.otpl.runtime.OpCode; -import com.diosay.otpl.runtime.opcodes.BreakDescriptor; -import java.util.ArrayList; - -/** - * 中断语句 - * - * @author jun - */ -public class BreakLexer extends com.diosay.otpl.Compiler implements Lexer { - - @Override - public void compile(Node node, ArrayList list) { - BreakDescriptor code=new BreakDescriptor(); - code.blocked=true; - list.add(code); - } - - @Override - public String getToken() { - return "break"; - } - - @Override - public boolean isBlock() { - return false; - } - - @Override - public void parse(Document dom, CharSequence source, int start, int end, int line) { - Span node = new Span(this.getToken()); - node.setCompiler(this); - node.setLineNumber(line); - node.setSource("", 0, 0); - dom.append(node); - } - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/ContinueLexer.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/ContinueLexer.java deleted file mode 100644 index 41bb9e1..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/ContinueLexer.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ - -package com.diosay.otpl.lexers; - -import com.diosay.otpl.Document; -import com.diosay.otpl.Lexer; -import com.diosay.otpl.Node; -import com.diosay.otpl.Span; -import com.diosay.otpl.runtime.OpCode; -import com.diosay.otpl.runtime.opcodes.BreakDescriptor; -import java.util.ArrayList; - -/** - * 中断语句 - * @author jun - */ -public class ContinueLexer extends com.diosay.otpl.Compiler implements Lexer { - - @Override - public void compile(Node node, ArrayList list) { - list.add(new BreakDescriptor()); - } - - @Override - public String getToken() { - return "continue"; - } - - @Override - public boolean isBlock() { - return false; - } - - @Override - public void parse(Document dom, CharSequence source, int start, int end, int line) { - Span node = new Span(this.getToken()); - node.setCompiler(this); - node.setLineNumber(line); - node.setSource("", 0, 0); - dom.append(node); - } - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/EachLexer.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/EachLexer.java deleted file mode 100644 index c24d2c1..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/EachLexer.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ -package com.diosay.otpl.lexers; - -import com.diosay.otpl.Block; -import com.diosay.otpl.Document; -import com.diosay.otpl.Lexer; -import com.diosay.otpl.Node; -import com.diosay.otpl.StringUtil; -import com.diosay.otpl.Token; -import com.diosay.otpl.runtime.OpCode; -import com.diosay.otpl.runtime.opcodes.Callvri; -import com.diosay.otpl.runtime.opcodes.LoadVariable; -import com.diosay.otpl.runtime.opcodes.SetVariable; -import com.diosay.otpl.runtime.opcodes.SourceLineNumber; -import java.util.ArrayList; - -/** - * 列出集合元素 - * - * @author jun - */ -public class EachLexer extends com.diosay.otpl.Compiler implements Lexer { - - @Override - public void compile(Node node, ArrayList rlist) { - // - /* - for(Object item:list){ - break - } - - loadItear - stv n - ldv n - callvri hsnext - brf ELSE - BEGIN - ldv n - callvri current - stv item - ... - ldv n - callvri hsnext - brf RET - br BEGIN - ELSE - ... - RET - - - */ - // - - CharSequence source = node.getSource(); - - if (source == null) { - throw new UnsupportedOperationException("语法错误:未设置名称"); - } - int index = 0; - index = StringUtil.trimLeftWhitespace(source, index, source.length()); - - if (index tokens = this.scan(source, index2, source.length(), node.getLineNumber()); - this.grammar(tokens); - if (tokens.size() != 1) { - throw new UnsupportedOperationException("语法错误:each语句参数错误。"); - } - rlist.add(new SourceLineNumber().setValue(node.getLineNumber())); - - for (Token sub : tokens) { - this.visit(sub, rlist); - } - ArrayList list = new ArrayList<>(); - OpCode lbElse = OpCode.label(); - OpCode begin = OpCode.label(); - OpCode ret = OpCode.label(); - begin.tag = "each"; - begin.mark = randomName(); - ret.tag = begin.tag; - ret.mark = begin.mark; - - SetVariable coll = new SetVariable().setName(randomName()); - //SetVariable var = new SetVariable().setName(name); - list.add(new Callvri().setName("iterator").setArgLength(1)); - list.add(coll); - list.add(new LoadVariable().setName(coll.getName())); - list.add(new Callvri().setName("iterator$hasNext").setArgLength(1)); - list.add(OpCode.makeBreakFalse(lbElse)); - list.add(begin); - list.add(new LoadVariable().setName(coll.getName())); - list.add(new Callvri().setName("iterator$next").setArgLength(1)); - list.add(new SetVariable().setName(name)); - ((Block) node).children.stream().forEach((sub) -> { - sub.getCompiler().compile(sub, list); - }); - list.add(new LoadVariable().setName(coll.getName())); - list.add(new Callvri().setName("iterator$hasNext").setArgLength(1)); - list.add(OpCode.makeBreakFalse(ret)); - list.add(OpCode.makeBreak(begin)); - list.add(lbElse); - //else - Node next = node.getNext();//is null - if (next != null && "else".equals(next.getName())) { - next.marked = true; - ((Block) next).children.stream().forEach((sub) -> { - sub.getCompiler().compile(sub, list); - }); - list.add(OpCode.makeBreak(ret)); - } - list.add(ret); - this.adjustEach(list, 0, list.size()); - rlist.addAll(list); - } - - @Override - public String getToken() { - return "each"; - } - - @Override - public boolean isBlock() { - return true; - } - - @Override - public void parse(Document dom, CharSequence source, int start, int end, int line) { - Block node = dom.createBlock(this.getToken()); - node.setCompiler(this); - node.setSource(source, start, end); - node.setLineNumber(line); - node.setCloseName("else"); - dom.append(node); - } - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/ElifLexer.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/ElifLexer.java deleted file mode 100644 index f85bc12..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/ElifLexer.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ -package com.diosay.otpl.lexers; - -import com.diosay.otpl.Block; -import com.diosay.otpl.Document; -import com.diosay.otpl.Lexer; -import com.diosay.otpl.Node; -import com.diosay.otpl.runtime.OpCode; -import java.util.ArrayList; - -/** - * 例外条件 - * - * @author jun - */ -public class ElifLexer extends com.diosay.otpl.Compiler implements Lexer { - - @Override - public void compile(Node node, ArrayList list) { - //nothing - } - - @Override - public String getToken() { - return "elif"; - } - - @Override - public boolean isBlock() { - return true; - } - - @Override - public void parse(Document dom, CharSequence source, int start, int end, int line) { - Block node = dom.createBlock(this.getToken()); - node.setCompiler(this); - node.setSource(source, start, end); - node.setLineNumber(line); - node.setCloseName("if", "else","elif"); - dom.append(node); - } - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/ElseLexer.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/ElseLexer.java deleted file mode 100644 index 11305ac..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/ElseLexer.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ -package com.diosay.otpl.lexers; - -import com.diosay.otpl.Block; -import com.diosay.otpl.Document; -import com.diosay.otpl.Lexer; -import com.diosay.otpl.Node; -import com.diosay.otpl.runtime.OpCode; -import java.util.ArrayList; - -/** - * 条件例外 - * @author jun - */ -public class ElseLexer extends com.diosay.otpl.Compiler implements Lexer { - - @Override - public void compile(Node node, ArrayList list) { - //nothing - } - - @Override - public String getToken() { - return "else"; - } - - @Override - public boolean isBlock() { - return true; - } - - @Override - public void parse(Document dom, CharSequence source, int start, int end, int line) { - Block node = dom.createBlock(this.getToken()); - node.setCompiler(this); - node.setSource(source, start, end); - node.setLineNumber(line); - node.setCloseName("if","elif","for","each"); - dom.append(node); - } - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/ForLexer.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/ForLexer.java deleted file mode 100644 index f9472a1..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/ForLexer.java +++ /dev/null @@ -1,254 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ -package com.diosay.otpl.lexers; - -import com.diosay.otpl.Block; -import com.diosay.otpl.Document; -import com.diosay.otpl.Lexer; -import com.diosay.otpl.Node; -import com.diosay.otpl.StringUtil; -import com.diosay.otpl.Token; -import com.diosay.otpl.runtime.OpCode; -import com.diosay.otpl.runtime.opcodes.*; -import java.util.ArrayList; - -/** - * for循环 - * - * @author jun - */ -public class ForLexer extends com.diosay.otpl.Compiler implements Lexer { - - @Override - public void compile(Node node, ArrayList rlist) { - if(node.marked){ - return; - } - - // - /* - for(int i=0;i<10;i++){ - break - } - - ldu 10 - ldu 0 - ldu 1 - - stv max - stv i - stv step - - //stackmax 4 - ldv i - ldv max - ldu 0 - ldv step - lt - brf DOWN - lt - brf ELSE - br BEGIN - DOWN - gt - brf ELSE - BEGIN - - ldv i - ldv max - ldu 0 - ldv step - lt - brf DOWN - lt - brf END - br RUN - DOWN - gt - brf RETURN - RUN - ... - - ldv i - ldv step - add - br BEGIN - ELSE - ... - END - - */ - // - CharSequence source = node.getSource(); - - if (source == null) { - throw new UnsupportedOperationException("语法错误:未设置名称"); - } - int index = 0; - index = StringUtil.trimLeftWhitespace(source, index, source.length()); - - if (source.charAt(index) != ':') { - throw new UnsupportedOperationException("语法错误:未知字符"); - } - index++; - int index2 = StringUtil.findIdentifier(source, index, source.length()); - - if (index2 < 0) { - throw new UnsupportedOperationException("语法错误:未设置名称"); - } - String name = source.subSequence(index, index2).toString(); - - if (this.isKeyword(name)) { - throw new UnsupportedOperationException("语法错误:变量名不能是关键词:" + name); - } - ArrayList tokens = this.scan(source, index2, source.length(), node.getLineNumber()); - this.grammar(tokens); - if(tokens.size()!=1){ - throw new UnsupportedOperationException("语法错误:for语句参数错误。"); - } - if(tokens.get(0).size()==0){ - Token token=new Token(); - token.code=","; - token.type=Token.COMMA; - tokens.add(token); - - token=new Token(); - token.code="0"; - token.type=Token.LONG; - tokens.add(token); - - token=new Token(); - token.code=","; - token.type=Token.COMMA; - tokens.add(token); - - token=new Token(); - token.code="1"; - token.type=Token.LONG; - tokens.add(token); - this.grammar(tokens); - }else if(tokens.get(0).size()==2){ - Token token=new Token(); - token.code=","; - token.type=Token.COMMA; - tokens.add(token); - - token=new Token(); - token.code="1"; - token.type=Token.LONG; - tokens.add(token); - this.grammar(tokens); - }else if(tokens.get(0).size()==3){ - - }else{ - throw new UnsupportedOperationException("语法错误:for语句参数错误。"); - } - for (Token sub : tokens) { - this.visit(sub, rlist); - } - - rlist.add(new SourceLineNumber().setValue(node.getLineNumber())); - - ArrayList list=new ArrayList<>(); - - //设置变量 - SetVariable max = new SetVariable().setName(randomName()); //stvar max - SetVariable var = new SetVariable().setName(name); //stvar i - SetVariable step = new SetVariable().setName(randomName()); //stvar step - list.add(step); - list.add(var); - list.add(max); - - - //定义标签 - OpCode begin = OpCode.label(); - begin.tag="for"; - begin.mark=randomName(); - OpCode end = OpCode.label(); - end.tag=begin.tag; - end.mark=begin.mark; - OpCode lbElse = OpCode.label(); - OpCode lbDown = OpCode.label(); - OpCode lbDown2 = OpCode.label(); - //获取变量 - list.add(new LoadVariable().setName(var.getName()));//ldv i - list.add(new LoadVariable().setName(max.getName()));//ldv max - list.add(new LoadVariable().setName(step.getName()));//ldv step - list.add(new LoadLong().setValue(0));//ldr 0 - - list.add(new Operator().setOperator(Operator.LE));//lt - list.add(OpCode.makeBreakTrue(lbDown));//brf DOWN - list.add(new Operator().setOperator(Operator.LE));//lt - list.add(OpCode.makeBreakFalse(lbElse));//brf ELSE - list.add(OpCode.makeBreak(begin));//br BEGIN - list.add(lbDown); - list.add(new Operator().setOperator(Operator.GT));//gt - list.add(OpCode.makeBreakFalse(lbElse));//brf ELSE - list.add(begin); - //body - for(Node sub:((Block)node).children){ - sub.getCompiler().compile(sub, list); - } - //加 - list.add(new LoadVariable().setName(var.getName()));//ldv i - list.add(new LoadVariable().setName(step.getName()));//ldv step - list.add(new Operator().setOperator(Operator.ADD));//add - list.add(new SetVariable().setName(var.getName()));//stv i - //获取变量 - list.add(new LoadVariable().setName(var.getName()));//ldv i - list.add(new LoadVariable().setName(max.getName()));//ldv max - list.add(new LoadVariable().setName(step.getName()));//ldv step - list.add(new LoadLong().setValue(0));//ldr 0 - - list.add(new Operator().setOperator(Operator.LE));//lt - list.add(OpCode.makeBreakTrue(lbDown));//brf DOWN - list.add(new Operator().setOperator(Operator.LE));//lt - list.add(OpCode.makeBreakFalse(end));//brf END - list.add(OpCode.makeBreak(begin));//br BEGIN - list.add(lbDown2); - list.add(new Operator().setOperator(Operator.GT));//gt - list.add(OpCode.makeBreakFalse(end));//brf ELSE - list.add(OpCode.makeBreak(begin));//br BEGIN - list.add(lbElse); - - //else - Node next=node.getNext();//is null - if(next!=null && next.getName().equals("else")){ - next.marked=true; - next.getCompiler().compile(next, list); - } - - list.add(end); - - this.adjustFor(list, 0, list.size()); - - rlist.addAll(list); - - } - - @Override - public String getToken() { - return "for"; - } - - @Override - public boolean isBlock() { - return true; - } - - @Override - public void parse(Document dom, CharSequence source, int start, int end, int line) { - Block node = dom.createBlock(this.getToken()); - node.setCloseName("else"); - node.setCompiler(this); - node.setLineNumber(line); - node.setSource(source, start, end); - dom.append(node); - } - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/IfLexer.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/IfLexer.java deleted file mode 100644 index 6a810e9..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/IfLexer.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ -package com.diosay.otpl.lexers; - -import com.diosay.otpl.Block; -import com.diosay.otpl.CompileException; -import com.diosay.otpl.Compiler; -import com.diosay.otpl.Document; -import com.diosay.otpl.Lexer; -import com.diosay.otpl.Node; -import com.diosay.otpl.runtime.OpCode; -import java.util.ArrayList; - -/** - * 解析与编译if语句 - * - * @author jun - */ -public class IfLexer extends Compiler implements Lexer { - - @Override - public String getToken() { - return "if"; - } - - @Override - public boolean isBlock() { - return true; - } - - @Override - public void parse(Document dom, CharSequence source, int start, int end, int line) { - if (start >= end) { - return; - } - Block node = dom.createBlock(this.getToken()); - node.setCompiler(this); - node.setSource(source, start, end); - node.setLineNumber(line); - node.setCloseName("elif", "else"); - dom.append(node); - } - - @Override - public void compile(Node node, ArrayList list) { - - // - /* - if(3<2){ - - } - - ldu 3 - ldu 2 - lt - brf RET - ... - RET - - */ - // - if (node == null || !node.isBlock() || !this.getToken().equalsIgnoreCase(node.getName())) { - throw new IllegalArgumentException("node"); - } - - OpCode lbElse = OpCode.label(); - OpCode ret = OpCode.label(); - this.compile(node.getSource(), list, node.getLineNumber()); - list.add(OpCode.makeBreakFalse(lbElse)); - - ((Block) node).children.stream().forEach((sub) -> { - sub.getCompiler().compile(sub, list); - }); - list.add(OpCode.makeBreak(ret)); - list.add(lbElse); - do { - Node next = node.getNext(); - if (next == null) { - break; - } else if ("elif".equals(next.getName())) { - - if (!("if".equals(next.getPrev().getName()) || "elif".equals(next.getPrev().getName()))) { - throw new CompileException("语法错误"); - } - OpCode lbElse2 = OpCode.label(); - this.compile(next.getSource(), list, next.getLineNumber()); - list.add(OpCode.makeBreakFalse(lbElse2)); - ((Block) next).children.stream().forEach((sub) -> { - sub.getCompiler().compile(sub, list); - }); - list.add(OpCode.makeBreak(ret)); - list.add(lbElse2); - } else if ("else".equals(next.getName())) { - if (!("if".equals(next.getPrev().getName()) || "elif".equals(next.getPrev().getName()))) { - throw new CompileException("语法错误"); - } - ((Block) next).children.stream().forEach((sub) -> { - sub.getCompiler().compile(sub, list); - }); - list.add(OpCode.makeBreak(ret)); - } else { - break; - } - next.marked = true; - node = next; - } while (true); - list.add(ret); - } -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/IncludeLexer.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/IncludeLexer.java deleted file mode 100644 index 147e614..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/IncludeLexer.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Project. All rights reserved. - * - * See more http://mano.diosay.com/ - * - */ -package com.diosay.otpl.lexers; - -import com.diosay.otpl.Document; -import com.diosay.otpl.Lexer; -import com.diosay.otpl.Node; -import com.diosay.otpl.Span; -import com.diosay.otpl.runtime.OpCode; -import com.diosay.otpl.runtime.opcodes.Include; -import com.diosay.otpl.runtime.opcodes.Layout; -import java.util.ArrayList; - -/** - * 包含 - * - * @author junhwong - */ -public class IncludeLexer extends com.diosay.otpl.Compiler implements Lexer { - - @Override - public void compile(Node node, ArrayList list) { - int size = list.size(); - this.compile(node.getSource(), list, node.getLineNumber()); - if (list.size() == size) { - throw new mano.InvalidOperationException("未设置布局文件名称."); - } - Include code = new Include(); - list.add(code); - } - - @Override - public String getToken() { - return "include"; - } - - @Override - public boolean isBlock() { - return false; - } - - @Override - public void parse(Document dom, CharSequence source, int start, int end, int line) { - Span node = new Span(this.getToken()); - node.setCompiler(this); - node.setLineNumber(line); - node.setSource(source, start, end); - dom.append(node); - } - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/LayoutLexer.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/LayoutLexer.java deleted file mode 100644 index 01f48b2..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/LayoutLexer.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ - -package com.diosay.otpl.lexers; - -import com.diosay.otpl.Document; -import com.diosay.otpl.Lexer; -import com.diosay.otpl.Node; -import com.diosay.otpl.Span; -import com.diosay.otpl.runtime.OpCode; -import com.diosay.otpl.runtime.OpcodeType; -import com.diosay.otpl.runtime.opcodes.Layout; -import com.diosay.otpl.runtime.opcodes.Print; -import java.util.ArrayList; - -/** - * 布局 - * @author jun - */ -public class LayoutLexer extends com.diosay.otpl.Compiler implements Lexer{ - - @Override - public void compile(Node node, ArrayList list) { - int size=list.size(); - this.compile(node.getSource(), list,node.getLineNumber()); - if(list.size()==size){ - throw new mano.InvalidOperationException("未设置布局文件名称."); - } - Layout code = new Layout(); - list.add(code); - } - - @Override - public String getToken() { - return "layout"; - } - - @Override - public boolean isBlock() { - return false; - } - - @Override - public void parse(Document dom, CharSequence source, int start, int end, int line) { - Span node=new Span(this.getToken()); - node.setCompiler(this); - node.setLineNumber(line); - node.setSource(source, start, end); - dom.append(node); - - } - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/PlaceLexer.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/PlaceLexer.java deleted file mode 100644 index afc97bc..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/PlaceLexer.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ -package com.diosay.otpl.lexers; - -import com.diosay.otpl.Document; -import com.diosay.otpl.Lexer; -import com.diosay.otpl.Node; -import com.diosay.otpl.Span; -import com.diosay.otpl.StringUtil; -import com.diosay.otpl.runtime.OpCode; -import com.diosay.otpl.runtime.opcodes.CallBlock; -import java.util.ArrayList; - -/** - * - * @author jun - */ -public class PlaceLexer extends com.diosay.otpl.Compiler implements Lexer { - - @Override - public void compile(Node node, ArrayList list) { - CharSequence source = node.getSource(); - - if (source == null) { - throw new UnsupportedOperationException("语法错误:未设置名称"); - } - int index = 0; - index = StringUtil.trimLeftWhitespace(source, index, source.length()); - - if (source.charAt(index) != ':') { - throw new UnsupportedOperationException("语法错误:未知字符"); - } - index++; - int index2 = StringUtil.findIdentifier(source, index, source.length()); - - if (index2 < 0) { - throw new UnsupportedOperationException("语法错误:未设置名称"); - } - String name = source.subSequence(index, index2).toString(); - CallBlock cb=new CallBlock(); - cb.setName(name); - index = StringUtil.trimLeftWhitespace(source, index2, source.length()); - if (index < source.length()) { - - index2 = StringUtil.findIdentifier(source, index, source.length()); - if (index2 < 0) { - throw new UnsupportedOperationException("语法错误:未知字符2"); - } - String id = source.subSequence(index, index2).toString(); - if("true".equalsIgnoreCase(id) || "t".equalsIgnoreCase(id)){ - cb.required(true); - }else if("false".equalsIgnoreCase(id) || "f".equalsIgnoreCase(id)){ - cb.required(true); - } - else{ - throw new UnsupportedOperationException("语法错误:不能识别的标识符:"+id); - } - } - index = StringUtil.trimLeftWhitespace(source, index2, source.length()); - if (index != source.length()) { - throw new UnsupportedOperationException("语法错误:未知字符2"); - } - list.add(cb); - } - - @Override - public String getToken() { - return "place"; - } - - @Override - public boolean isBlock() { - return false; - } - - @Override - public void parse(Document dom, CharSequence source, int start, int end, int line) { - Span node = new Span(this.getToken()); - node.setCompiler(this); - node.setLineNumber(line); - node.setSource(source, start, end); - dom.append(node); - } - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/PrintLexer.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/PrintLexer.java deleted file mode 100644 index b659223..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/PrintLexer.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ -package com.diosay.otpl.lexers; - -import com.diosay.otpl.Document; -import com.diosay.otpl.Lexer; -import com.diosay.otpl.Node; -import com.diosay.otpl.Span; -import com.diosay.otpl.StringUtil; -import com.diosay.otpl.runtime.OpCode; -import com.diosay.otpl.runtime.opcodes.LoadVariable; -import com.diosay.otpl.runtime.opcodes.Print; -import java.util.ArrayList; - -/** - * 打印 - * - * @author jun - */ -public class PrintLexer extends com.diosay.otpl.Compiler implements Lexer { - - @Override - public void compile(Node node, ArrayList list) { - CharSequence source = node.getSource(); - if (source == null || source.length() == 0) { - return; - } - boolean filtrable = false; - if ('@' == source.charAt(0)) { - filtrable = true; - } - - //TODO:格式化 - this.compile(filtrable ? source.subSequence(1, source.length() - 1) : source, list,node.getLineNumber()); - -// LoadVariable var = new LoadVariable(); -// var.setName(source.subSequence(filtrable ? 1 : 0, source.length()).toString()); -// list.add(var); - - Print code = new Print(); - code.setFiltrable(filtrable); - - list.add(code); - } - - @Override - public String getToken() { - return "print"; - } - - @Override - public boolean isBlock() { - return false; - } - - @Override - public void parse(Document dom, CharSequence source, int start, int end, int line) { - - Span node = new Span(this.getToken()); - node.setCompiler(this); - node.setLineNumber(line); - node.setSource(source, start, end); - dom.append(node); - } - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/SectionLexer.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/SectionLexer.java deleted file mode 100644 index 91fa3f9..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/SectionLexer.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ -package com.diosay.otpl.lexers; - -import com.diosay.otpl.Block; -import com.diosay.otpl.Document; -import com.diosay.otpl.Lexer; -import com.diosay.otpl.Node; -import com.diosay.otpl.StringUtil; -import com.diosay.otpl.runtime.OpCode; -import java.util.ArrayList; - -/** - * 块定义词条 - * - * @author jun - */ -public class SectionLexer extends com.diosay.otpl.Compiler implements Lexer { - - @Override - public void compile(Node node, ArrayList list) { - CharSequence source = node.getSource(); - - if (source == null) { - throw new UnsupportedOperationException("语法错误:未设置名称"); - } - int index = 0; - index = StringUtil.trimLeftWhitespace(source, index, source.length()); - - if (source.charAt(index) != ':') { - throw new UnsupportedOperationException("语法错误:未知字符"); - } - index++; - int index2 = StringUtil.findIdentifier(source, index, source.length()); - - if (index2 < 0) { - throw new UnsupportedOperationException("语法错误:未设置名称"); - } - String name = source.subSequence(index, index2).toString(); - - index = StringUtil.trimLeftWhitespace(source, index2, source.length()); - if (index != source.length()) { - throw new UnsupportedOperationException("语法错误:未知字符2"); - } - - OpCode begin = OpCode.label(); - OpCode end = OpCode.label(); - list.add(begin); - Block bnode = (Block) node; - for (Node sub : bnode.children) { - sub.getCompiler().compile(sub, list); - } - com.diosay.otpl.runtime.opcodes.Block code = new com.diosay.otpl.runtime.opcodes.Block(); - - code.setBegin(begin); - code.setName(name); - - list.add(end); - //list.add(OpCode.label(node.getLineNumber())); - list.add(code); - } - - @Override - public String getToken() { - return "section"; - } - - @Override - public boolean isBlock() { - return true; - } - - @Override - public void parse(Document dom, CharSequence source, int start, int end, int line) { - - Block node = dom.createBlock(this.getToken()); - node.setCompiler(this); - node.setLineNumber(line); - node.setSource(source, start, end); - dom.append(node); - } - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/TextLexer.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/TextLexer.java deleted file mode 100644 index 9577dd0..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/TextLexer.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ - -package com.diosay.otpl.lexers; - -import com.diosay.otpl.Document; -import com.diosay.otpl.Lexer; -import com.diosay.otpl.Node; -import com.diosay.otpl.runtime.OpCode; -import com.diosay.otpl.runtime.opcodes.Print; -import com.diosay.otpl.runtime.opcodes.PrintString; -import java.util.ArrayList; - -/** - * 实现文本的编译。 - * @author jun - */ -public class TextLexer extends com.diosay.otpl.Compiler implements Lexer { - - @Override - public void compile(Node node, ArrayList list) { - PrintString code=new PrintString(); - code.setString(node.getSource().toString()); - list.add(code); - } - - @Override - public String getToken() { - return "text"; - } - - @Override - public boolean isBlock() { - return false; - } - - @Override - public void parse(Document dom, CharSequence source, int start, int end, int line) { - throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. - } - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/VariableLexer.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/VariableLexer.java deleted file mode 100644 index 030bd6d..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/lexers/VariableLexer.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ -package com.diosay.otpl.lexers; - -import com.diosay.otpl.CompileException; -import com.diosay.otpl.Document; -import com.diosay.otpl.Lexer; -import com.diosay.otpl.Node; -import com.diosay.otpl.Span; -import com.diosay.otpl.StringUtil; -import com.diosay.otpl.Token; -import com.diosay.otpl.runtime.OpCode; -import com.diosay.otpl.runtime.opcodes.SetVariable; -import java.util.ArrayList; - -/** - * 设置变量的值 - * - * @author jun - */ -public class VariableLexer extends com.diosay.otpl.Compiler implements Lexer { - - @Override - public void compile(Node node, ArrayList list) { - - CharSequence source = node.getSource(); - - if (source == null) { - throw new CompileException("语法错误:未设置变量名称"); - } - int index = 0; - index = StringUtil.trimLeftWhitespace(source, index, source.length()); - - if (source.charAt(index) != ':') { - throw new CompileException("语法错误:未知字符"); - } - index++; - int index2 = StringUtil.findIdentifier(source, index, source.length()); - - if (index2 < 0) { - throw new CompileException("语法错误:未设置变量名称。"); - } - String name = source.subSequence(index, index2).toString(); - - if (this.isKeyword(name)) { - throw new UnsupportedOperationException("语法错误:变量名不能是关键词:" + name); - } - ArrayList tokens = this.scan(source, index2, source.length(), node.getLineNumber()); - this.grammar(tokens); - if (tokens.size() != 1) { - throw new UnsupportedOperationException("语法错误:变量值太多。"); - } - for (Token sub : tokens) { - this.visit(sub, list); - } - list.add(new SetVariable().setName(name)); - - } - - @Override - public String getToken() { - return "var"; - } - - @Override - public boolean isBlock() { - return false; - } - - @Override - public void parse(Document dom, CharSequence source, int start, int end, int line) { - Span node = new Span(this.getToken()); - node.setCompiler(this); - node.setLineNumber(line); - node.setSource(source, start, end); - dom.append(node); - } - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/BuiltinFunctionInterface.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/BuiltinFunctionInterface.java deleted file mode 100644 index 252f8ae..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/BuiltinFunctionInterface.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ - -package com.diosay.otpl.runtime; - -/** - * 内建函数(BFI)。 - * @author jun - */ -public interface BuiltinFunctionInterface { - - /** - * 将对象转换为字符串串并合并。 - * @param args - * @return - */ - String str(Object[] args); - Object iterator(Object obj); - Object indexer(Object obj,Object[] args); -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/CodeLoader.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/CodeLoader.java deleted file mode 100644 index 3935da1..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/CodeLoader.java +++ /dev/null @@ -1,374 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ -package com.diosay.otpl.runtime; - -import com.diosay.otpl.runtime.opcodes.*; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.Charset; -import java.util.HashMap; -import mano.util.Utility; - -/** - * 操作码载入器 - * - * @author jun - */ -public class CodeLoader { - - private InputStream input; - private String version; - private Charset encoding;// = Charset.forName("utf-8"); - byte[] buf = new byte[8]; - private HashMap codes = new HashMap<>(); - private File source; - public CodeLoader parent; - public CodeLoader child; - public int pageAddr; - - void close() { - if (input != null) { - try { - input.close(); - } catch (IOException ex) { - } - } - } - - public File getSource() { - return source; - } - - public boolean load(ExecutionContext context, InputStream in, boolean b, File source) throws IOException { - encoding = context.inputEncoding(); - this.source = source; - input = in; - - if (input.read(buf, 0, 8) != 8) { //head line - close(); - throw new mano.InvalidOperationException("无效的OTPL文件。"); - } - version = new String(buf, 0, 7, encoding);//OTPL-01 - - byte mode = buf[7]; - //create time //8 - if (input.read(buf, 0, 8) != 8) { //创建时间 - close(); - throw new mano.InvalidOperationException("无效的OTPL文件。"); - } - if (mode == 1) {//检查文件 改变 - if (input.read(buf, 0, 8) != 8) { //修改时间 - close(); - throw new mano.InvalidOperationException("无效的OTPL文件。"); - } - long modified = Utility.toLong(buf, 0);//8 - File file = new File(new String(loadString(), encoding)); - if (!file.exists() || !file.isFile() || modified != file.lastModified()) { - close(); - return false; - } - } - readToEhead(); - - return startAddr != 0; - } - - int startAddr = 0; - int endAddr = -1; - - private void readToEhead() throws IOException { - while (true) { - - OpCode code = loadCode(); - - if (code == null) { - - } else if (code.getType() == OpcodeType.stblk) { - codes.put(code.getAddress(), code); - Block blk = (Block) code; - this.blocks.put(blk.getName(), blk); - } else if (code.getType() == OpcodeType.ehead) { - codes.put(code.getAddress(), code); - startAddr = code.getAddress(); - return; - } else { - codes.put(code.getAddress(), code); - } - } - } - - private OpCode loadCode() throws IOException { - - int read = input.read(buf, 0, 5); - if (read != 5) { //head line - close(); - throw new mano.InvalidOperationException("无效的OTPL文件:读取行头失败。"); - } - int addr = Utility.toInt(buf, 0); - OpcodeType type = OpcodeType.parse(buf, 4); - - if (type.equals(OpcodeType.abort)) { - EndOfFile code = new EndOfFile(); - code.setAddress(addr); - code.setLoader(this); - return code; - } else if (type.equals(OpcodeType.call)) { - Call code = new Call(); - code.setAddress(addr); - code.setArgLength(loadInt()); - - code.setLoader(this); - return code; - } else if (type.equals(OpcodeType.callvri)) { - Callvri code = new Callvri(); - code.setAddress(addr); - code.setArgLength(loadInt()); - code.setName(new String(loadString(), this.encoding)); - - code.setLoader(this); - return code; - } else if (type.equals(OpcodeType.doc)) { - Layout code = new Layout(); - code.setAddress(addr); - code.setLoader(this); - return code; - }else if (type.equals(OpcodeType.inc)) { - Include code = new Include(); - code.setAddress(addr); - code.setLoader(this); - return code; - } else if (type.equals(OpcodeType.body)) { - Body code = new Body(); - code.setAddress(addr); - code.setLoader(this); - return code; - } else if (type.equals(OpcodeType.ehead)) { - EndHeader code = new EndHeader(); - code.setAddress(addr); - code.setLoader(this); - return code; - } else if (type.equals(OpcodeType.br)) { - Break code = new Break(); - code.setAddress(addr); - code.setBehavior(loadBytes(1)[0]); - if (code.getBehavior() != Break.BREAK_EXIT) { - code.setTarget(loadInt()); - } - code.setLoader(this); - return code; - } else if (type.equals(OpcodeType.ldu)) { - LoadLong code = new LoadLong(); - code.setAddress(addr); - code.setValue(loadLong()); - code.setLoader(this); - return code; - } else if (type.equals(OpcodeType.ldm)) { - LoadMember code = new LoadMember(); - code.setAddress(addr); - code.setArgLength(loadInt()); - code.setName(new String(loadString(), this.encoding)); - - code.setLoader(this); - return code; - } else if (type.equals(OpcodeType.ldr)) { - LoadReal code = new LoadReal(); - code.setAddress(addr); - code.setValue(Double.parseDouble(new String(this.loadString(), this.encoding))); - code.setLoader(this); - return code; - } else if (type.equals(OpcodeType.ldstr)) { - LoadString code = new LoadString(); - code.setAddress(addr); - code.setContent(new String(this.loadString(), this.encoding)); - code.setLoader(this); - return code; - } else if (type.equals(OpcodeType.ldv)) { - LoadVariable code = new LoadVariable(); - code.setAddress(addr); - code.setName(new String(this.loadString(), this.encoding)); - code.setLoader(this); - return code; - } - else if (type.equals(OpcodeType.nop)) { - Nop code = new Nop(); - code.setAddress(addr); - code.setLoader(this); - return code; - } else if (type.equals(OpcodeType.pop)) { - Pop code = new Pop(); - code.setAddress(addr); - - code.setLoader(this); - return code; - } else if (type.equals(OpcodeType.prt)) { - Print code = new Print(); - code.setAddress(addr); - - if (input.read(buf, 0, 1) != 1) { - close(); - throw new mano.InvalidOperationException("无效的OTPL文件,读取参数失败。"); - } - code.setFiltrable(buf[0] == 1); - code.setLoader(this); - return code; - } else if (type.equals(OpcodeType.stblk)) { - Block code = new Block(); - code.setAddress(addr); - code.setBeginAddress(this.loadInt()); - code.setName(new String(loadString(), this.encoding)); - - code.setLoader(this); - return code; - } else if (type.equals(OpcodeType.call_blk)) { - CallBlock code = new CallBlock(); - code.setAddress(addr); - code.setName(new String(loadString(), this.encoding)); - if (input.read(buf, 0, 1) != 1) { //长度 - close(); - throw new mano.InvalidOperationException("获取布尔值失败。"); - } - code.required(buf[0] == 1); - - code.setLoader(this); - return code; - } else if (type.equals(OpcodeType.stv)) { - SetVariable code = new SetVariable(); - code.setAddress(addr); - - code.setName(new String(loadString(), this.encoding)); - code.setLoader(this); - return code; - } else if (type.equals(OpcodeType.ptstr)) { - PrintString code = new PrintString(); - code.setAddress(addr); - - byte[] bytes = loadString(); - code.setBytes(bytes, 0, bytes.length); - code.setLoader(this); - return code; - } else if (type.equals(OpcodeType.op)) { - Operator code = new Operator(); - code.setAddress(addr); - code.setOperator(loadBytes(1)[0]); - - code.setLoader(this); - return code; - } else if (type.equals(OpcodeType.peek)) { - Peek code = new Peek(); - code.setAddress(addr); - - code.setLoader(this); - return code; - } else if (type.equals(OpcodeType.ldc)) { - LoadConst code = new LoadConst(); - code.setAddress(addr); - code.setValue(loadBytes(1)[0]); - - code.setLoader(this); - return code; - } else if (type.equals(OpcodeType.sl)) { - SourceLineNumber code = new SourceLineNumber(); - code.setAddress(addr); - code.setValue(loadInt()); - code.setLoader(this); - return code; - } else { - throw new java.lang.RuntimeException("OTPL操作码类型未定义:" + type); - } - } - - private byte[] loadString() throws IOException { - if (input.read(buf, 0, 4) != 4) { //长度 - close(); - throw new mano.InvalidOperationException("获取字符串长度。"); - } - int len = Utility.toInt(buf, 0); - byte[] bytes = new byte[len]; - if (input.read(bytes) != len) { - close(); - throw new mano.InvalidOperationException("无效的OTPL文件,读取字符串失败。"); - } - return bytes; - } - - private int loadInt() throws IOException { - if (input.read(buf, 0, 4) != 4) { //长度 - close(); - throw new mano.InvalidOperationException("获取int失败。"); - } - return Utility.toInt(buf, 0); - } - - private byte[] loadBytes(int len) throws IOException { - if (input.read(buf, 0, len) != len) { //长度 - close(); - throw new mano.InvalidOperationException("获取字节失败。"); - } - return buf; - } - - private long loadLong() throws IOException { - if (input.read(buf, 0, 8) != 8) { //长度 - close(); - throw new mano.InvalidOperationException("获取int失败。"); - } - return Utility.toLong(buf, 0); - } - - /** - * 读取一个操作码 - * - * @param addr - * @return - */ - public OpCode loadCode(int addr) throws IOException { - if (this.endAddr != -1 && addr > this.endAddr) { - return null; - } - if (this.codes.containsKey(addr)) { - return this.codes.get(addr); - } - while (true) { - OpCode code = loadCode(); - if (code == null) { - return null; - } - this.codes.put(code.getAddress(), code); - if (code.getType().equals(OpcodeType.abort)) { - this.endAddr = code.getAddress(); - this.close(); - } - if (code.getAddress() == addr) { - return code; - } - } - } - private HashMap blocks = new HashMap<>(); - - /** - * 获取一个块 - * - * @param name - * @return - */ - public Block getBlock(String name) { - - Block result = null; - if (this.child != null && this.child.blocks.containsKey(name)) { - result = this.child.blocks.get(name); - } - - if (result == null && this.blocks.containsKey(name)) { - result = this.blocks.get(name); - } - - return result != null ? result : (this.child != null ? this.child.getBlock(name) : null); - } - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/ExecutionContext.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/ExecutionContext.java deleted file mode 100644 index a0db342..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/ExecutionContext.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ - -package com.diosay.otpl.runtime; - -import java.io.File; -import java.nio.charset.Charset; - -/** - * 表示一个执行上下文。 - * @author jun - */ -public interface ExecutionContext { - - /** - * 获取源文件的根目录。 - */ - String getBasedir(); - - /** - * 获取目标生成文件的临时目录。 - */ - String getTempdir(); - - /** - * 获取输出编译。 - * @return - */ - Charset outputEncoding(); - - /** - * 获取输出编译。 - * @return - */ - Charset inputEncoding(); - - /** - * 设置一个变量 - * @param key - * @param value - */ - void set(String key,Object value); - /** - * 获取一个变量 - * @param key - * @return - */ - Object get(String key); - - /** - * 压入对象到栈顶 - * @param value - */ - void push(Object value); - /** - * 从栈顶弹出一个对象,如果栈为空则返回 null - * @return - */ - Object pop(); - - /** - * 从栈顶取出一个对象,如果栈为空则返回 null - * @return - */ - Object peek(); - - void write(boolean filtrable,Object obj); - - /** - * 写入字序列。 - * @param filtrable - * @param cs - * @param start - * @param end - */ - void write(boolean filtrable,CharSequence cs, int start, int end); - - /** - * 写入二进制。 - * @param filtrable - * @param array - * @param index - * @param count - */ - void write(boolean filtrable, byte[] array, int index, int count); - - /** - * 清空变量、堆栈与重置相关运行时参数。 - */ - void reset(); - - /** - * 获取(或创建)一个新的解释器。 - * @return - */ - Interpreter newInterpreter(); - - /** - * 释放一个解释器,以便其他使用。 - * @param interpreter - */ - void freeInterpreter(Interpreter interpreter); - - /** - * 根据源文件获取加载器。 - * @param source - * @return - */ - CodeLoader getLoader(File source,Interpreter interpreter) throws Exception; - - /** - * 设置当前源代码行号。 - * @param line - */ - void setCurrentSourceLine(int line); - - /** - * 获取当前源代码行号。 - * @return - */ - int getCurrentSourceLine(); - - /** - * 获取内置函数接口。 - * @return - */ - BuiltinFunctionInterface calls(); - - /** - * 调用函数。 - * @param funcName - * @param args - * @return - */ - Object call(String funcName,Object[] args); -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/Filter.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/Filter.java deleted file mode 100644 index 60a4da5..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/Filter.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ - -package com.diosay.otpl.runtime; - -import java.nio.charset.Charset; - -/** - * 一个写入过滤器,可以在写入时重定向输出或改变编码等。 - * @author jun - */ -public interface Filter { - /** - * 写入二进制。 - * @param writer - * @param original - * @param array - * @param index - * @param count - */ - void write(Writer writer,Charset original, byte[] array, int index, int count); -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/Interpreter.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/Interpreter.java deleted file mode 100644 index 71df32f..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/Interpreter.java +++ /dev/null @@ -1,552 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ -package com.diosay.otpl.runtime; - -import com.diosay.otpl.Document; -import com.diosay.otpl.Parser; -import com.diosay.otpl.runtime.opcodes.EndOfFile; -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.Closeable; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.StringReader; -import java.lang.reflect.Array; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Stack; -import mano.DateTime; -import mano.util.Utility; - -/** - * 实现的 OTPL 解释器 - * - * @author jun - */ -public class Interpreter implements Closeable { - - @Override - public void close() throws IOException { - // - } - - static class TempExecutionContext implements ExecutionContext { - - private HashMap items = new HashMap<>(); - private Stack stack = new Stack<>(); - - @Override - public String getBasedir() { - - return "E:\\repositories\\java\\mano\\mano-server-projects\\otpl4j\\demo"; - } - - @Override - public String getTempdir() { - return "C:\\Users\\jun\\Desktop\\demo"; - } - - @Override - public void set(String key, Object value) { - items.put(key, value); - } - - @Override - public Object get(String key) { - if (items.containsKey(key)) { - return items.get(key); - } - return null;//TODO:报错? - } - - @Override - public void push(Object value) { - stack.push(value); - } - - @Override - public Object pop() { - if (stack.isEmpty()) { - return null; - } - return stack.pop(); - } - - @Override - public void reset() { - throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. - } - - @Override - public Charset outputEncoding() { - return Charset.defaultCharset(); -//return Charset.forName("utf-8"); - } - - @Override - public void write(boolean filtrable, Object obj) { - if (obj == null) { - return; - } - String s = obj.toString(); - write(filtrable, s, 0, s.length()); - } - - @Override - public void write(boolean filtrable, CharSequence cs, int start, int end) { - byte[] array = cs.subSequence(start, end).toString().getBytes(this.outputEncoding()); - write(filtrable, array, 0, array.length); - } - - @Override - public void write(boolean filtrable, byte[] array, int index, int count) { - if (filtrable) { - //TODO: - } - - System.out.write(array, index, count); - } - - @Override - public Charset inputEncoding() { - return Charset.forName("utf-8"); - } - - @Override - public Interpreter newInterpreter() { - return new Interpreter(); - } - - @Override - public void freeInterpreter(Interpreter interpreter) { - - } - - private HashMap loaders = new HashMap<>(); - - @Override - public CodeLoader getLoader(File source, Interpreter interpreter) throws Exception { - - String id = Integer.toHexString(source.toString().hashCode()); - if (loaders.containsKey(id)) { - return loaders.get(id); - } - - if (interpreter == null) { - interpreter = newInterpreter(); - loaders.put(id, interpreter.load(this, source)); - freeInterpreter(interpreter); - } else { - loaders.put(id, interpreter.load(this, source)); - } - return loaders.get(id); - } - - @Override - public Object peek() { - return this.stack.peek(); - } - private int lineNumber; - - @Override - public void setCurrentSourceLine(int line) { - lineNumber = line; - } - - @Override - public int getCurrentSourceLine() { - return lineNumber; - } - - @Override - public BuiltinFunctionInterface calls() { - return new BFI(); - } - - @Override - public Object call(String funcName, Object[] args) { - - if ("str".equals(funcName)) { - return calls().str(args); - }else if ("int".equals(funcName)) { - return Utility.toInt(args[0]); - }else if ("long".equals(funcName)) { - return Utility.toLong(args[0]); - } else if ("iterator".equals(funcName)) { - return calls().iterator(args[0]); - } else if ("iterator$hasNext".equals(funcName)) { - Iterator itor = (Iterator) args[0]; - return itor.hasNext(); - } else if ("iterator$next".equals(funcName)) { - Iterator itor = (Iterator) args[0]; - return itor.next(); - } else if ("indexer".equals(funcName)) { - if (args.length < 2) { - throw new UnsupportedOperationException("参数不匹配:" + funcName); - } - Object[] nargs = new Object[args.length - 1]; - System.arraycopy(args, 0, nargs, 0, args.length - 1); - return calls().indexer(args[args.length - 1], nargs); - } else { - Object obj = items.get(funcName); - if (obj == null || !(obj instanceof Method)) { - throw new UnsupportedOperationException("函数未定义:" + funcName); - } - Method method = (Method) obj; - method.setAccessible(true); - try { - - Class[] types = method.getParameterTypes(); - if (args.length < types.length) { - throw new UnsupportedOperationException("参数不匹配:" + funcName); - } - Object[] nargs = new Object[types.length]; - for (int i = 0; i < types.length; i++) { - Class clazz = types[i]; - - nargs[i] = Utility.cast(clazz, args[i]); - } - - return method.invoke(null, nargs); - } catch (IllegalAccessException | IllegalArgumentException ex) { - throw new RuntimeException(ex); - } catch (InvocationTargetException ex) { - if (ex.getTargetException() != null) { - throw new RuntimeException(ex.getTargetException()); - } - throw new RuntimeException(ex); - } - - } - } - - static Object invokeMethod(Method method, Object instance, Object[] args) { - if (method == null) { - return null; - } - - try { - method.setAccessible(true); - - Class[] types = method.getParameterTypes(); - if (args.length < types.length) { - throw new UnsupportedOperationException("参数不匹配:" + method.getName()); - } - Object[] nargs = new Object[types.length]; - for (int i = 0; i < types.length; i++) { - Class clazz = types[i]; - - nargs[i] = Utility.cast(clazz, args[i]); - } - - return method.invoke(instance, nargs); - } catch (IllegalAccessException | IllegalArgumentException ex) { - throw new RuntimeException(ex); - } catch (InvocationTargetException ex) { - if (ex.getTargetException() != null) { - throw new RuntimeException(ex.getTargetException()); - } - throw new RuntimeException(ex); - } - } - - class BFI implements BuiltinFunctionInterface { - - @Override - public String str(Object[] args) { - if (args == null) { - return null; - } - StringBuilder sb = new StringBuilder(); - for (Object obj : args) { - sb.append(obj); - } - return sb.toString(); - } - - public int len(Object value) { - if (value == null) { - return -1; - } - - return 0; - } - - @Override - public Object iterator(Object obj) { - if (obj == null) { - obj = new Object[0]; - } - - if (obj instanceof Iterable) { - return ((Iterable) obj).iterator(); - } else if (obj instanceof Map) { - return ((Iterable) ((Map) obj).entrySet()).iterator(); - } else if (obj.getClass().isArray()) { - final Object array = obj; - final int size = Array.getLength(obj); - return new Iterator() { - int current = 0; - - @Override - public boolean hasNext() { - return current < size; - } - - @Override - public Object next() { - return Array.get(array, current++); - } - - }; - } - throw new RuntimeException("give object is a non-iterable object." + obj.getClass()); - } - - @Override - public Object indexer(Object obj, Object[] args) { - - if (obj == null) { - return null; - } else if (obj.getClass().isArray()) { - return Array.get(obj, Integer.parseInt(args[0].toString())); - } else { - Method method = null; - for (Method m : obj.getClass().getMethods()) { - if (m.getName().equals("get") && m.getParameterCount() == args.length) { - method = m; - break; - } - } - if (method == null) { - throw new UnsupportedOperationException("函数未定义:" + "get"); - } - return invokeMethod(method, obj, args); - } - } - } - - } - - static class MyItem { - - public int name = 0; - - public String getName2() { - return "hello" + name; - } - - public Object get(Object obj){ - return obj; - } - } - - static class MyItemXX { - - public MyItem inner=new MyItem(); - - } - - private static String substr(String n, Integer len) { - if (n == null || len < 0) { - return n; - } - return n.substring(0, len); - } - - public static void main(String[] args) throws Exception { - - Interpreter interpreter = new Interpreter(); - ArrayList list = new ArrayList<>(); - MyItem item = new MyItem(); - item.name = 1; - list.add(item); - item = new MyItem(); - item.name = 2; - list.add(item); - item = new MyItem(); - item.name = 3; - list.add(item); - String file = "E:\\repositories\\java\\mano\\mano-server-projects\\otpl4j\\demo\\page.html"; - TempExecutionContext context = new TempExecutionContext(); - context.items.put("name", "张三"); - context.items.put("list", list); - context.items.put("item2", new MyItemXX()); - context.items.put("item", new MyItem()); - context.items.put("arr", new String[]{"张三","李四","王二"}); - context.items.put("substr", Interpreter.class.getDeclaredMethod("substr", String.class, Integer.class)); - interpreter.exec(context, new File(file)); - - } - - /** - * 编译一个文件OTPL源文件。 - * - * @param filename - */ - public void compileFile(File file, String basedir, File target) throws Exception { - - Parser parser = new Parser(); - Charset encoding = Charset.forName("utf-8"); - try (BufferedReader reader = Parser.open(file.toString())) { - Document dom = parser.parse(reader, file.toString()); - ArrayList list = new ArrayList<>(); - dom.getCompiler().compile(dom, list); - list.add(new EndOfFile()); - int line = 0; - for (OpCode code : list) { - line++; - code.setAddress(line); - } - target.delete(); - target.createNewFile(); - try (FileOutputStream out = new FileOutputStream(target)) { - - //文件头 - //版本 类型 目标文件最后修改时间 源文件最后修改时间 文件名长度 文件名 - //OTPL-01 1(FILE 1,OTHER:2 {8 LONG} {8} {4} N - byte[] bytes = file.toString().getBytes(encoding); - out.write("OTPL-02".getBytes(encoding)); - out.write(1); - out.write(Utility.toBytes(DateTime.nowTime())); - out.write(Utility.toBytes(file.lastModified())); - out.write(Utility.toBytes(bytes.length)); - out.write(bytes); - for (OpCode code : list) { - code.compile(out, encoding); - } - - } - } - - } - - /** - * 载入文件 - * - * @param context - * @param source - * @return - * @throws Exception - */ - public CodeLoader load(ExecutionContext context, File source) throws Exception { - CodeLoader loader = new CodeLoader(); - File target; - target = new File(Utility.toPath(context.getTempdir(), Integer.toHexString(source.toString().hashCode()) + ".otc").toString()); - - boolean compiled = true; - if (!target.exists() || !target.isFile()) { - compiled = false; - } else { - if (!loader.load(context, new FileInputStream(target), true, source)) { - compiled = false; - } - } - - if (!compiled) { - try { - compileFile(source, context.getBasedir(), target); - } catch (java.io.FileNotFoundException ex) { - throw new java.io.FileNotFoundException("未找到源文件:" + source.toString()); - } - } - - if (!loader.load(context, new FileInputStream(target), true, source)) { - throw new mano.InvalidOperationException("编译失败"); - } - - return loader; - } - - /** - * 执行一个OTPL源文件。 - * - * @param context - * @param source - * @throws Exception - */ - public void exec(ExecutionContext context, File source) throws Exception { - this.exec(context, context.getLoader(source, this)); - } - - /** - * 执行已经加载的代码 - * - * @param context - * @param loader - * @throws Exception - */ - public void exec(ExecutionContext context, CodeLoader loader) throws Exception { - exec(context,loader,loader.startAddr,loader.endAddr); -// int next = loader.startAddr; -// OpCode code; -// while (true) { -// if (next <= 0) { -// break; -// } -// code = loader.loadCode(next); -// if (code == null) { -// throw new java.lang.RuntimeException("无效的指令地址:" + next); -// } else if (code.getAddress() == loader.endAddr) { -// break; -// } -// next = code.execute(context); -// if (code.getType() == OpcodeType.doc) { -// code.getLoader().parent.pageAddr = next; -// return; -// } -// } - - } - - /** - * 执行指定段的代码 - * - * @param context - * @param loader - * @param start - * @param end - * @throws Exception - */ - public void exec(ExecutionContext context, CodeLoader loader, int start, int end) throws Exception { - int next = start < 1 ? loader.startAddr : start; - int lineNumber = 0; - OpCode code; - while (true) { - if (next <= 0) { - break; - } - if (end != -1 && next >= end) { - break; - } - - code = loader.loadCode(next); - if (code == null) { - throw new java.lang.RuntimeException("无效的指令地址:" + next); - } - else if (code.getAddress() == loader.endAddr) { - break; - } - next = code.execute(context); - lineNumber = context.getCurrentSourceLine(); - if (code.getType() == OpcodeType.doc) { - code.getLoader().parent.pageAddr = next; - return; - } - } - } -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/OpCode.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/OpCode.java deleted file mode 100644 index b33b6fd..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/OpCode.java +++ /dev/null @@ -1,169 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ -package com.diosay.otpl.runtime; - -import com.diosay.otpl.runtime.opcodes.*; -import java.io.OutputStream; -import java.io.Writer; -import java.nio.charset.Charset; - -/** - * 表示一条Open-TPL操作指令。 - * - * @author jun - */ -public abstract class OpCode { - - public static final boolean DEBUG=true; - - private int addr; - @Deprecated - private int lineNumber; - private CodeLoader loader; - /** - * 获取当前指令的地址。 - * @return - */ - public final int getAddress(){ - return this.addr; - } - /** - * 获取下条指令的地址。 - * @return - */ - public final int getNextAddress(){ - return this.addr+1; - } - /** - * 设置当前指令的地址。 - * @param address - */ - public final void setAddress(int address){ - this.addr=address; - } - - /** - * 获取源代码行号 - * @return - */ - @Deprecated - public final int getSourceLine(){ - return this.lineNumber; - } - /** - * 置源代码行号 - * @param line - */ - @Deprecated - public final OpCode setSourceLine(int line){ - this.lineNumber=line; - return this; - } - - /** - * 获取当前的操作码 - * @return - */ - public abstract OpcodeType getType(); - - /** - * 编译并输出。 - *

注意:编码格式必须是UTF8. - * @param output - */ - public abstract void compile(OutputStream output,Charset encoding) throws Exception; - - /** - * 执行该指令,并返回下条指令地址 - * @param context - */ - public abstract int execute(ExecutionContext context) throws Exception; - - - /** - * 创建一个新标签。 - * @return - */ - public static OpCode label(){ - return new Nop(); - } - - /** - * 创建一个新的中断指令。 - * @param target - * @return - */ - public static Break makeBreak(OpCode target){ - return new Break().setTarget(target).setBehavior(Break.BREAK); - } - /** - * 创建一个新的中断指令。 - * @param target - * @return - */ - public static Break makeBreakTrue(OpCode target){ - return new Break().setTarget(target).setBehavior(Break.BREAK_TRUE); - } - /** - * 创建一个新的中断指令。 - * @param target - * @return - */ - public static Break makeBreakFalse(OpCode target){ - return new Break().setTarget(target).setBehavior(Break.BREAK_FALSE); - } - /** - * 创建一个新的中断指令。 - * @return - */ - public static Break makeBreakReturn(){ - return new Break().setBehavior(Break.BREAK_EXIT); - } - /** - * 创建一个新的中断指令。 - * @param target - * @return - */ - public static Break makeBreak(int target){ - return new Break().setTarget(target).setBehavior(Break.BREAK); - } - /** - * 创建一个新的中断指令。 - * @param target - * @return - */ - public static Break makeBreakTrue(int target){ - return new Break().setTarget(target).setBehavior(Break.BREAK_TRUE); - } - /** - * 创建一个新的中断指令。 - * @param target - * @return - */ - public static Break makeBreakFalse(int target){ - return new Break().setTarget(target).setBehavior(Break.BREAK_FALSE); - } - /** - * 设置与之关联的载入器 - * @param loader - */ - public void setLoader(CodeLoader loader){ - this.loader=loader; - } - - /** - * 获取与之关联的载入器 - * @return - */ - public CodeLoader getLoader(){ - return loader; - } - - public String tag; - public String mark; -} \ No newline at end of file diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/OpcodeType.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/OpcodeType.java deleted file mode 100644 index 14b3315..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/OpcodeType.java +++ /dev/null @@ -1,209 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ - -package com.diosay.otpl.runtime; - -/** - * 操作码类型 - * @author jun - */ -public enum OpcodeType { - /** - * 表示一个占位,不执行任何操作。通常用作 label 使用。 - */ - nop(0), - /** - * 表示一个文档,执行此操作时将打开该文档为执行。 - */ - doc(1), - /** - * 从栈顶弹出一个元素并打印到输出流。 - */ - prt(2), - /** - * 无条件跳转到指定指令行。 - */ - br(3), - /** - * 从栈顶弹出一个元素,如果该对象为假(null,0,false),则跳转到指定指令行。 - */ - brf(4), - /** - * 从栈顶弹出一个元素,并丢弃。 - */ - pop(5), - /** - * 根据给定索引,从变量组中获取一个对象,并将该对象压入栈顶。 - */ - ldv(6), - /** - * 从栈顶弹出一个对象O,并从中获取其成员对象(字段、属性、方法),并将对象O与成员对象压入栈顶。 - */ - ldm(7), - /** - * 从栈顶弹出一个对象并将该对象设置到变量组中。 - */ - stv(8), - /** - * 从栈顶开始弹出执行方法所需对象并执行,将执行结果对象压入栈顶。 - */ - call(9), - /** - * 载入一个 double 小数,并压入栈顶。 - */ - ldr(10), - /** - * 载入一个 long 整数,并压入栈顶。 - */ - ldu(11), - /** - * 载入一个字符串,并压入栈顶。 - */ - ldstr(12), - /** - * 从栈顶弹出两个对象进行相加,并将结果压入栈顶。 - */ - @Deprecated - add(13), - /** - * 从栈顶弹出两个对象进行相减,并将结果压入栈顶。 - */ - @Deprecated - sub(14), - /** - * 从栈顶弹出两个对象进行相乘,并将结果压入栈顶。 - */ - @Deprecated - mul(15), - /** - * 从栈顶弹出两个对象进行相除,并将结果压入栈顶。 - */ - @Deprecated - div(16), - /** - * 从栈顶弹出两个对象进行模运算,并将结果压入栈顶。 - */ - @Deprecated - mod(17), - /** - * 从栈顶弹出两个对象进行等于比较,并将结果压入栈顶。 - */ - @Deprecated - eq(18), - /** - * 从栈顶弹出两个对象进行不等于比较,并将结果压入栈顶。 - */ - @Deprecated - neq(19), - /** - * 从栈顶弹出两个对象进行大于比较,并将结果压入栈顶。 - */ - @Deprecated - gt(20), - /** - * 从栈顶弹出两个对象进行大于等于比较,并将结果压入栈顶。 - */ - @Deprecated - gte(21), - /** - * 从栈顶弹出两个对象进行小于比较,并将结果压入栈顶。 - */ - @Deprecated - lt(22), - /** - * 从栈顶弹出两个对象进行小于比较,并将结果压入栈顶。 - */ - @Deprecated - lte(23), - /** - * 从栈顶弹出一个对象进行非运算,并将结果压入栈顶。 - */ - @Deprecated - not(24), - /** - * 从栈顶弹出两个对象进行逻辑与运算,并将结果压入栈顶。 - */ - @Deprecated - and(25), - /** - * 从栈顶弹出两个对象进行逻辑非运算,并将结果压入栈顶。 - */ - @Deprecated - or(26), - /** - * 终止当前文档的执行。 - */ - abort(27), - /** - * 结束整个当前事务的执行。 - */ - exit(28), - /** - * 头部结束。 - */ - ehead(29), - /** - * 设置块变 - */ - stblk(30), - /** - * 打印字符串 - */ - ptstr(31), - /** - * 正文 - */ - body(32), - /** - * 调用一个块。 - */ - call_blk(33), - /** - * 压入 null 到栈。 - */ - @Deprecated - nil(34), - /** - * 操作符 - */ - op(35), - /** - * 获取栈顶元素,再压入栈顶? - */ - peek(36), - /** - * 临时 - */ - brd(37), - /** - * 载入一个预定义常量。 - */ - ldc(38), - /** - * 行号 - */ - sl(39), - callvri(40), - inc(41); - - - - public final byte value; - private OpcodeType(int value){ - this.value=(byte)value; - } - - public static OpcodeType parse(byte[] buffer,int index){ - for (OpcodeType type : OpcodeType.values()) { - if (buffer[index] == type.value) { - return type; - } - } - throw new mano.InvalidOperationException("解析失败,value:"+buffer[index]); - } -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/Util.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/Util.java deleted file mode 100644 index 5acbb31..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/Util.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ -package com.diosay.otpl.runtime; - -import mano.util.Utility; - -/** - * 内部工具 - * - * @author jun - */ -public class Util { - - public static boolean toBoolean(Object obj) { - if (obj == null) { - return false; - } - try { - return Utility.cast(Boolean.class, obj); - } catch (Exception ex) { - try { - return Utility.cast(Double.class, obj) == 0 ? false : true; - } catch (Exception ex2) { - return true; - } - } - } -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/Writer.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/Writer.java deleted file mode 100644 index a406666..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/Writer.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ -package com.diosay.otpl.runtime; - -import java.nio.charset.Charset; - -/** - * 写入器 - * - * @author jun - */ -public interface Writer { - - /** - * 获取过滤器。 - * @return - */ - Filter getFilter(); - - /** - * 写入字序列。 - * @param filtrable - * @param cs - * @param start - * @param end - */ - void write(boolean filtrable,CharSequence cs, int start, int end); - - /** - * 写入二进制。 - * @param filtrable - * @param original - * @param array - * @param index - * @param count - */ - void write(boolean filtrable,Charset original, byte[] array, int index, int count); -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Block.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Block.java deleted file mode 100644 index 15f5b3a..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Block.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ -package com.diosay.otpl.runtime.opcodes; - -import com.diosay.otpl.runtime.ExecutionContext; -import com.diosay.otpl.runtime.OpCode; -import com.diosay.otpl.runtime.OpcodeType; -import java.io.OutputStream; -import java.nio.charset.Charset; -import mano.util.Utility; - -/** - * 块 - * - * @author jun - */ -public class Block extends OpCode { - - private OpCode begin; - private int beginAddr; - - private String name; - - /** - * 设置变量名 - * - * @param n - */ - public void setName(String n) { - this.name = n; - } - - public void setBegin(OpCode start) { - begin = start; - } - - public void setBeginAddress(int addr) { - beginAddr = addr; - } - - public int getBeginAddress() { - return beginAddr; - } - - public int getEndAddress() { - return this.getAddress() - 1; - } - - public String getName() { - return name; - } - - @Override - public OpcodeType getType() { - return OpcodeType.stblk; - } - - @Override - public void compile(OutputStream output, Charset encoding) throws Exception { - output.write(Utility.toBytes(this.getAddress())); - output.write(this.getType().value); - output.write(Utility.toBytes(begin.getAddress())); - if (this.name != null) { - byte[] bytes = this.name.getBytes(encoding); - output.write(Utility.toBytes(bytes.length)); - output.write(bytes); - } else { - throw new UnsupportedOperationException("未设置块名."); - } - } - - @Override - public int execute(ExecutionContext context) throws Exception {// - throw new UnsupportedOperationException("Not supported yet.");//apply - } - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Body.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Body.java deleted file mode 100644 index 77ca24e..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Body.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ - -package com.diosay.otpl.runtime.opcodes; - -import com.diosay.otpl.runtime.ExecutionContext; -import com.diosay.otpl.runtime.Interpreter; -import com.diosay.otpl.runtime.OpCode; -import static com.diosay.otpl.runtime.OpCode.DEBUG; -import com.diosay.otpl.runtime.OpcodeType; -import java.io.OutputStream; -import java.nio.charset.Charset; -import mano.util.Utility; - -/** - * 正文 - * @author jun - */ -public class Body extends OpCode { - - @Override - public OpcodeType getType() { - return OpcodeType.body; - } - - @Override - public void compile(OutputStream output, Charset encoding) throws Exception { - output.write(Utility.toBytes(this.getAddress())); - output.write(this.getType().value); - - } - - @Override - public int execute(ExecutionContext context) throws Exception { - - if(this.getLoader().child==null){ - throw new mano.InvalidOperationException("不是一个效的布局页面,或未找到子页面。"); - } - - Interpreter interpreter = context.newInterpreter(); - - interpreter.exec(context, this.getLoader().child,this.getLoader().pageAddr,-1);//执行全部子页面 - - context.freeInterpreter(interpreter); - - - return this.getAddress()+1; - } - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Break.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Break.java deleted file mode 100644 index a5d5d5a..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Break.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ -package com.diosay.otpl.runtime.opcodes; - -import com.diosay.otpl.CompileException; -import com.diosay.otpl.runtime.ExecutionContext; -import com.diosay.otpl.runtime.OpCode; -import com.diosay.otpl.runtime.OpcodeType; -import com.diosay.otpl.runtime.Util; -import java.io.OutputStream; -import java.nio.charset.Charset; -import mano.util.Utility; - -/** - * 无条件地将控制转移到目标指令。 - * - * @author jun - */ -public class Break extends OpCode { - - private byte behavior; - private int addr = -1; - private OpCode target; - - public static final byte BREAK = 0; - public static final byte BREAK_FALSE = 1; - public static final byte BREAK_TRUE = 2; - public static final byte BREAK_EXIT = 3; - - /** - * 设置跳转目标。 - * - * @param addr - * @return - */ - public Break setTarget(OpCode addr) { - if (addr == null) { - throw new IllegalArgumentException(); - } - target = addr; - return this; - } - - /** - * 设置跳转目标。 - * - * @param addr - * @return - */ - public Break setTarget(int target) { - if (target <= 0) { - throw new IllegalArgumentException(); - } - addr = target; - return this; - } - - public Break setBehavior(byte b) { - behavior = b; - return this; - } - - public byte getBehavior() { - return behavior; - } - - @Override - public OpcodeType getType() { - return OpcodeType.br; - } - - @Override - public void compile(OutputStream output, Charset encoding) throws Exception { - output.write(Utility.toBytes(this.getAddress())); - output.write(this.getType().value); - output.write(behavior); - if (behavior != BREAK_EXIT) { - if (addr <= -1) { - if (target == null) { - throw new CompileException("未设置目标地址。"); - } - addr = target.getAddress(); - } - output.write(Utility.toBytes(addr)); - } - } - - @Override - public int execute(ExecutionContext context) throws Exception { - if (behavior != BREAK_EXIT) { - if (addr <= -1) { - if (target == null) { - throw new RuntimeException("未设置目标地址。"); - } - addr = target.getAddress(); - } - if (behavior == BREAK) { - return addr; - } else if (behavior == BREAK_TRUE || behavior == BREAK_FALSE) { - boolean b=Util.toBoolean(context.pop()); - if (behavior == BREAK_FALSE && !b) { - return addr; - } else if (behavior == BREAK_TRUE && b) { - return addr; - } - } - - return this.getNextAddress(); - } - return -1; - } - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/BreakDescriptor.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/BreakDescriptor.java deleted file mode 100644 index 4e96604..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/BreakDescriptor.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ - -package com.diosay.otpl.runtime.opcodes; - -import com.diosay.otpl.runtime.ExecutionContext; -import com.diosay.otpl.runtime.OpCode; -import com.diosay.otpl.runtime.OpcodeType; -import java.io.OutputStream; -import java.nio.charset.Charset; - -/** - * 中断指令描述符。 - * 注意:该指令属于辅助指令(属于jmp的代理指令),只用于编译阶段,不具体生成和执行。 - * @author jun - */ -public class BreakDescriptor extends OpCode { - - public OpCode target; - - /** - * true 表示 break ,false 表示 continue。默认 flase。 - */ - public boolean blocked; - - @Override - public OpcodeType getType() { - return OpcodeType.brd; - } - - @Override - public void compile(OutputStream output, Charset encoding) throws Exception { - Break jmp=new Break(); - jmp.setBehavior(Break.BREAK); - jmp.setTarget(target); - jmp.setAddress(this.getAddress()); - jmp.compile(output, encoding); - } - - @Override - public int execute(ExecutionContext context) throws Exception { - throw new UnsupportedOperationException("Not supported yet."); - } - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/BreakFalse.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/BreakFalse.java deleted file mode 100644 index 3c160aa..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/BreakFalse.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ - -package com.diosay.otpl.runtime.opcodes; - -import com.diosay.otpl.runtime.ExecutionContext; -import com.diosay.otpl.runtime.OpCode; -import com.diosay.otpl.runtime.OpcodeType; -import java.io.OutputStream; -import java.nio.charset.Charset; - -/** - * 如果 value 为 false、空引用或零,则将控制转移到目标指令。 - * @author jun - */ -@java.lang.Deprecated -public class BreakFalse extends OpCode { - - private OpCode target; - - /** - * 获取条件满足时跳转的地址。 - * @return - */ - public OpCode getTarget(){ - return target; - } - - /** - * 获取条件满足时跳转的地址。 - * @return - */ - public BreakFalse setTarget(OpCode target){ - this.target=target; - return this; - } - - @Override - public final OpcodeType getType() { - return OpcodeType.brf; - } - - @Override - public void compile(OutputStream output,Charset encoding) throws Exception { - throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. - } - - @Override - public int execute(ExecutionContext context) throws Exception { - throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. - } - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Call.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Call.java deleted file mode 100644 index 1088a29..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Call.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ -package com.diosay.otpl.runtime.opcodes; - -import com.diosay.otpl.runtime.ExecutionContext; -import com.diosay.otpl.runtime.OpCode; -import com.diosay.otpl.runtime.OpcodeType; -import java.io.OutputStream; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.Collections; -import mano.util.Utility; - -/** - * 调用一个函数。 - * - * @author jun - */ -public class Call extends OpCode { - - private int len; - - public Call setArgLength(int n) { - len = n; - return this; - } - - @Override - public OpcodeType getType() { - return OpcodeType.call; - } - - @Override - public void compile(OutputStream output, Charset encoding) throws Exception { - output.write(Utility.toBytes(this.getAddress())); - output.write(this.getType().value); - output.write(Utility.toBytes(this.len)); - } - - @Override - public int execute(ExecutionContext context) throws Exception { - - ArrayList args = new ArrayList<>(); - for (int i = 0; i < len; i++) { - args.add(context.pop()); - } - Collections.reverse(args); - Object obj = context.pop(); - Object instance = context.pop(); - if (instance == null) { - throw new RuntimeException("对象实例不能为 null"); - } - if (obj == null) { - throw new UnsupportedOperationException("Null is not a callable object."); - } else if (obj instanceof Method) { - Method method = (Method) obj; - method.setAccessible(true); - try { - - Class[] types = method.getParameterTypes(); - if (args.size() != types.length) { - throw new UnsupportedOperationException("参数不匹配:" + len); - } - Object[] nargs = new Object[types.length]; - for (int i = 0; i < types.length; i++) { - Class clazz = types[i]; - nargs[i] = Utility.cast(clazz, args.get(i)); - } - context.push(method.invoke(instance, nargs)); - } catch (IllegalAccessException | IllegalArgumentException ex) { - throw new RuntimeException(ex); - } catch (InvocationTargetException ex) { - if (ex.getTargetException() != null) { - throw new RuntimeException(ex.getTargetException()); - } - throw new RuntimeException(ex); - } - - } else if (obj instanceof Field) { - Field field = (Field) obj; - field.setAccessible(true); - context.push(field.get(instance)); - } else { - throw new UnsupportedOperationException(obj.getClass() + " is not a callable object."); - } - - return this.getNextAddress(); - } - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/CallBlock.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/CallBlock.java deleted file mode 100644 index 26272ec..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/CallBlock.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ -package com.diosay.otpl.runtime.opcodes; - -import com.diosay.otpl.runtime.ExecutionContext; -import com.diosay.otpl.runtime.Interpreter; -import com.diosay.otpl.runtime.OpCode; -import com.diosay.otpl.runtime.OpcodeType; -import java.io.OutputStream; -import java.nio.charset.Charset; -import mano.util.Utility; - -/** - * 调用一个块。 - * - * @author jun - */ -public class CallBlock extends OpCode { - - private boolean required; - private String name; - - public void required(boolean b) { - required = b; - } - - public void setName(String n) { - name = n; - } - - @Override - public OpcodeType getType() { - return OpcodeType.call_blk; - } - - @Override - public void compile(OutputStream output, Charset encoding) throws Exception { - output.write(Utility.toBytes(this.getAddress())); - output.write(this.getType().value); - if (this.name != null) { - byte[] bytes = this.name.getBytes(encoding); - output.write(Utility.toBytes(bytes.length)); - output.write(bytes); - } else { - throw new UnsupportedOperationException("未设置块名."); - } - output.write(required ? 1 : 0); - } - - @Override - public int execute(ExecutionContext context) throws Exception { - - Block blk = this.getLoader().getBlock(name); - if (blk == null && required) { - throw new UnsupportedOperationException("块 "+name +" 是必须的,但未找到"); - }else if (blk == null){ - return this.getAddress()+1; - } - - try (Interpreter interpreter = context.newInterpreter()) { - interpreter.exec(context, blk.getLoader(),blk.getBeginAddress(),blk.getEndAddress()); - context.freeInterpreter(interpreter); - } - - return this.getAddress()+1; - } - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Callvri.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Callvri.java deleted file mode 100644 index 84bd9f8..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Callvri.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ -package com.diosay.otpl.runtime.opcodes; - -import com.diosay.otpl.runtime.ExecutionContext; -import com.diosay.otpl.runtime.OpCode; -import com.diosay.otpl.runtime.OpcodeType; -import java.io.OutputStream; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import mano.util.Utility; - -/** - * 调用虚函数或内建函数。 - * - * @author jun - */ -public class Callvri extends OpCode { - - private String name; - private int len; - - public Callvri setName(String n) { - name = n; - return this; - } - - public Callvri setArgLength(int n) { - len = n; - return this; - } - - @Override - public OpcodeType getType() { - return OpcodeType.callvri; - } - - @Override - public void compile(OutputStream output, Charset encoding) throws Exception { - output.write(Utility.toBytes(this.getAddress())); - output.write(this.getType().value); - output.write(Utility.toBytes(this.len)); - if (this.name != null) { - byte[] bytes = this.name.getBytes(encoding); - output.write(Utility.toBytes(bytes.length)); - output.write(bytes); - } else { - throw new UnsupportedOperationException("未设置函数名."); - } - } - - @Override - public int execute(ExecutionContext context) throws Exception { - if (this.name == null || "".equals(this.name)) { - throw new UnsupportedOperationException("未设置函数名."); - } - - ArrayList args = new ArrayList<>(); - for (int i = 0; i < len; i++) { - args.add(context.pop()); - } - Collections.reverse(args); - context.push(context.call(this.name, args.toArray())); - return this.getNextAddress(); - } - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/EndHeader.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/EndHeader.java deleted file mode 100644 index eed3de5..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/EndHeader.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ - -package com.diosay.otpl.runtime.opcodes; - -import com.diosay.otpl.runtime.ExecutionContext; -import com.diosay.otpl.runtime.OpCode; -import static com.diosay.otpl.runtime.OpCode.DEBUG; -import com.diosay.otpl.runtime.OpcodeType; -import java.io.OutputStream; -import java.nio.charset.Charset; -import mano.util.Utility; - -/** - * 表示一个文档的开始 - * @author jun - */ -public class EndHeader extends OpCode { - - @Override - public OpcodeType getType() { - return OpcodeType.ehead; - } - - @Override - public void compile(OutputStream output,Charset encoding) throws Exception { - output.write(Utility.toBytes(this.getAddress())); - output.write(this.getType().value); - - } - - @Override - public int execute(ExecutionContext context) throws Exception { - //nothing - return this.getAddress()+1; - } - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/EndOfFile.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/EndOfFile.java deleted file mode 100644 index a1ae217..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/EndOfFile.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ - -package com.diosay.otpl.runtime.opcodes; - -import com.diosay.otpl.runtime.ExecutionContext; -import com.diosay.otpl.runtime.OpCode; -import static com.diosay.otpl.runtime.OpCode.DEBUG; -import com.diosay.otpl.runtime.OpcodeType; -import java.io.OutputStream; -import java.nio.charset.Charset; -import mano.util.Utility; - -/** - * 表示一个文档的结束。 - * @author jun - */ -public class EndOfFile extends OpCode { - - @Override - public OpcodeType getType() { - return OpcodeType.abort; - } - - @Override - public void compile(OutputStream output, Charset encoding) throws Exception { - output.write(Utility.toBytes(this.getAddress())); - output.write(this.getType().value); - - } - - @Override - public int execute(ExecutionContext context) throws Exception { - //nothing - return 0; - } - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Include.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Include.java deleted file mode 100644 index 10d7a75..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Include.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Project. All rights reserved. - * - * See more http://mano.diosay.com/ - * - */ - -package com.diosay.otpl.runtime.opcodes; - -import com.diosay.otpl.runtime.CodeLoader; -import com.diosay.otpl.runtime.ExecutionContext; -import com.diosay.otpl.runtime.Interpreter; -import com.diosay.otpl.runtime.OpCode; -import com.diosay.otpl.runtime.OpcodeType; -import java.io.File; -import java.io.OutputStream; -import java.nio.charset.Charset; -import mano.util.Utility; - -/** - * - * @author junhwong - */ -public class Include extends OpCode { - - @Override - public OpcodeType getType() { - return OpcodeType.inc; - } - - @Override - public void compile(OutputStream output, Charset encoding) throws Exception { - output.write(Utility.toBytes(this.getAddress())); - output.write(this.getType().value); - } - - @Override - public int execute(ExecutionContext context) throws Exception { - - Object obj=context.pop(); - if(obj==null){ - throw new mano.InvalidOperationException("未设置文件名称"); - } - String filename=obj.toString().replace("\\", "/"); - - if(filename.startsWith("~/")){ - filename=Utility.toPath(context.getBasedir(), filename.substring(2)).toString(); - }else if(filename.startsWith("/")){ - if(this.getLoader()==null || this.getLoader().getSource()==null){ - throw new mano.InvalidOperationException("当前代码未关联加载器或不是执行的文件。"); - } - filename=Utility.toPath(this.getLoader().getSource().getParent(), filename.substring(1)).toString(); - } - - try (Interpreter interpreter = context.newInterpreter()) { - interpreter.exec(context, new File(filename)); - context.freeInterpreter(interpreter); - } - return this.getAddress()+1; - } - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Layout.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Layout.java deleted file mode 100644 index ed9f4a8..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Layout.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ - -package com.diosay.otpl.runtime.opcodes; - -import com.diosay.otpl.runtime.CodeLoader; -import com.diosay.otpl.runtime.ExecutionContext; -import com.diosay.otpl.runtime.Interpreter; -import com.diosay.otpl.runtime.OpCode; -import com.diosay.otpl.runtime.OpcodeType; -import java.io.File; -import java.io.OutputStream; -import java.nio.charset.Charset; -import mano.util.Utility; - -/** - * 执行一个文档 - * @author jun - */ -public class Layout extends OpCode { - - @Override - public OpcodeType getType() { - return OpcodeType.doc; - } - - @Override - public void compile(OutputStream output, Charset encoding) throws Exception { - output.write(Utility.toBytes(this.getAddress())); - output.write(this.getType().value); - } - - @Override - public int execute(ExecutionContext context) throws Exception { - - Object obj=context.pop(); - if(obj==null){ - throw new mano.InvalidOperationException("未设置文件名称"); - } - String filename=obj.toString().replace("\\", "/"); - - if(filename.startsWith("~/")){ - filename=Utility.toPath(context.getBasedir(), filename.substring(2)).toString(); - }else if(filename.startsWith("/")){ - if(this.getLoader()==null || this.getLoader().getSource()==null){ - throw new mano.InvalidOperationException("当前代码未关联加载器或不是执行的文件。"); - } - filename=Utility.toPath(this.getLoader().getSource().getParent(), filename.substring(1)).toString(); - } - - try (Interpreter interpreter = context.newInterpreter()) { - this.getLoader().parent=context.getLoader(new File(filename), interpreter); - this.getLoader().parent.pageAddr=this.getAddress()+1; - this.getLoader().parent.child=this.getLoader();//TODO:循环引用 - interpreter.exec(context, this.getLoader().parent); - context.freeInterpreter(interpreter); - } - return this.getAddress()+1; - } - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/LoadConst.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/LoadConst.java deleted file mode 100644 index 4b9430e..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/LoadConst.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ -package com.diosay.otpl.runtime.opcodes; - -import com.diosay.otpl.runtime.ExecutionContext; -import com.diosay.otpl.runtime.OpCode; -import com.diosay.otpl.runtime.OpcodeType; -import java.io.OutputStream; -import java.nio.charset.Charset; -import mano.util.Utility; - -/** - * 载入常量 - * - * @author jun - */ -public class LoadConst extends OpCode { - - public static byte NULL = 0; - public static byte FALSE = 1; - public static byte TRUE = 2; - private byte value; - - public LoadConst setValue(byte val) { - this.value = val; - return this; - } - - @Override - public OpcodeType getType() { - return OpcodeType.ldc; - } - - @Override - public void compile(OutputStream output, Charset encoding) throws Exception { - output.write(Utility.toBytes(this.getAddress())); - output.write(this.getType().value); - output.write(value); - } - - @Override - public int execute(ExecutionContext context) throws Exception { - if (value == NULL) { - context.push(null); - } else if (value == FALSE) { - context.push(false); - } - else if (value == TRUE) { - context.push(true); - } else { - throw new java.lang.RuntimeException("常量类型未定义:" + value); - } - return this.getNextAddress(); - } - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/LoadLong.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/LoadLong.java deleted file mode 100644 index d08b277..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/LoadLong.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ - -package com.diosay.otpl.runtime.opcodes; - -import com.diosay.otpl.runtime.ExecutionContext; -import com.diosay.otpl.runtime.OpCode; -import static com.diosay.otpl.runtime.OpCode.DEBUG; -import com.diosay.otpl.runtime.OpcodeType; -import java.io.OutputStream; -import java.nio.charset.Charset; -import mano.util.Utility; - -/** - * 载入一个整数 - * @author jun - */ -public class LoadLong extends OpCode { - - private long value; - public LoadLong setValue(long val){ - this.value=val; - return this; - } - - @Override - public OpcodeType getType() { - return OpcodeType.ldu; - } - - @Override - public void compile(OutputStream output, Charset encoding) throws Exception { - output.write(Utility.toBytes(this.getAddress())); - output.write(this.getType().value); - output.write(Utility.toBytes(value)); - - } - - @Override - public int execute(ExecutionContext context) throws Exception { - context.push(value); - return this.getAddress()+1; - } -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/LoadMember.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/LoadMember.java deleted file mode 100644 index f3ef747..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/LoadMember.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ -package com.diosay.otpl.runtime.opcodes; - -import com.diosay.otpl.runtime.ExecutionContext; -import com.diosay.otpl.runtime.OpCode; -import com.diosay.otpl.runtime.OpcodeType; -import java.io.OutputStream; -import java.lang.reflect.Field; -import java.lang.reflect.Member; -import java.lang.reflect.Method; -import java.nio.charset.Charset; -import mano.util.Utility; - -/** - * 载入一个成员方法。 - * - * @author jun - */ -public class LoadMember extends OpCode { - - private String name; - private int len; - - public LoadMember setName(String n) { - name = n; - return this; - } - - public LoadMember setArgLength(int n) { - len = n; - return this; - } - - @Override - public OpcodeType getType() { - return OpcodeType.ldm; - } - - @Override - public void compile(OutputStream output, Charset encoding) throws Exception { - output.write(Utility.toBytes(this.getAddress())); - output.write(this.getType().value); - output.write(Utility.toBytes(this.len)); - if (this.name != null) { - byte[] bytes = this.name.getBytes(encoding); - output.write(Utility.toBytes(bytes.length)); - output.write(bytes); - } else { - throw new UnsupportedOperationException("未设置函数名."); - } - } - - @Override - public int execute(ExecutionContext context) throws Exception { - - Object obj = context.pop(); - if (obj == null) { - context.push(null); - return this.getNextAddress(); - } - Class clazz = obj.getClass(); - Member member = null; - try { - for (Method m : clazz.getMethods()) { - if (m.getName().equalsIgnoreCase(name) && m.getParameterCount() == len) { - member = m; - break; - } - } - } catch (Exception ex) { - } - - if (member == null) { - StringBuilder sb = new StringBuilder(name); - sb.setCharAt(0, Character.toUpperCase(sb.charAt(0))); - sb.insert(0, "get");//getXxxx - String tmp = sb.toString(); - try { - for (Method m : clazz.getMethods()) { - if (m.getName().equalsIgnoreCase(tmp) && m.getParameterCount() == len) { - member = m; - break; - } - } - } catch (Exception ex) { - } - } - if (member == null) { - try { - for (Method m : clazz.getMethods()) { - if (m.getName().equalsIgnoreCase(name) && m.getParameterCount() == len) { - member = m; - break; - } - } - } catch (Exception ex) { - } - } - if (member == null && len == 0) { - try { - for (Field m : clazz.getFields()) { - if (m.getName().equalsIgnoreCase(name)) { - member = m; - break; - } - } - } catch (Exception ex) { - } - } - - if (member == null) { - throw new UnsupportedOperationException("指定类成员未找到或未定义:" + name); - } - context.push(member); - - return this.getNextAddress(); - } - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/LoadNull.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/LoadNull.java deleted file mode 100644 index c634e31..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/LoadNull.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ - -package com.diosay.otpl.runtime.opcodes; - -import com.diosay.otpl.runtime.ExecutionContext; -import com.diosay.otpl.runtime.OpCode; -import com.diosay.otpl.runtime.OpcodeType; -import java.io.OutputStream; -import java.nio.charset.Charset; -import mano.util.Utility; - -/** - * 载入空值 - * @author jun - */ -@java.lang.Deprecated -public class LoadNull extends OpCode { - - @Override - public OpcodeType getType() { - return OpcodeType.nil; - } - - @Override - public void compile(OutputStream output, Charset encoding) throws Exception { - output.write(Utility.toBytes(this.getAddress())); - output.write(this.getType().value); - } - - @Override - public int execute(ExecutionContext context) throws Exception { - context.push(null); - return this.getAddress()+1; - } - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/LoadReal.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/LoadReal.java deleted file mode 100644 index 477a0b8..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/LoadReal.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ - -package com.diosay.otpl.runtime.opcodes; - -import com.diosay.otpl.runtime.ExecutionContext; -import com.diosay.otpl.runtime.OpCode; -import static com.diosay.otpl.runtime.OpCode.DEBUG; -import com.diosay.otpl.runtime.OpcodeType; -import java.io.OutputStream; -import java.nio.charset.Charset; -import mano.util.Utility; - -/** - * 载入一个小数 - * @author jun - */ -public class LoadReal extends OpCode { - - private double value; - public void setValue(double val){ - this.value=val; - } - - @Override - public OpcodeType getType() { - return OpcodeType.ldr; - } - - @Override - public void compile(OutputStream output, Charset encoding) throws Exception { - output.write(Utility.toBytes(this.getAddress())); - output.write(this.getType().value); - output.write(Utility.toBytes(value)); - - } - - @Override - public int execute(ExecutionContext context) throws Exception { - context.push(value); - return this.getAddress()+1; - } - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/LoadString.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/LoadString.java deleted file mode 100644 index 6a811df..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/LoadString.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ -package com.diosay.otpl.runtime.opcodes; - -import com.diosay.otpl.runtime.ExecutionContext; -import com.diosay.otpl.runtime.OpCode; -import static com.diosay.otpl.runtime.OpCode.DEBUG; -import com.diosay.otpl.runtime.OpcodeType; -import java.io.OutputStream; -import java.nio.charset.Charset; -import mano.util.Utility; - -/** - * 载入字符串 - * - * @author jun - */ -public class LoadString extends OpCode { - - private String str; - public void setContent(String s) { - str = s; - } - - public String getContent() { - return str; - } - - @Override - public OpcodeType getType() { - return OpcodeType.ldstr; - } - - @Override - public void compile(OutputStream output, Charset encoding) throws Exception { - output.write(Utility.toBytes(this.getAddress())); - output.write(this.getType().value); - if (this.getContent() == null) { - output.write(Utility.toBytes(0)); - } else { - byte[] bytes = this.getContent().getBytes(encoding); - output.write(Utility.toBytes(bytes.length)); - output.write(bytes); - } - } - - @Override - public int execute(ExecutionContext context) throws Exception { - context.push(this.getContent()); - return this.getAddress()+1; - } - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/LoadTrue.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/LoadTrue.java deleted file mode 100644 index c22cbde..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/LoadTrue.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ - -package com.diosay.otpl.runtime.opcodes; - -import com.diosay.otpl.runtime.ExecutionContext; -import com.diosay.otpl.runtime.OpCode; -import com.diosay.otpl.runtime.OpcodeType; -import java.io.OutputStream; -import java.nio.charset.Charset; - -/** - * 载入常量 true - * @author jun - */ -public class LoadTrue extends OpCode { - - @Override - public OpcodeType getType() { - return OpcodeType.ldc;//TODO - } - - @Override - public void compile(OutputStream output, Charset encoding) throws Exception { - throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. - } - - @Override - public int execute(ExecutionContext context) throws Exception { - throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. - } - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/LoadVariable.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/LoadVariable.java deleted file mode 100644 index 95ce7e1..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/LoadVariable.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ -package com.diosay.otpl.runtime.opcodes; - -import com.diosay.otpl.runtime.ExecutionContext; -import com.diosay.otpl.runtime.OpCode; -import com.diosay.otpl.runtime.OpcodeType; -import java.io.OutputStream; -import java.nio.charset.Charset; -import mano.util.Utility; - -/** - * 载入一个变量 - * @author jun - */ -public class LoadVariable extends OpCode { - - private String name; - - /** - * 设置变量名 - * @param n - */ - public LoadVariable setName(String n) { - this.name = n; - return this; - } - - @Override - public OpcodeType getType() { - return OpcodeType.ldv; - } - - @Override - public void compile(OutputStream output, Charset encoding) throws Exception { - output.write(Utility.toBytes(this.getAddress())); - output.write(this.getType().value); - if (this.name != null) { - byte[] bytes = this.name.getBytes(encoding); - output.write(Utility.toBytes(bytes.length)); - output.write(bytes); - } else { - throw new UnsupportedOperationException("未设置变量名."); - } - } - - @Override - public int execute(ExecutionContext context) throws Exception { - context.push(context.get(name)); - return this.getAddress() + 1; - } - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Nop.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Nop.java deleted file mode 100644 index c63ba59..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Nop.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ -package com.diosay.otpl.runtime.opcodes; - -import com.diosay.otpl.runtime.ExecutionContext; -import com.diosay.otpl.runtime.OpCode; -import com.diosay.otpl.runtime.OpcodeType; -import java.io.OutputStream; -import java.nio.charset.Charset; -import mano.util.Utility; - -/** - * 表示一个占位,不执行任何操作。通常用作 label 使用。 - * @author jun - */ -public class Nop extends OpCode { - - public Nop(){} - public Nop(int line){ - this.setSourceLine(line); - } - - /** - * 编译的辅助标记。 - */ - public String mark; - - @Override - public final OpcodeType getType() { - return OpcodeType.nop; - } - - @Override - public void compile(OutputStream output,Charset encoding) throws Exception { - - output.write(Utility.toBytes(this.getAddress())); - output.write(this.getType().value); - - - } - - @Override - public int execute(ExecutionContext context) throws Exception { - //nothing - return this.getAddress()+1; - } - - - - - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Operator.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Operator.java deleted file mode 100644 index 594005e..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Operator.java +++ /dev/null @@ -1,257 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ -package com.diosay.otpl.runtime.opcodes; - -import com.diosay.otpl.runtime.ExecutionContext; -import com.diosay.otpl.runtime.OpCode; -import com.diosay.otpl.runtime.OpcodeType; -import java.io.OutputStream; -import java.nio.charset.Charset; -import mano.util.Utility; - -/** - * 操作符 - * - * @author jun - */ -public class Operator extends OpCode { - - public static final byte /** - * 加 - */ - ADD = 1, - /** - * 减 - */ - SUB = 2, - /** - * 乘 - */ - MUL = 3, - /** - * 除 - */ - DIV = 4, - /** - * 模 - */ - MOD = 5, - /** - * 等于 - */ - EQ = 6, - /** - * 不等于 - */ - NE = 7, - /** - * 大于 - */ - GT = 8, - /** - * 大于等于 - */ - GE = 9, - /** - * 小于 - */ - LT = 10, - /** - * 小于等于 - */ - LE = 11, - /** - * 与 - */ - AND = 12, - /** - * 或 - */ - OR = 13, - /** - * 非 - */ - NOT = 14, - /** - * 负 - */ - NEG = 15; - - private byte operator; - public Operator setOperator(byte op){ - this.operator=op; - return this; - } - public static Operator parse(byte operator) { - switch (operator) { - case Operator.ADD: - case Operator.AND: - case Operator.DIV: - case Operator.EQ: - case Operator.GE: - case Operator.GT: - case Operator.LE: - case Operator.LT: - case Operator.MOD: - case Operator.MUL: - case Operator.NE: - case Operator.NOT: - case Operator.OR: - case Operator.SUB: - break; - } - return null; - } - - @Override - public OpcodeType getType() { - return OpcodeType.op; - } - - @Override - public void compile(OutputStream output, Charset encoding) throws Exception { - output.write(Utility.toBytes(this.getAddress())); - output.write(this.getType().value); - output.write(operator); - } - - private boolean toBool(Object obj) { - if (obj == null) { - return false; - } - - try { - return Utility.cast(Boolean.class, obj); - } catch (Exception ex) { - try { - return Utility.cast(Double.class, obj) == 0 ? false : true; - } catch (Exception ex2) { - return true; - } - } - } - - @Override - public int execute(ExecutionContext context) throws Exception { - - switch (this.operator) { - case Operator.ADD: { - Object left = context.pop(); - Object right = context.pop(); - context.push(Utility.asNumber(Math.max(Utility.geTypeCode(left.getClass()), - Utility.geTypeCode(right.getClass())), - Utility.toDouble(left) + Utility.toDouble(right))); - break; - } - case Operator.AND: { - context.push(this.toBool(context.pop()) && this.toBool(context.pop())); - break; - } - case Operator.DIV: { - Object left = context.pop(); - Object right = context.pop(); - context.push(Utility.asNumber(Math.max(Utility.geTypeCode(left.getClass()), - Utility.geTypeCode(right.getClass())), - Utility.toDouble(left) / Utility.toDouble(right))); - break; - } - case Operator.EQ: { - Object left = context.pop(); - Object right = context.pop(); - if (left != null) { - context.push(left.equals(right)); - } else if (right != null) { - context.push(right.equals(left)); - } else { - context.push(right == left); - } - break; - } - case Operator.GE: { - Object right = context.pop(); - Object left = context.pop(); - context.push(Utility.toDouble(left) >= Utility.toDouble(right)); - break; - } - case Operator.GT:{ - Object right = context.pop(); - Object left = context.pop(); - context.push(Utility.toDouble(left) > Utility.toDouble(right)); - break; - } - case Operator.LE:{ - Object right = context.pop(); - Object left = context.pop(); - context.push(Utility.toDouble(left) <= Utility.toDouble(right)); - break; - } - case Operator.LT:{ - Object right = context.pop(); - Object left = context.pop(); - context.push(Utility.toDouble(left) < Utility.toDouble(right)); - break; - } - case Operator.MOD: { - Object left = context.pop(); - Object right = context.pop(); - context.push(Utility.asNumber(Math.max(Utility.geTypeCode(left.getClass()), - Utility.geTypeCode(right.getClass())), - Utility.toDouble(left) % Utility.toDouble(right))); - break; - } - case Operator.MUL: { - Object left = context.pop(); - Object right = context.pop(); - context.push(Utility.asNumber(Math.max(Utility.geTypeCode(left.getClass()), - Utility.geTypeCode(right.getClass())), - Utility.toDouble(left) * Utility.toDouble(right))); - break; - } - case Operator.NE: { - Object left = context.pop(); - Object right = context.pop(); - if (left != null) { - context.push(!left.equals(right)); - } else if (right != null) { - context.push(!right.equals(left)); - } else { - context.push(right != left); - } - break; - } - case Operator.NOT:{ - context.push(!this.toBool(context.pop())); - break; - }case Operator.NEG:{ - String obj=context.pop().toString(); - if(obj.indexOf('.')>0){ - context.push(-Utility.toDouble(obj)); - }else{ - context.push(-Utility.toLong(obj)); - } - - break; - } - case Operator.OR: { - context.push(this.toBool(context.pop()) || this.toBool(context.pop())); - break; - } - case Operator.SUB: { - Object right = context.pop(); - Object left = context.pop(); - context.push(Utility.asNumber(Math.max(Utility.geTypeCode(left.getClass()), - Utility.geTypeCode(right.getClass())), - Utility.toDouble(left) - Utility.toDouble(right))); - break; - } - } - - return this.getAddress() + 1; - } - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Peek.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Peek.java deleted file mode 100644 index b612627..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Peek.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ - -package com.diosay.otpl.runtime.opcodes; - -import com.diosay.otpl.runtime.ExecutionContext; -import com.diosay.otpl.runtime.OpCode; -import com.diosay.otpl.runtime.OpcodeType; -import java.io.OutputStream; -import java.nio.charset.Charset; -import mano.util.Utility; - -/** - * 取出元素 - * @author jun - */ -public class Peek extends OpCode{ - - @Override - public OpcodeType getType() { - return OpcodeType.peek; - } - - @Override - public void compile(OutputStream output, Charset encoding) throws Exception { - output.write(Utility.toBytes(this.getAddress())); - output.write(this.getType().value); - } - - @Override - public int execute(ExecutionContext context) throws Exception { - context.push(context.peek()); - return this.getAddress()+1; - } - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Pop.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Pop.java deleted file mode 100644 index e5f65b1..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Pop.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ -package com.diosay.otpl.runtime.opcodes; - -import com.diosay.otpl.runtime.ExecutionContext; -import com.diosay.otpl.runtime.OpCode; -import com.diosay.otpl.runtime.OpcodeType; -import java.io.OutputStream; -import java.nio.charset.Charset; -import mano.util.Utility; - -/** - * 弹出元素 - * - * @author jun - */ -public class Pop extends OpCode { - - @Override - public OpcodeType getType() { - return OpcodeType.pop; - } - - @Override - public void compile(OutputStream output, Charset encoding) throws Exception { - output.write(Utility.toBytes(this.getAddress())); - output.write(this.getType().value); - } - - @Override - public int execute(ExecutionContext context) throws Exception { - context.pop(); - return this.getAddress() + 1; - } - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Print.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Print.java deleted file mode 100644 index b48e38f..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/Print.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ -package com.diosay.otpl.runtime.opcodes; - -import com.diosay.otpl.runtime.ExecutionContext; -import com.diosay.otpl.runtime.OpCode; -import com.diosay.otpl.runtime.OpcodeType; -import java.io.OutputStream; -import java.nio.charset.Charset; -import mano.util.Utility; - -/** - * 打印对象 - * - * @author jun - */ -public class Print extends OpCode { - - private boolean filtrable; - - /** - * 设置一否过滤,默认真 - * - * @param b - */ - public void setFiltrable(boolean b) { - filtrable = b; - } - - public boolean getFiltrable() { - return filtrable; - } - - @Override - public OpcodeType getType() { - return OpcodeType.prt; - } - - @Override - public void compile(OutputStream output, Charset encoding) throws Exception { - output.write(Utility.toBytes(this.getAddress())); - output.write(this.getType().value); - output.write(getFiltrable() ? 1 : 0); - } - - @Override - public int execute(ExecutionContext context) throws Exception { - - Object obj=context.pop(); - if(obj!=null){ - context.write(getFiltrable(),obj); - } - - return this.getAddress()+1; - - } - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/PrintString.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/PrintString.java deleted file mode 100644 index fa44ddb..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/PrintString.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ -package com.diosay.otpl.runtime.opcodes; - -import com.diosay.otpl.runtime.ExecutionContext; -import com.diosay.otpl.runtime.OpCode; -import com.diosay.otpl.runtime.OpcodeType; -import java.io.OutputStream; -import java.nio.charset.Charset; -import mano.util.Utility; - -/** - * 打印字符串 - * - * @author jun - */ -public class PrintString extends OpCode { - - private byte[] array; - private int offset; - private int length; - private String str; - - /** - * 设置字符串 - * - * @param s - */ - public void setString(String s) { - array = null; - str = s; - } - - /** - * 设置字节组 - * - * @param array - * @param offset - * @param length - */ - public void setBytes(byte[] array, int offset, int length) { - str = null; - this.array = array; - this.offset = offset; - this.length = length; - } - - @Override - public OpcodeType getType() { - return OpcodeType.ptstr; - } - - @Override - public void compile(OutputStream output, Charset encoding) throws Exception { - if (array == null && str != null) { - array = str.getBytes(encoding); - offset = 0; - length = array.length; - } - if (array == null) { - throw new UnsupportedOperationException("array required."); - } - - output.write(Utility.toBytes(this.getAddress())); - output.write(this.getType().value); - output.write(Utility.toBytes(length)); - output.write(array, offset, length); - } - - @Override - public int execute(ExecutionContext context) throws Exception { - if (array == null && str != null) { - array = str.getBytes(context.outputEncoding()); - offset = 0; - length = array.length; - } else if (!context.inputEncoding().equals(context.outputEncoding())) { - str = new String(array, offset, length, context.inputEncoding()); - array = str.getBytes(context.outputEncoding()); - offset = 0; - length = array.length; - } - - context.write(false, array, offset, length); - return this.getAddress() + 1; - } - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/SetVariable.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/SetVariable.java deleted file mode 100644 index 7a9cfd8..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/SetVariable.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ - -package com.diosay.otpl.runtime.opcodes; - -import com.diosay.otpl.runtime.ExecutionContext; -import com.diosay.otpl.runtime.OpCode; -import com.diosay.otpl.runtime.OpcodeType; -import java.io.OutputStream; -import java.nio.charset.Charset; -import mano.util.Utility; - -/** - * 设置变量值 - * @author jun - */ -public class SetVariable extends OpCode { - - private String name; - - /** - * 设置变量名 - * @param n - */ - public SetVariable setName(String n) { - this.name = n; - return this; - } - public String getName(){ - return name; - } - - @Override - public OpcodeType getType() { - return OpcodeType.stv; - } - - @Override - public void compile(OutputStream output, Charset encoding) throws Exception { - output.write(Utility.toBytes(this.getAddress())); - output.write(this.getType().value); - if (this.name != null) { - byte[] bytes = this.name.getBytes(encoding); - output.write(Utility.toBytes(bytes.length)); - output.write(bytes); - } else { - throw new UnsupportedOperationException("未设置变量名."); - } - } - - @Override - public int execute(ExecutionContext context) throws Exception { - context.set(name,context.pop()); - return this.getAddress() + 1; - } - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/SourceLineNumber.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/SourceLineNumber.java deleted file mode 100644 index 5e271f7..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl/runtime/opcodes/SourceLineNumber.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ -package com.diosay.otpl.runtime.opcodes; - -import com.diosay.otpl.runtime.ExecutionContext; -import com.diosay.otpl.runtime.OpCode; -import com.diosay.otpl.runtime.OpcodeType; -import java.io.OutputStream; -import java.nio.charset.Charset; -import mano.util.Utility; - -/** - * 定义一个源代码行号。 - * - * @author jun - */ -public class SourceLineNumber extends OpCode { - - private int lineNumber; - - public SourceLineNumber setValue(int line) { - lineNumber = line; - return this; - } - - @Override - public OpcodeType getType() { - return OpcodeType.sl; - } - - @Override - public void compile(OutputStream output, Charset encoding) throws Exception { - output.write(Utility.toBytes(this.getAddress())); - output.write(this.getType().value); - output.write(Utility.toBytes(lineNumber)); - } - - @Override - public int execute(ExecutionContext context) throws Exception { - context.setCurrentSourceLine(lineNumber); - return this.getNextAddress(); - } - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl4j/SourceLine.java b/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl4j/SourceLine.java deleted file mode 100644 index f8919fc..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/com/diosay/otpl4j/SourceLine.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. - */ -package com.diosay.otpl4j; - -/** - * - * @author jun - */ -public class SourceLine { - - private int line; - private StringBuilder source; - private String filename(){ - //layout=5555 - //is_layout=0|1 - return null; - } - - class PlainText{ - SourceLine source; - - int offset; - int length; - - } - - - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/mano/otpl/Block.java b/del/mano-server-projects/open-tpl/src/main/java/mano/otpl/Block.java deleted file mode 100644 index 7e5be83..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/mano/otpl/Block.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ -package mano.otpl; - -import java.util.LinkedList; -import java.util.NoSuchElementException; - -/** - * 表示一个块元素 - * @author jun - */ -public class Block extends Node { - - private LinkedList nodes; - private LinkedList inlines; - - protected Block(Parser p, int type, String s) { - super(p, type, s); - nodes = new LinkedList<>(); - inlines = new LinkedList<>(); - } - - @Override - public final boolean isBlock() { - return true; - } - - public LinkedList getNodes() { - return this.nodes; - } - - public LinkedList getInlines() { - return this.inlines; - } - - private boolean closed; - - protected void close() { - this.closed = true; - } - int[] endTypes; - - public boolean canEnd(Node node) { - if (endTypes == null) { - return false; - } - for (int t : endTypes) { - if (node.getNodeType() == t) { - return true; - } - } - return false; - } - - public static Block create(Parser parser, int type, String source, int... endTypes) { - Block result = new Block(parser, type, source); - result.endTypes = endTypes; - return result; - } - - public Block append(Node node) { - - if (this.canEnd(node)) { - this.close(); - if (node instanceof End) { - return this.getParent(); - } - } - if (node.getNodeType() == Node.LEXS_PLAIN) { //合并字符串 - Node last = null; - try { - last = this.getNodes().getLast(); - } catch (NoSuchElementException e) { - } - if (last != null && last.getNodeType() == Node.LEXS_PLAIN) { - last = this.getNodes().removeLast(); - last.source += node.source; - node = last; - } - } - if (this.closed) { - node.setParent(this.getParent()); //设置父级 - node.setPrevNode(this); - this.getParent().getNodes().add(node); - return (Block) node; - } else { - node.setParent(this); //设置父级 - if (!this.getNodes().isEmpty()) { //设置上个节点 - node.setPrevNode(this.getNodes().getLast()); - } - } - this.getNodes().add(node); - if (node.isBlock()) { - return (Block) node; - } else { - return this; - } - } - - @Override - public void parse() { - this.parser.parse(this); - } - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/mano/otpl/Document.java b/del/mano-server-projects/open-tpl/src/main/java/mano/otpl/Document.java deleted file mode 100644 index fc6528e..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/mano/otpl/Document.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. - */ -package mano.otpl; - -import java.util.Map; -import java.util.NoSuchElementException; -import mano.otpl.Block; -import mano.otpl.Node; -import mano.util.NameValueCollection; - -/** - * - * @author jun - */ -public class Document extends Block { - - Block current; - public Node Layout; - public Node Body; - public Map blocks; - - public Document(Parser p) { - super(p, Node.LEXB_DOM, null); - this.current = this; - blocks = new NameValueCollection<>(); - } - - @Override - public Block append(Node node) { - - if (current == this) { - if (node.getNodeType() == Node.LEXS_PLAIN) { //合并字符串 - Node last = null; - try { - last = this.getNodes().getLast(); - } catch (NoSuchElementException e) { - } - if (last != null && last.getNodeType() == Node.LEXS_PLAIN) { - last = this.getNodes().removeLast(); - last.source += node.source; - node = last; - } - } - node.setParent(this); //设置父级 - if (!this.getNodes().isEmpty()) { //设置上个节点 - node.setPrevNode(this.getNodes().getLast()); - } - this.getNodes().add(node); - if (node.isBlock()) { - current = (Block) node; - if (node.getNodeType() == Node.LEXB_BLOCK) { - blocks.put(node.getSource(), current); - } - } - } else { - if (current.getNodeType() == Node.LEXB_BLOCK && node.getNodeType() == Node.LEXB_BLOCK) { - this.parser.reportError("block 不允许嵌套"); - } - current = current.append(node); - if (node.getNodeType() == Node.LEXB_BLOCK) { - blocks.put(node.getSource(), current); - } - } - return current; - } - - @Override - public boolean canEnd(Node node) { - - return false; - } - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/mano/otpl/End.java b/del/mano-server-projects/open-tpl/src/main/java/mano/otpl/End.java deleted file mode 100644 index 37959e1..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/mano/otpl/End.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. - */ - -package mano.otpl; - -/** - * - * @author jun - */ -public class End extends Span { - protected End(Parser p, int type, String s) { - super(p, type, s); - } - - public static End create(Parser parser, int type) { - End result=new End(parser,type,null); - return result; - } -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/mano/otpl/Node.java b/del/mano-server-projects/open-tpl/src/main/java/mano/otpl/Node.java deleted file mode 100644 index 8c673af..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/mano/otpl/Node.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ -package mano.otpl; - -/** - * 表示一个元素节点。 - * @author jun - */ -public abstract class Node { - - public static final int NODE_UNDEFINED = 0, - LEXB_DOM = 1, - LEXS_PLAIN = 2, - LEXS_PRINT = 3, - LEXB_IF = 4, - LEXB_ELIF = 5, - LEXB_ELSE = 6, - LEXS_ENDIF = 7, - LEXS_RAW = 8, - LEXS_CCALL = 9, - LEXS_CALL = 10, - LEXB_FOR = 11, - LEXS_ENDFOR = 12, - LEXB_EACH = 13, - LEXS_ENDEACH = 14, - LEXB_WHILE = 15, - LEXS_ENDWHILE = 16, - LEXS_BREAK = 17, - LEXS_CONTINUE = 18, - LEXS_EXIT = 19, - LEXS_INCLUDE = 20, - LEXS_LAYOUT = 21, - LEXB_BLOCK = 22, - LEXS_ENDBLOCK = 23, - LEXS_BODY = 24, - LEXS_SET = 25, - LEXS_PLACE = 26; - - private String nodeName; - private String fileName; - private long lineNo; - private Block parent; - private int indent = 0; - private int nodeType; - public static char INDENT_CHAR = ' '; - protected String source; - protected final Parser parser; - protected Node prevNode; - protected Node nextNode; - protected Node(Parser p, int type, String s) { - parser = p; - this.nodeType = type; - this.fileName = parser.getSourceName(); - this.lineNo = parser.getCurrentLine(); - source = s; - } - - public Block getParent() { - return parent; - } - - public void setParent(Block node) { - this.indent = node.getIndent() + (node instanceof Document ? 0 : 4); - parent = node; - } - - public int getIndent() { - return indent; - } - - public String getName() { - return nodeName; - } - - public String getSourceFilename() { - return fileName; - } - - public String getSource() { - return source; - } - - public long getLine() { - return lineNo; - } - - public abstract boolean isBlock(); - - public int getNodeType(){ - return nodeType; - } - - public Node getPrevNode(){ - return prevNode; - } - - public void setPrevNode(Node node){ - node.nextNode=this; - this.prevNode=node; - } - - public Node getNextNode(){ - return nextNode; - } - - - public abstract void parse(); - - protected void appendIndents(StringBuilder sb) { - for (int i = 0; i < this.getIndent(); i++) { - sb.append(Node.INDENT_CHAR); - } - } - - protected void appendLine(StringBuilder sb) { - sb.append("\r\n"); - } - - public boolean mark=false; -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/mano/otpl/OtplViewEngine.java b/del/mano-server-projects/open-tpl/src/main/java/mano/otpl/OtplViewEngine.java deleted file mode 100644 index a3abf0f..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/mano/otpl/OtplViewEngine.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. - */ -package mano.otpl; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.PrintStream; -import java.util.HashMap; -import java.util.Map; -import java.util.Stack; -import mano.http.HttpContext; -import mano.otpl.emit.EmitParser; -import mano.otpl.emit.Interpreter; -import mano.otpl.emit.OpCode; -import mano.util.LinkedMap; -import mano.util.Utility; -import mano.web.ViewContext; -import mano.web.ViewEngine; - -/** - * - * @author jun - */ -public class OtplViewEngine extends ViewEngine { - - EmitParser parser=new EmitParser(); - Interpreter interpreter = new Interpreter(); - - @Override - public void render(ViewContext service) { - String source = Utility.toPath(this.getViewdir(), service.getPath()).toString(); - String target = Integer.toHexString(this.getViewdir().hashCode()) + "$" + Integer.toHexString(source.hashCode()) + ".otc"; - service.getContext().getApplication().getLogger().debug(source); - File target_file = new File(Utility.toPath(this.getTempdir(), target).toUri()); - OutProxy proxy = new OutProxy(); - proxy.context = service.getContext(); - try { - if (target_file.exists()) { - if (!target_file.delete()) { - service.getContext().getApplication().getLogger().debug("file deleting failed:" + target_file); - } - } - service.getContext().getApplication().getLogger().debug("create file :" + target_file); - if (true) { - target_file.createNewFile(); - - //parser=new EmitParser(); - parser.compile(source, target_file.toString()); - } - for (Map.Entry entry : service.getEntries()) { - proxy.args.put(entry.getKey(), entry.getValue()); - } - interpreter.init(proxy); - interpreter.setOut(proxy); - interpreter.exec(target_file.toString()); - } catch (Exception ex) { - //logger.error(null, ex); - try { - service.getContext().getResponse().write(ex.getMessage()); - } catch (Exception e) { - //logger.error(null, e); - } - } - } - - @Override - public ViewContext createContext(HttpContext context) { - throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. - } - - public static class OutProxy extends OutputStream { - - HttpContext context; - public Stack stack; - public Map args; - - public OutProxy() { - stack = new Stack<>(); - args = new HashMap<>(); - } - - @Override - public void flush() throws IOException { - context.getResponse().flush(); - } - - @Override - public void write(byte[] b, int off, int len) throws IOException { - context.getResponse().write(b, off, len); - } - - @Override - public void write(int b) throws IOException { - context.getResponse().write(new byte[]{(byte) b}, 0, 1); - } - } -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/mano/otpl/Parser.java b/del/mano-server-projects/open-tpl/src/main/java/mano/otpl/Parser.java deleted file mode 100644 index 69b0c4a..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/mano/otpl/Parser.java +++ /dev/null @@ -1,386 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ -package mano.otpl; - -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * - * @author jun - */ -public abstract class Parser { - - protected Parser() { - - } - - protected String filename; - protected java.io.BufferedReader reader; - private long line = 0; - private Map lines; - String leftDelimiter = "{{"; - String rightDelimiter = "}}"; - - public String getSourceName() { - return filename; - } - - public long getCurrentLine() { - return line; - } - - public void open(String file) throws FileNotFoundException,IOException { - java.io.FileInputStream fs = new java.io.FileInputStream(file); - reader = new java.io.BufferedReader(new java.io.InputStreamReader(fs,"utf-8")); - filename = file; - } - - protected boolean isDigital(char c) { - return (c >= 48 && c <= 57); - } - - protected boolean isLetter(char c) { - return (c >= 65 && c <= 90 || c >= 97 && c <= 122); - } - - protected boolean isAlphanumeric(char c) { - return isDigital(c) || isLetter(c); - } - - protected boolean isWhitespace(char c) { - return (c == ' ' || c == '\t'); - } - - public void parse() throws IOException { - line=0; - lines = new HashMap<>(); - dom = new Document(this); - String s; - while ((s = reader.readLine()) != null) { - line++; - lines.put(line, s); - this.findLine(s, 0); - parsePlian("\r\n");////todo: 补足一个回车,因为分析时的消耗 - } - } - - protected void findLine(String line, int index) { - if (line == null || "".equals(line)) { - return; - } - this.findDelimiter(line, index); - - } - - private void findDelimiter(String source, int index) { - int old=index; - String ld = ""; - int start = source.indexOf(ld, index); - if (start < 0) { - ld = leftDelimiter; - rd = rightDelimiter; - start = source.indexOf(ld, index); - } - - if (start > -1) { - - int end = this.parseRange(source, start + ld.length(), ld, rd); - //int next = source.indexOf(leftDelimiter, end); //确认中间是否有分割符 - if (end < 0) { - this.reportError("分割符"); - } - - String tmp=source.substring(start + ld.length(), end).trim(); - if(inLiteral){ - if (assertKeyword("/literal",tmp) > -1) { - inLiteral=false; - } - else{ - parsePlian(source.substring(index, end + rd.length())); - } - } - else{ - parsePlian(source.substring(index, start)); - this.parseMarkup(tmp); - } - this.findLine(source.substring(end + rd.length()), 0); - } else { - parsePlian(source.substring(index)); - } - - } - - protected void parsePlian(String source) { - if (inComment) { - return; - } - dom.append(Span.create(this, Node.LEXS_PLAIN, source)); - } - - protected int parseIdentifier(String source, int index) { - if (source == null || index < 0 || index > source.length() || !this.isLetter(source.charAt(index))) { - return -1; - } - int ori = index; - for (; index < source.length(); index++) { - if (!this.isAlphanumeric(source.charAt(index))) { - break; - } - } - return ori == index ? -1 : index; - } - - protected int parseNumber(String source, int index) { - if (source == null || index < 0 || index > source.length()) { - return -1; - } - int ori = index; - for (; index < source.length(); index++) { - if (!this.isDigital(source.charAt(index))) { - break; - } - } - return ori == index ? -1 : index; - } - - protected int parseRange(String source, int index, String open, String close) { - if (index < 0 || index >= source.length() || open == null || open.length() < 1 || close == null || close.length() < 1) { - return -1; - } - boolean like = open.equals(close); - int matches = 1; - for (; index < source.length(); index++) { - if (source.charAt(index) == '\\') {//转义 - index++; - } else if (!like && source.charAt(index) == open.charAt(0)) {//确定开始 - boolean tmp = true; - for (int i = 0; i < open.length(); i++) { - if (source.charAt(index + i) != open.charAt(i)) { - tmp = false; - break; - } - } - if (tmp) { - index += open.length(); - matches += 1; - } - } else if (source.charAt(index) == close.charAt(0)) {//确定结束 - boolean tmp = true; - for (int i = 0; i < close.length(); i++) { - if (source.charAt(index + i) != close.charAt(i)) { - tmp = false; - break; - } - } - if (tmp) { - matches -= 1; - if (matches == 0) { - return index; - } - index += close.length(); - } - } - } - - return -1; - } - protected Node cnode; - - protected void reportError(String cacuse) { - if (cnode != null) { - cacuse += "," + cnode.getLine() + "(" + cnode.getSourceFilename() + ")"; - } else { - cacuse += "," + this.line + "(" + this.filename + ")"; - } - throw new java.lang.RuntimeException(cacuse); - } - - protected int assertKeyword(String key, String source) { - return assertKeyword(key, source, 0); - } - - protected int assertKeyword(String key, String source, int index) { - if (key == null || key.length() == 0 || source == null || source.length() == 0) { - return -1; - } - boolean tmp = false; - int total = source.length(); - for (; index < total; index++) { - if (!this.isWhitespace(source.charAt(index))) { - break; - } - } - - for (; index < total; index++) { - if (source.charAt(index) == key.charAt(0)) { - tmp = true; - for (int i = 0; i < key.length(); i++) { - if (index + i >= total || source.charAt(index + i) != key.charAt(i)) { - tmp = false; - break; - } - } - if (tmp) { - break; - } else { - index++; - } - } else { - return -1; - } - } - if (tmp) { - return index + key.length(); - } - return -1; - } - protected boolean inLiteral = false; - protected boolean inComment = false; - protected Document dom; - - protected void parseMarkup(String source) { - int index; - if (source.startsWith("/*")) { //块注释结束 - inComment = true; - } else if (source.startsWith("*/")) {//块注释开始 - inComment = false; - } else if (inComment || source.startsWith("//")) { //当前为注释中 - //ignored - } else if ((index = assertKeyword("literal", source)) > -1) { //end if - inLiteral=true; - } else if ((index = assertKeyword("/if", source)) > -1) { //end if - Node node = End.create(this, Node.LEXS_ENDIF); - dom.append(node); - } else if ((index = assertKeyword("/for", source)) > -1) { //end if - Node node = End.create(this, Node.LEXS_ENDFOR); - dom.append(node); - } else if ((index = assertKeyword("/each", source)) > -1) { //end if - Node node = End.create(this, Node.LEXS_ENDEACH); - dom.append(node); - } else if ((index = assertKeyword("/while", source)) > -1) { //end if - Node node = End.create(this, Node.LEXS_ENDWHILE); - dom.append(node); - } else if ((index = assertKeyword("/block", source)) > -1) { //end if - Node node = End.create(this, Node.LEXS_ENDBLOCK); - dom.append(node); - } else if ((index = assertKeyword("block", source)) > -1) { //end if - if ((index = assertKeyword(":", source, index)) < 0) { - this.reportError("语法错误"); - } - int found = this.parseIdentifier(source, index); - if (found < 0) { - this.reportError("非法的标识符"); - } - Node node = Block.create(this, Node.LEXB_BLOCK, source.substring(index, found), Node.LEXS_ENDBLOCK); - dom.append(node); - } else if ((index = assertKeyword("elif", source)) > -1) { //end if - Node node = Block.create(this, Node.LEXB_ELIF, source.substring(index), Node.LEXB_ELIF, Node.LEXB_ELSE, Node.LEXS_ENDIF); - dom.append(node); - } else if ((index = assertKeyword("else", source)) > -1) {//if for each while - Node node = Block.create(this, Node.LEXB_ELSE, source.substring(index), Node.LEXS_ENDFOR, Node.LEXS_ENDIF, Node.LEXS_ENDWHILE,Node.LEXS_ENDEACH); - //Node node = new End(this,"else", source.substring(index)); - dom.append(node); - } else if ((index = assertKeyword("if", source)) > -1) { //if语句 - /*String test = this.parseExpr(s, index); - if (test == null || "".equals(test.trim())) { - this.reportError("syntax error,illegal markup. look like as a if statement but dont found cod"); - }*/ - //Node node = new If(this,"if", source.substring(index)); - Node node = Block.create(this, Node.LEXB_IF, source.substring(index), Node.LEXB_ELIF, Node.LEXB_ELSE, Node.LEXS_ENDIF); - dom.append(node); - } else if ((index = assertKeyword("for", source)) > -1) { //语句 - Node node = Block.create(this, Node.LEXB_FOR, source.substring(index), Node.LEXS_ENDFOR, Node.LEXB_ELSE); - //node.PName=id; - dom.append(node); - } else if ((index = assertKeyword("each", source)) > -1) { //语句 - Node node = Block.create(this, Node.LEXB_EACH, source.substring(index), Node.LEXS_ENDEACH, Node.LEXB_ELSE); - dom.append(node); - } else if ((index = assertKeyword("while", source)) > -1) { //语句 - Node node = Block.create(this, Node.LEXB_WHILE, source.substring(index), Node.LEXS_ENDWHILE, Node.LEXB_ELSE); - dom.append(node); - } else if ((index = assertKeyword("break", source)) > -1) { //语句 - Node node = Span.create(this, Node.LEXS_BREAK, source.substring(index)); - dom.append(node); - } else if ((index = assertKeyword("continue", source)) > -1) { //语句 - Node node = Span.create(this, Node.LEXS_BREAK, source.substring(index)); - dom.append(node); - } else if ((index = assertKeyword("layout", source)) > -1) { //语句 - if (dom.Layout != null) { - this.reportError("不能存在多个 layout 标签."); - } - int tmp = assertKeyword("'", source, index); - if (tmp < 0) { - this.reportError("未设置 layout 路径."); - } - //source=source.substring(tmp); - int end = this.parseRange(source, tmp, "'", "'"); - if (tmp < 0) { - this.reportError("未设置 layout 路径."); - } - - Node node = Span.create(this, Node.LEXS_LAYOUT, source.substring(tmp, end)); - dom.Layout = node; - } else if ((index = assertKeyword("body", source)) > -1) { //语句 - if (dom.Body != null) { - this.reportError("不能存在多个 body 标签."); - } - - Node node = Span.create(this, Node.LEXS_BODY, source.substring(index)); - dom.Body = node; - dom.append(node); - } else if ((index = assertKeyword("include", source)) > -1) { //语句 - - int tmp = assertKeyword("'", source, index); - if (tmp < 0) { - this.reportError("未设置 include 路径."); - } - //source=source.substring(tmp); - int end = this.parseRange(source, tmp, "'", "'"); - if (tmp < 0) { - this.reportError("未设置 include 路径."); - } - - Node node = Span.create(this, Node.LEXS_INCLUDE, source.substring(tmp, end)); - dom.append(node); - } else if ((index = assertKeyword("place", source)) > -1) { //语句 - Node node = Span.create(this, Node.LEXS_PLACE, source.substring(index)); - dom.append(node); - } else { - //String code; - Node node; - if (source.startsWith("@")) { - node = Span.create(this, Node.LEXS_RAW, source); - } else { - node = Span.create(this, Node.LEXS_PRINT, source); - } - dom.append(node); - } - //System.out.println(s); - } - - public void compile(String toFilename) throws FileNotFoundException, IOException { - StringBuilder sb = new StringBuilder(); - //dom.compile(sb); - System.out.println(sb.toString()); - java.io.FileOutputStream fs = new java.io.FileOutputStream(toFilename); - java.io.BufferedWriter writer = new java.io.BufferedWriter(new java.io.OutputStreamWriter(fs)); - writer.append(sb); - writer.flush(); - writer.close(); - - } - - public abstract void parse(Node node); - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/mano/otpl/Span.java b/del/mano-server-projects/open-tpl/src/main/java/mano/otpl/Span.java deleted file mode 100644 index 769d79a..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/mano/otpl/Span.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (C) 2014 The MANO Authors. - * All rights reserved. Use is subject to license terms. - * - * See more http://mano.diosay.com/ - * - */ - -package mano.otpl; - -/** - * - * @author jun - */ -public class Span extends Node { - protected Span(Parser p, int type, String s) { - super(p, type, s); - } - - public static Span create(Parser parser, int type, String source) { - Span result=new Span(parser,type,source); - return result; - } - - @Override - public final boolean isBlock() { - return false; - } - - @Override - public void parse(){ - this.parser.parse(this); - } -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/mano/otpl/emit/EmitParser.java b/del/mano-server-projects/open-tpl/src/main/java/mano/otpl/emit/EmitParser.java deleted file mode 100644 index ca88cea..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/mano/otpl/emit/EmitParser.java +++ /dev/null @@ -1,990 +0,0 @@ -/* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. - */ -package mano.otpl.emit; - -import java.io.DataInputStream; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.nio.charset.Charset; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.LinkedHashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.NoSuchElementException; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.logging.Level; -import java.util.logging.Logger; -import mano.otpl.*; -import mano.util.Utility; - -/** - * - * @author jun - */ -public class EmitParser extends Parser { - - /*public static void mains(String[] args) { - EmitParser parser = new EmitParser(); - //Object t = paraser.parseExpr("123.56", 0);//13 - //System.out.println(t); - //http://java.chinaitlab.com/base/922270.html - - try { - parser.open("E:\\repositories\\java\\mano\\mano.server\\server\\wwwroot\\views\\tpl\\member.tpl.html"); - } catch (FileNotFoundException ex) { - Logger.getLogger(Parser.class.getName()).log(Level.SEVERE, null, ex); - return; - } - try { - - String path = "E:\\repositories\\java\\mano\\mano.server\\server\\tmp\\"; - String name = Integer.toHexString(parser.getSourceName().hashCode()) + ".il"; - File file = new File(path + name); - if (file.exists()) { - file.delete(); - } - file.createNewFile(); - FileOutputStream fs = new FileOutputStream(file); - //OutputStreamWriter write = new OutputStreamWriter(fs, "UTF-8"); - parser.parse(); - parser.compile(fs); - fs.close(); - } catch (IOException ex) { - Logger.getLogger(Parser.class.getName()).log(Level.SEVERE, null, ex); - } - System.out.println("compiling done"); - }*/ - @Override - public void parse() throws IOException { - this.parseParent(null); - } - EmitParser parent; - - private void parseParent(Document content) throws IOException { - this.conentDom = content; - super.parse(); - - if (dom.Layout != null) { - parent = new EmitParser(); - String file = dom.Layout.getSource(); - if (file.startsWith("./") || file.startsWith(".\\")) { - file = file.substring(2); - } else if (file.startsWith("/") || file.startsWith("\\")) { - file = file.substring(1); - } - parent.open(Paths.get(Paths.get(this.getSourceName()).getParent().toString(), file).toString()); - parent.parseParent(dom); - - if (parent.reader != null) { - parent.reader.close(); - parent.reader=null; - } - - //setparent - //parent.parse(parent.dom, null, null); - } else {// if (this.conentDom == null) - codes.add(OpCode.create(OpCodes.DOM)); - parse(dom, null, null); - codes.add(OpCode.create(OpCodes.EXIT)); - } - - } - - LinkedList codes = new LinkedList<>(); - long addr = 0; - - private long newAddress() { - addr++; - return addr; - } - - private long newAddress(int size) { - addr++; - long r = addr; - addr += size; - return r; - } - - @Override - public void parse(Node node) {//OpCode loop_start, OpCode loop_end - if (node == null || node.mark) { - return; - } - cnode = node; - if (node.isBlock()) { - parseBlock((Block) node, null, null); - } else { - parseSpan((Span) node, null, null); - } - } - - public void parse(Node node, OpCode loop_start, OpCode loop_end) { - if (node == null || node.mark) { - return; - } - cnode = node; - if (node.isBlock()) { - parseBlock((Block) node, loop_start, loop_end); - - } else { - parseSpan((Span) node, loop_start, loop_end); - } - } - - private void parseBlock(Block node, OpCode loop_start, OpCode loop_end) { - if (node == null) { - return; - } - if (false) { - System.out.println(node.getSource()); - for (Node sub : node.getNodes()) { - sub.parse(); - } - return; - } - switch (node.getNodeType()) { - case Node.LEXB_BLOCK: - break; - case Node.LEXB_DOM: - //codes.add(OpCode.create(OpCodes.DOM)); - for (Node sub : node.getNodes()) { - parse(sub, null, null); - } - return; - case Node.LEXB_EACH: { - String source = node.getSource(); - int index; - if ((index = assertKeyword(":", source)) < 0) { - this.reportError("语法错误"); - } - int found = this.parseIdentifier(source, index); - if (found < 0) { - this.reportError("非法的标识符"); - } - String id = source.substring(index, found); - OpCode ret = OpCode.label(); - OpCode elseLable = OpCode.label(); - OpCode testLabel = OpCode.label(); - OpCode continueLabel = OpCode.label(); - - String part = Integer.toHexString(UUID.randomUUID().hashCode()); - String iterator = id + "$itel_" + part; - String hasnext = id + "$hnxt_" + part; - String next = id + "$nxt_" + part; - - this.parseExpr(source.substring(found), 0);//参数 - codes.add(OpCode.create(OpCodes.LOAD_ITERATOR));//将对象转换为迭代器,如果对象为null则会创建一个空迭代 - codes.add(OpCode.create(OpCodes.SET_VAR, iterator));//保存到迭代器变量 - codes.add(OpCode.create(OpCodes.LOAD_VAR, iterator));//载入迭代器对象 - codes.add(OpCode.create(OpCodes.LOAD_METHOD, 0, "hasNext"));//找到迭代器方法 - codes.add(OpCode.create(OpCodes.SET_VAR, hasnext));//保存迭代器方法变量 - codes.add(OpCode.create(OpCodes.LOAD_VAR, iterator));//载入迭代器对象 - codes.add(OpCode.create(OpCodes.LOAD_METHOD, 0, "next"));//找到迭代器方法 - codes.add(OpCode.create(OpCodes.SET_VAR, next));//保存迭代器方法变量 - - //第一次判断 - codes.add(OpCode.create(OpCodes.LOAD_VAR, iterator)); - codes.add(OpCode.create(OpCodes.LOAD_VAR, hasnext)); - codes.add(OpCode.create(OpCodes.CALL, 0)); - codes.add(OpCode.create(OpCodes.CONDITION_JUMP, continueLabel, elseLable)); - codes.add(testLabel); - //循环判断 - codes.add(OpCode.create(OpCodes.LOAD_VAR, iterator)); - codes.add(OpCode.create(OpCodes.LOAD_VAR, hasnext)); - codes.add(OpCode.create(OpCodes.CALL, 0)); - codes.add(OpCode.create(OpCodes.JUMP_FLASE, ret)); - codes.add(continueLabel); - //设置迭代值 - codes.add(OpCode.create(OpCodes.LOAD_VAR, iterator)); - codes.add(OpCode.create(OpCodes.LOAD_VAR, next)); - codes.add(OpCode.create(OpCodes.CALL, 0)); - codes.add(OpCode.create(OpCodes.SET_VAR, id)); - - //循环体 - for (Node sub : node.getNodes()) { - parse(sub, testLabel, ret); - } - codes.add(OpCode.create(OpCodes.JUMP, testLabel)); - codes.add(elseLable); - - //each-else body - Node nextNode = node.getNextNode(); - if (nextNode != null && nextNode.getNodeType() == Node.LEXB_ELSE) { - nextNode.mark = true; - - for (Node sub : ((Block) nextNode).getNodes()) { - parse(sub, null, null); - } - - codes.add(OpCode.create(OpCodes.JUMP, ret)); - } - codes.add(ret); - return; - } - case Node.LEXB_ELSE: - throw new java.lang.RuntimeException("else"); - case Node.LEXB_FOR: { - String source = node.getSource(); - int index; - if ((index = assertKeyword(":", source)) < 0) { - this.reportError("语法错误"); - } - int found = this.parseIdentifier(source, index); - if (found < 0) { - this.reportError("非法的标识符"); - } - String id = source.substring(index, found); - OpCode ret = OpCode.label(); - OpCode begin = OpCode.create(OpCodes.BEGIN_BLOCK); - OpCode end = OpCode.create(OpCodes.END_BLOCK, begin); - OpCode label = OpCode.label(); - OpCode label2 = OpCode.label(); - OpCode label3 = OpCode.label(); - codes.add(begin); - - LinkedList args = new LinkedList<>(); - AtomicInteger count = new AtomicInteger(0); - this.parseExpr(source.substring(found), 0, args, count);//参数 - if (!args.isEmpty()) { - count.addAndGet(1); - } - while (true) { - OpCode n = args.pollFirst(); - if (n == null) { - break; - } - codes.add(n); - } - - if (count.get() == 3) { - - } else if (count.get() == 2) { - codes.add(OpCode.create(OpCodes.LOAD_INTEGER, 1L)); - } else if (count.get() == 1) { - codes.add(OpCode.create(OpCodes.LOAD_INTEGER, 0L)); - codes.add(OpCode.create(OpCodes.LOAD_INTEGER, 1L)); - } else { - this.reportError("参数错误"); - } - String part = Integer.toHexString(UUID.randomUUID().hashCode()); - String max = id + "$max_" + part; - String step = id + "$stp_" + part; - - codes.add(OpCode.create(OpCodes.SET_VAR, step)); - codes.add(OpCode.create(OpCodes.SET_VAR, id)); - codes.add(OpCode.create(OpCodes.SET_VAR, max)); - - //比较两个数的大小,如果初始大于max则跳到else,如果有的话 - codes.add(OpCode.create(OpCodes.LOAD_VAR, id)); - codes.add(OpCode.create(OpCodes.LOAD_VAR, max)); - codes.add(OpCode.create(OpCodes.OP_GTE)); - codes.add(OpCode.create(OpCodes.CONDITION_JUMP, end, label2)); //第一次判断 - codes.add(label); - codes.add(OpCode.create(OpCodes.LOAD_VAR, step)); - codes.add(OpCode.create(OpCodes.LOAD_VAR, id)); - codes.add(OpCode.create(OpCodes.OP_ADD)); - codes.add(OpCode.create(OpCodes.SET_VAR, id)); - codes.add(OpCode.create(OpCodes.LOAD_VAR, id)); - codes.add(OpCode.create(OpCodes.LOAD_VAR, max)); - codes.add(OpCode.create(OpCodes.OP_GTE)); - codes.add(OpCode.create(OpCodes.CONDITION_JUMP, ret, label2));//循环判断 - codes.add(label2); - for (Node sub : node.getNodes()) { - parse(sub, label, ret); - } - codes.add(OpCode.create(OpCodes.JUMP, label)); - codes.add(end); - Node next = node.getNextNode(); - if (next != null && next.getNodeType() == Node.LEXB_ELSE) { - next.mark = true; - - begin = OpCode.create(OpCodes.BEGIN_BLOCK); - end = OpCode.create(OpCodes.END_BLOCK, begin); - codes.add(begin); - for (Node sub : ((Block) next).getNodes()) { - parse(sub, null, null); - } - codes.add(OpCode.create(OpCodes.JUMP, ret)); - codes.add(end); - } - codes.add(ret); - return; - } - case Node.LEXB_ELIF: - throw new java.lang.RuntimeException("elif"); - case Node.LEXB_IF: - OpCode ret = OpCode.label(); - OpCode begin = OpCode.create(OpCodes.BEGIN_BLOCK); - OpCode end = OpCode.create(OpCodes.END_BLOCK, begin); - OpCode label = OpCode.label(); - codes.add(begin); - this.parseExpr(node.getSource(), 0); - codes.add(OpCode.create(OpCodes.CONDITION_JUMP, label, end)); - codes.add(label); - for (Node sub : node.getNodes()) { - parse(sub, label, ret); - } - codes.add(OpCode.create(OpCodes.JUMP, ret)); - codes.add(end); - - Node next = node.getNextNode(); - while (true) { - if (next != null && next.getNodeType() == Node.LEXB_ELIF) { - next.mark = true; - - begin = OpCode.create(OpCodes.BEGIN_BLOCK); - end = OpCode.create(OpCodes.END_BLOCK, begin); - label = OpCode.label(); - codes.add(begin); - this.parseExpr(next.getSource(), 0); - codes.add(OpCode.create(OpCodes.CONDITION_JUMP, label, end)); - codes.add(label); - for (Node sub : ((Block) next).getNodes()) { - parse(sub, label, ret); - } - codes.add(OpCode.create(OpCodes.JUMP, ret)); - codes.add(end); - - next = next.getNextNode(); - } else { - break; - } - } - if (next != null && next.getNodeType() == Node.LEXB_ELSE) { - next.mark = true; - - begin = OpCode.create(OpCodes.BEGIN_BLOCK); - end = OpCode.create(OpCodes.END_BLOCK, begin); - codes.add(begin); - for (Node sub : ((Block) next).getNodes()) { - parse(sub, label, ret); - } - codes.add(OpCode.create(OpCodes.JUMP, ret)); - codes.add(end); - } - codes.add(ret); - return; - case Node.LEXB_WHILE: - break; - } - System.out.println("no parsing:" + node.getNodeType()); - } - Document conentDom; - - private void parseSpan(Span node, OpCode loop_start, OpCode loop_end) { - if (node == null) { - return; - } - if (false) { - System.out.println(node.getSource()); - return; - } - switch (node.getNodeType()) { - case Node.LEXS_BODY: { - if (this.conentDom == null) { - throw new java.lang.RuntimeException("语法错误,布局模板不能单独解析"); - } - this.parse(conentDom); - return; - } - case Node.LEXS_BREAK: - if (loop_end == null) { - throw new java.lang.RuntimeException("语法错误,不在循环中"); - } - codes.add(OpCode.create(OpCodes.JUMP, loop_end)); - return; - case Node.LEXS_CALL: - case Node.LEXS_CCALL: - break; - case Node.LEXS_CONTINUE: - if (loop_start == null) { - throw new java.lang.RuntimeException("语法错误,不在循环中"); - } - codes.add(OpCode.create(OpCodes.JUMP, loop_start)); - return; - case Node.LEXS_RAW: - case Node.LEXS_ENDBLOCK: - case Node.LEXS_ENDEACH: - case Node.LEXS_ENDFOR: - case Node.LEXS_ENDIF: - case Node.LEXS_ENDWHILE: - case Node.LEXS_EXIT: - case Node.LEXS_INCLUDE: - case Node.LEXS_LAYOUT: - - break; - case Node.LEXS_PLACE: { - String source = node.getSource(); - int index; - if ((index = assertKeyword(":", source)) < 0) { - this.reportError("语法错误"); - } - int found = this.parseIdentifier(source, index); - if (found < 0) { - this.reportError("非法的标识符"); - } - String id = source.substring(index, found); - index = this.parseIdentifier(source, found + 1); - boolean required = false; - if (index < 0) { - required = false; - } else { - String tmp = source.substring(found + 1, index).trim(); - if ("".equals(tmp) || "false".equals(tmp)) { - required = false; - } else if ("true".equals(tmp)) { - required = true; - } else { - this.reportError("必须是 true 或 false"); - } - } - - if (conentDom == null || conentDom.blocks == null || !conentDom.blocks.containsKey(id)) {//TODO: 处理失败? - if (required) { - this.reportError("block 是必须的 但未提供或未找到"); - } else { - return; - } - } - - Block block = conentDom.blocks.get(id); - - for (Node sub : block.getNodes()) { - this.parse(sub, loop_start, loop_end);//是否需要传loop? - } - return; - } - case Node.LEXS_PLAIN: - codes.add(OpCode.create(OpCodes.PRINT_STR, node.getSource())); - return; - case Node.LEXS_PRINT: - this.parseExpr(node.getSource(), 0); - codes.add(OpCode.create(OpCodes.PRINT, node.getSource())); - return; - case Node.LEXS_SET: - break; - } - System.out.println("no parsing:" + node.getNodeType()); - } - - boolean canSwap = false; - - /** - * 查找最后一个元素查看是否是运算操作 - * - * @return - */ - private OpCode findSwap(List l) { - if (!canSwap) { - return null; - } - LinkedList link; - - if (l instanceof Tuple) { - link = ((Tuple) l).list; - } else { - link = (LinkedList) l; - } - - canSwap = false; - OpCode code = null; - try { - code = link.getLast(); - } catch (NoSuchElementException e) { - } - if (code == null) { - return null; - } - ArrayList list = new ArrayList<>(); - list.add(OpCodes.OP_ADD.getValue()); - list.add(OpCodes.OP_AND.getValue()); - list.add(OpCodes.OP_DIV.getValue()); - list.add(OpCodes.OP_EQ.getValue()); - list.add(OpCodes.OP_GT.getValue()); - list.add(OpCodes.OP_GTE.getValue()); - list.add(OpCodes.OP_LT.getValue()); - list.add(OpCodes.OP_LTE.getValue()); - list.add(OpCodes.OP_MOD.getValue()); - list.add(OpCodes.OP_MUL.getValue()); - list.add(OpCodes.OP_NEQ.getValue()); - list.add(OpCodes.OP_NOT.getValue()); - list.add(OpCodes.OP_NOT.getValue()); - list.add(OpCodes.OP_OR.getValue()); - list.add(OpCodes.OP_SUB.getValue()); - if (list.contains(code.getCode().getValue())) { - link.removeLast(); - return code; - } - return null; - } - - private OpCode findSwap() { - return findSwap(codes); - } - - private boolean isDot(String source, int index) { - if (source == null || index >= source.length()) { - return false; - } - return source.charAt(index) == '.'; - } - - protected void parseExpr(String source, int index) { - parseExpr(source, index, codes, new AtomicInteger(0)); - } - - protected void parseExpr(String source, int index, List link, AtomicInteger argCount) { - if (source == null || index >= source.length()) { - return; - } - - for (; index < source.length(); index++) { - if (this.isWhitespace(source.charAt(index))) {//空白 - //ignored - } else if (source.charAt(index) == '@' || source.charAt(index) == '.' || this.isLetter(source.charAt(index))) {//视图对象 - boolean local = false; - boolean memberacc = false; - if (source.charAt(index) == '@') { - local = true;//TODO: 仅调用 - index++; - } else if (source.charAt(index) == '.') { - memberacc = true;//移动到下部 - index++; - } - - int tmp = parseIdentifier(source, index); - if (tmp < 0) { - this.reportError("syntax error,illegal identifier at " + index); - } - String id = source.substring(index, tmp); - index = tmp - 1; - OpCode swap = findSwap(link); - if (id.equals("true") || id.equals("false") || id.equals("null")) { - link.add(OpCode.create(OpCodes.LOAD_STR, "[!--SYS-TYPE--$" + id + "]")); - if (swap != null) { - link.add(swap); - } - return; - } - //预测后续 - if (index + 1 >= source.length()) { - //处理 - - if (memberacc) { - link.add(OpCode.create(OpCodes.LOAD_PROPERTY, id));//获取成员 - link.add(OpCode.create(OpCodes.CALL));//执行 - } else { - this.codes.add(OpCode.create(OpCodes.LOAD_VAR, id));//变量 - } - if (swap != null) { - link.add(swap); - } - return; - } - int type = 0; - int tinx = 0; - int tmp2 = 0; - if ((tmp = this.assertKeyword("[", source, index + 1)) > -1) { - type = 1;//索引 - tinx = tmp; - tmp = this.parseRange(source, tmp + 1, "[", "]"); - } else if ((tmp = this.assertKeyword("(", source, index + 1)) > -1) { - type = 2;//函数 - tinx = tmp; - tmp = this.parseRange(source, tmp + 1, "(", ")"); - } - if (type != 0) { - if (tmp < 0) { - this.reportError("syntax error,illegal characters at " + index); - } - LinkedList args = new LinkedList<>(); - AtomicInteger count = new AtomicInteger(0); - this.parseExpr(source.substring(tinx, tmp), 0, args, count);//参数 - if (!args.isEmpty()) { - count.addAndGet(1); - } - int args_len = count.get(); - index = tmp + 1; - if (memberacc) { - if (type == 1) { - link.add(OpCode.create(OpCodes.LOAD_PROPERTY, id));//获取成员 - link.add(OpCode.create(OpCodes.CALL));//执行 - } else { - link.add(OpCode.create(OpCodes.LOAD_METHOD, args_len, id));//获取成员 - } - } else { - link.add(OpCode.create(OpCodes.LOAD_VAR, id));//变量 - } - if (type == 1) { - link.add(OpCode.create(OpCodes.INDEXER, args_len, id));//查找索引器 - } - while (true) { - OpCode n = args.pollFirst(); - if (n == null) { - break; - } - link.add(n); - } - link.add(OpCode.create(OpCodes.CALL, args_len));//执行 - if (swap != null) { - this.codes.add(swap); - } - } else { - if (memberacc) { - link.add(OpCode.create(OpCodes.LOAD_PROPERTY, id));//获取成员 - link.add(OpCode.create(OpCodes.CALL));//执行 - } else { - link.add(OpCode.create(OpCodes.LOAD_VAR, id));//变量 - } - if (swap != null) { - link.add(swap); - } - } - } else if (this.isDigital(source.charAt(index))) {//数字 - int tmp = this.parseNumber(source, index); - if (tmp < 0) { - this.reportError("syntax error,illegal identifier at " + index); - } - String part = source.substring(index, tmp); - index = tmp; - OpCode swap = findSwap(link); - if (index < source.length() && source.charAt(index) == '.') { - tmp = this.parseNumber(source, index + 1); - if (tmp < 0) { - this.reportError("syntax error,illegal identifier at " + index); - } - part += "." + source.substring(index + 1, tmp); - index = tmp; - link.add(OpCode.create(OpCodes.LOAD_NUMBER, Double.parseDouble(part))); - } else { - link.add(OpCode.create(OpCodes.LOAD_INTEGER, Long.parseLong(part))); - } - if (swap != null) { - link.add(swap); - } - index--; - //load_arg number - - } else if (source.charAt(index) == '(') { //括号 - int tmp = this.parseRange(source, index + 1, "(", ")"); - if (tmp < 0) { - this.reportError("syntax error,illegal characters at " + index); - } - Tuple tup = new Tuple(); - this.parseExpr(source.substring(index + 1, tmp), 0, tup, new AtomicInteger()); - link.add(tup); - index = tmp + 1; - } else if (source.charAt(index) == '\'') {//字符串 - int tmp = this.parseRange(source, index + 1, "'", "'"); - if (tmp < 0) { - this.reportError("syntax error,illegal characters at " + index); - } - OpCode swap = findSwap(link); - link.add(OpCode.create(OpCodes.LOAD_STR, source.substring(index + 1, tmp))); - if (swap != null) { - link.add(swap); - } - index = tmp; - } else if (source.charAt(index) == '+') {//运算符 - link.add(OpCode.create(OpCodes.OP_ADD)); - canSwap = true; - } else if (source.charAt(index) == '-') {//运算符 - if (index + 1 < source.length() && this.isDigital(source.charAt(index + 1))) {//负数 - int tmp = this.parseNumber(source, index + 1); - if (tmp < 0) { - this.reportError("syntax error,illegal identifier at " + index); - } - String part = "-" + source.substring(index, tmp); - index = tmp; - OpCode swap = findSwap(link); - if (index < source.length() && source.charAt(index) == '.') { - tmp = this.parseNumber(source, index + 1); - if (tmp < 0) { - this.reportError("syntax error,illegal identifier at " + index); - } - part += "." + source.substring(index + 1, tmp); - index = tmp; - link.add(OpCode.create(OpCodes.LOAD_NUMBER, Double.parseDouble(part))); - } else { - link.add(OpCode.create(OpCodes.LOAD_INTEGER, Long.parseLong(part))); - } - - if (swap != null) { - link.add(swap); - } - index--; - } else { - link.add(OpCode.create(OpCodes.OP_SUB)); - canSwap = true; - } - } else if (source.charAt(index) == '*') {//运算符 - link.add(OpCode.create(OpCodes.OP_MUL)); - canSwap = true; - } else if (source.charAt(index) == '/') {//运算符 - link.add(OpCode.create(OpCodes.OP_DIV)); - canSwap = true; - } else if (source.charAt(index) == '%') {//运算符 - link.add(OpCode.create(OpCodes.OP_MOD)); - canSwap = true; - } else if (source.charAt(index) == '=' && index + 1 < source.length() && source.charAt(index + 1) == '=') {//运算符 - link.add(OpCode.create(OpCodes.OP_EQ)); - canSwap = true; - index += 1; - } else if (source.charAt(index) == '!' && index + 1 < source.length() && source.charAt(index + 1) == '=') {//运算符 - link.add(OpCode.create(OpCodes.OP_NEQ)); - canSwap = true; - index += 1; - } else if (source.charAt(index) == '>' && index + 1 < source.length() && source.charAt(index + 1) == '=') {//运算符 - link.add(OpCode.create(OpCodes.OP_GTE)); - canSwap = true; - index += 1; - } else if (source.charAt(index) == '<' && index + 1 < source.length() && source.charAt(index + 1) == '=') {//运算符 - link.add(OpCode.create(OpCodes.OP_LTE)); - index += 1; - canSwap = true; - } else if (source.charAt(index) == '|' && index + 1 < source.length() && source.charAt(index + 1) == '|') {//运算符 - link.add(OpCode.create(OpCodes.OP_OR)); - index += 1; - canSwap = true; - } else if (source.charAt(index) == '&' && index + 1 < source.length() && source.charAt(index + 1) == '&') {//运算符 - link.add(OpCode.create(OpCodes.OP_AND)); - index += 1; - canSwap = true; - } else if (source.charAt(index) == '>') {//运算符 - link.add(OpCode.create(OpCodes.OP_GT)); - canSwap = true; - } else if (source.charAt(index) == '<') {//运算符 - link.add(OpCode.create(OpCodes.OP_LT)); - canSwap = true; - } else if (source.charAt(index) == '!') {//运算符 - link.add(OpCode.create(OpCodes.OP_NOT)); - canSwap = true; - } else if (source.charAt(index) == ',') {//参数(使用时必须做修正) - argCount.addAndGet(1); - } else { - this.reportError("syntax error,illegal characters at " + index); - } - } - - } - - private void setAddress(OpCode code) { - if (code instanceof Tuple) { - for (OpCode sub : (Tuple) code) { - setAddress(sub); - } - } else { - code.setAdress(this.newAddress()); - } - } - - public void compile(String source, String target) throws IOException { - this.addr=0; - this.canSwap=false; - this.cnode=null; - this.codes.clear(); - this.conentDom=null; - this.dom=null; - this.filename=null; - this.inComment=false; - this.inLiteral=false; - this.parent=null; - this.reader=null; - try (java.io.FileInputStream in = new java.io.FileInputStream(source)) { - reader = new java.io.BufferedReader(new java.io.InputStreamReader(in,"utf-8")); - filename = source; - this.parse(); - reader.close(); - reader=null; - } - - try (java.io.FileOutputStream out = new java.io.FileOutputStream(target)) { - this.compile(out); - out.close(); - } - } - - public void compile(OutputStream output) throws IOException { - - if (parent != null) { - parent.compile(output); - return; - } - - //this.parse(); - for (OpCode code : codes) { - setAddress(code); - } - - for (OpCode code : codes) { - this.compile(code, output); - } - } - Charset charset=Charset.forName("utf-8"); - private void compile(OpCode code, OutputStream output) throws IOException { - if (code instanceof Tuple) { - for (OpCode sub : (Tuple) code) { - compile(sub, output); - } - return; - } - - if (!OpCodes.DOM.equals(code.getCode())) { - output.write(Utility.toBytes(code.getAddress())); - output.write(Utility.toBytes(code.getCode().getValue())); - } - if (OpCodes.BEGIN_BLOCK.equals(code.getCode())) { - } else if (OpCodes.CONDITION_JUMP.equals(code.getCode())) { - output.write(Utility.toBytes(code.getElement(0).getAddress())); - output.write(Utility.toBytes(code.getElement(1).getAddress())); - } else if (OpCodes.JUMP.equals(code.getCode()) || OpCodes.JUMP_FLASE.equals(code.getCode()) || OpCodes.JUMP_TRUE.equals(code.getCode())) { - output.write(Utility.toBytes(code.getElement(0).getAddress())); - } else if (OpCodes.DOM.equals(code.getCode())) { - output.write("OTPL-IL".getBytes(charset));//id7 - output.write(Utility.toBytes((short) 11));//ver - output.write(0x1);//utf-8 - - output.write(Utility.toBytes(0L));//file mod time8 - output.write(Utility.toBytes(0L));//gen time8 - } else if (OpCodes.END_BLOCK.equals(code.getCode())) { - output.write(Utility.toBytes(code.getElement(0).getAddress())); - } else if (OpCodes.EXIT.equals(code.getCode())) { - - } else if (OpCodes.LOAD_ITERATOR.equals(code.getCode())) { - - } else if (OpCodes.LOAD_NUMBER.equals(code.getCode())) { - output.write(Utility.toBytes(code.getNumber())); - } else if (OpCodes.LOAD_VAR.equals(code.getCode())) { - byte[] bytes = code.getString().getBytes(charset); - output.write(Utility.toBytes(bytes.length)); - output.write(bytes); - } else if (OpCodes.LOAD_INTEGER.equals(code.getCode())) { - output.write(Utility.toBytes(code.getLong()));// - } else if (OpCodes.LOAD_PROPERTY.equals(code.getCode())) { - byte[] bytes = code.getString().getBytes(charset); - output.write(Utility.toBytes(bytes.length)); - output.write(bytes); - } else if (OpCodes.LOAD_METHOD.equals(code.getCode())) { - output.write(Utility.toBytes(code.getInt())); - byte[] bytes = code.getString().getBytes(charset); - output.write(Utility.toBytes(bytes.length)); - output.write(bytes); - } else if (OpCodes.LOAD_STR.equals(code.getCode())) { - byte[] bytes = code.getString().getBytes(charset); - output.write(Utility.toBytes(bytes.length)); - output.write(bytes); - } else if (OpCodes.CALL.equals(code.getCode())) { - output.write(Utility.toBytes(code.getInt())); - } else if (OpCodes.INDEXER.equals(code.getCode())) { - } else if (OpCodes.NOP.equals(code.getCode())) { - } else if (OpCodes.OP_ADD.equals(code.getCode())) { - } else if (OpCodes.OP_AND.equals(code.getCode())) { - } else if (OpCodes.OP_DIV.equals(code.getCode())) { - } else if (OpCodes.OP_EQ.equals(code.getCode())) { - } else if (OpCodes.OP_GT.equals(code.getCode())) { - } else if (OpCodes.OP_GTE.equals(code.getCode())) { - } else if (OpCodes.OP_LT.equals(code.getCode())) { - } else if (OpCodes.OP_LTE.equals(code.getCode())) { - } else if (OpCodes.OP_MOD.equals(code.getCode())) { - } else if (OpCodes.OP_MUL.equals(code.getCode())) { - } else if (OpCodes.OP_NEQ.equals(code.getCode())) { - } else if (OpCodes.OP_NOT.equals(code.getCode())) { - } else if (OpCodes.OP_OR.equals(code.getCode())) { - } else if (OpCodes.OP_SUB.equals(code.getCode())) { - } else if (OpCodes.PRINT.equals(code.getCode())) { - } else if (OpCodes.PRINT_STR.equals(code.getCode())) { - byte[] bytes = code.getString().getBytes(charset); - output.write(Utility.toBytes(bytes.length)); - output.write(bytes); - } else if (OpCodes.SET_VAR.equals(code.getCode())) { - byte[] bytes = code.getString().getBytes(charset); - output.write(Utility.toBytes(bytes.length)); - output.write(bytes); - } else { - this.reportError("未实现命令"); - } - } - - private void compileT(OpCode code, OutputStream output) throws IOException { - String s = ""; - if (!OpCodes.DOM.equals(code.getCode())) { - s += code.getAddress() + " "; - s += code.getCode().getName() + " "; - } - if (OpCodes.BEGIN_BLOCK.equals(code.getCode())) { - } else if (OpCodes.CONDITION_JUMP.equals(code.getCode())) { - s += code.getElement(0).getAddress() + " "; - s += code.getElement(1).getAddress() + " "; - } else if (OpCodes.DOM.equals(code.getCode())) { - s += "OTPL-IL"; - s += (short) 11; - s += " "; - s += (byte) 11; - s += " "; - s += mano.DateTime.now() + " "; - s += mano.DateTime.now() + " "; - s += this.addr + " "; - } else if (OpCodes.END_BLOCK.equals(code.getCode())) { - s += code.getElement(0).getAddress() + " "; - } else if (OpCodes.EXIT.equals(code.getCode())) { - - } else if (OpCodes.JUMP.equals(code.getCode())) { - s += code.getElement(0).getAddress() + " "; - } else if (OpCodes.LOAD_NUMBER.equals(code.getCode())) { - s += code.getNumber() + " "; - } else if (OpCodes.LOAD_VAR.equals(code.getCode())) { - s += code.getString().getBytes().length + " "; - s += code.getString() + " "; - } else if (OpCodes.LOAD_INTEGER.equals(code.getCode())) { - s += code.getLong() + " "; - } else if (OpCodes.LOAD_PROPERTY.equals(code.getCode())) { - s += code.getString().getBytes().length + " "; - s += code.getString() + " "; - } else if (OpCodes.LOAD_METHOD.equals(code.getCode())) { - s += code.getInt() + " "; - s += code.getString().getBytes().length + " "; - s += code.getString() + " "; - } else if (OpCodes.LOAD_STR.equals(code.getCode())) { - s += code.getString().getBytes().length + " "; - s += code.getString() + " "; - } else if (OpCodes.CALL.equals(code.getCode())) { - s += code.getInt() + " "; - } else if (OpCodes.INDEXER.equals(code.getCode())) { - } else if (OpCodes.NOP.equals(code.getCode())) { - } else if (OpCodes.OP_ADD.equals(code.getCode())) { - } else if (OpCodes.OP_AND.equals(code.getCode())) { - } else if (OpCodes.OP_DIV.equals(code.getCode())) { - } else if (OpCodes.OP_EQ.equals(code.getCode())) { - } else if (OpCodes.OP_GT.equals(code.getCode())) { - } else if (OpCodes.OP_GTE.equals(code.getCode())) { - } else if (OpCodes.OP_LT.equals(code.getCode())) { - } else if (OpCodes.OP_LTE.equals(code.getCode())) { - } else if (OpCodes.OP_MOD.equals(code.getCode())) { - } else if (OpCodes.OP_MUL.equals(code.getCode())) { - } else if (OpCodes.OP_NEQ.equals(code.getCode())) { - } else if (OpCodes.OP_NOT.equals(code.getCode())) { - } else if (OpCodes.OP_OR.equals(code.getCode())) { - } else if (OpCodes.OP_SUB.equals(code.getCode())) { - } else if (OpCodes.PRINT.equals(code.getCode())) { - } else if (OpCodes.PRINT_STR.equals(code.getCode())) { - s += code.getString().getBytes().length + " "; - s += code.getString() + " "; - } else if (OpCodes.SET_VAR.equals(code.getCode())) { - s += code.getString().getBytes().length + " "; - s += code.getString() + " "; - } - s += "\r\n"; - output.write(s.getBytes()); - } -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/mano/otpl/emit/Interpreter.java b/del/mano-server-projects/open-tpl/src/main/java/mano/otpl/emit/Interpreter.java deleted file mode 100644 index a5f35a5..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/mano/otpl/emit/Interpreter.java +++ /dev/null @@ -1,667 +0,0 @@ -/* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. - */ -package mano.otpl.emit; - -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.UnsupportedEncodingException; -import java.lang.reflect.Array; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.Iterator; -import java.util.Map; -import mano.otpl.OtplViewEngine; -import mano.util.LinkedMap; -import mano.util.LinkedMap.LinkedNode; -import mano.util.Utility; - -/** - * 实现 Open-TPL 编译文件(OTC)的解释器。 - * - * @see https://github.com/diosay/open-tpl - * @author jun - */ -public class Interpreter { - - InputStream stream; - String version; - byte[] buf; - String charsetName; - long sourceLastMTime; - long ilCTime; - LinkedMap cmds; - LinkedNode current; - boolean running = true; - //Stack stack; - //Map args; - OutputStream output; - static final String TRUE = "[!--SYS-TYPE--$true]"; - static final String FLASE = "[!--SYS-TYPE--$false]"; - static final String NULL = "[!--SYS-TYPE--$null]"; - OtplViewEngine.OutProxy environment; - - public void set(String name, Object val) { - //args.put(name, val); - } - - public void setOut(OutputStream stream) { - this.output = stream; - } - - public void init(OtplViewEngine.OutProxy env) { - buf = new byte[26]; - cmds = new LinkedMap<>(); - environment = env; - - } - - public void exec(String filename) throws FileNotFoundException, IOException { - stream = new FileInputStream(filename); - - this.readHeader(); - - if (current == null) { - getCode(); - current = cmds.getFirstNode(); - exec(current); - } - while (running) { - - if (current.getNext() == null) { - getCode(); - } - if (current.getNext() == null) { - exec(cmds.getLastNode()); - } else { - exec(current.getNext()); - } - } - current = null; - running = true; - stream.close(); - stream = null; - //LinkedList f; - } - - private void error(String msg) { - throw new java.lang.RuntimeException(msg); - } - - private void readHeader() throws IOException { - int len = stream.read(buf, 0, 26); - if (len != 26) { - error("输入错误。"); - } - version = new String(buf, 0, 7); - version += " " + Utility.toShort(buf, 7); - if (buf[9] == 1) { - charsetName = "utf-8"; - } else { - charsetName = "utf-8";//default - } - sourceLastMTime = Utility.toLong(buf, 10); - ilCTime = Utility.toLong(buf, 18); - - } - - private byte[] getString(int left) throws IOException { - int len = 0; - int index = 0; - byte[] arg = new byte[left]; - while (left > 0) { - if (left >= left - index) { - len = stream.read(arg, index, left - index); - } else { - len = stream.read(arg, index, left); - } - index += len; - left -= len; - } - return arg; - } - - private OpCode getCode() throws IOException { - int len = stream.read(buf, 0, 10); - if (len != 10) { - error("输入错误。"); - } - - long addr = Utility.toLong(buf, 0); - OpCodes op = OpCodes.parse(buf, 8); - OpCode code = null; - if (OpCodes.BEGIN_BLOCK.equals(op)) { - code = OpCode.create(op).setAdress(addr); - } else if (OpCodes.CONDITION_JUMP.equals(op)) { - len = stream.read(buf, 0, 16); - if (len != 16) { - error("输入错误。"); - } - code = OpCode.create(op, - OpCode.create(OpCodes.NOP).setAdress(Utility.toLong(buf, 0)), - OpCode.create(OpCodes.NOP).setAdress(Utility.toLong(buf, 8))) - .setAdress(addr); - } else if (OpCodes.DOM.equals(op)) { - error("错误的指令。"); - } else if (OpCodes.END_BLOCK.equals(op)) { - len = stream.read(buf, 0, 8); - if (len != 8) { - error("输入错误。"); - } - code = OpCode.create(op, - OpCode.create(OpCodes.NOP).setAdress(Utility.toLong(buf, 0))) - .setAdress(addr); - } else if (OpCodes.EXIT.equals(op)) { - code = OpCode.create(op).setAdress(addr); - } else if (OpCodes.JUMP.equals(op) || OpCodes.JUMP_FLASE.equals(op) || OpCodes.JUMP_TRUE.equals(op)) { - len = stream.read(buf, 0, 8); - if (len != 8) { - error("输入错误。"); - } - code = OpCode.create(op, - OpCode.create(OpCodes.NOP).setAdress(Utility.toLong(buf, 0))) - .setAdress(addr); - } else if (OpCodes.LOAD_NUMBER.equals(op)) { - len = stream.read(buf, 0, 8); - if (len != 8) { - error("输入错误。"); - } - code = OpCode.create(op, Utility.toDouble(buf, 0)) - .setAdress(addr); - } else if (OpCodes.LOAD_VAR.equals(op)) { - len = stream.read(buf, 0, 4); - if (len != 4) { - error("输入错误。"); - } - code = OpCode.create(op, getString(Utility.toInt(buf, 0))) - .setAdress(addr); - - } else if (OpCodes.LOAD_INTEGER.equals(op)) { - len = stream.read(buf, 0, 8); - if (len != 8) { - error("输入错误。"); - } - code = OpCode.create(op, Utility.toLong(buf, 0)) - .setAdress(addr); - } else if (OpCodes.LOAD_PROPERTY.equals(op)) { - len = stream.read(buf, 0, 4); - if (len != 4) { - error("输入错误。"); - } - code = OpCode.create(op, getString(Utility.toInt(buf, 0))) - .setAdress(addr); - } else if (OpCodes.LOAD_METHOD.equals(op)) { - len = stream.read(buf, 0, 8); - if (len != 8) { - error("输入错误。"); - } - //Utility.toInt(buf, 0), - code = OpCode.create(op, Utility.toInt(buf, 0), getString(Utility.toInt(buf, 4))) - .setAdress(addr); - } else if (OpCodes.LOAD_STR.equals(op)) { - len = stream.read(buf, 0, 4); - if (len != 4) { - error("输入错误。"); - } - code = OpCode.create(op, getString(Utility.toInt(buf, 0))) - .setAdress(addr); - } else if (OpCodes.CALL.equals(op)) { - len = stream.read(buf, 0, 4); - if (len != 4) { - error("输入错误。"); - } - code = OpCode.create(op, Utility.toInt(buf, 0)).setAdress(addr); - } else if (OpCodes.LOAD_ITERATOR.equals(op)) { - code = OpCode.create(op).setAdress(addr); - } else if (OpCodes.INDEXER.equals(op)) { - code = OpCode.create(op).setAdress(addr); - } else if (OpCodes.NOP.equals(op)) { - code = OpCode.create(op).setAdress(addr); - } else if (OpCodes.OP_ADD.equals(op)) { - code = OpCode.create(op).setAdress(addr); - } else if (OpCodes.OP_AND.equals(op)) { - code = OpCode.create(op).setAdress(addr); - } else if (OpCodes.OP_DIV.equals(op)) { - code = OpCode.create(op).setAdress(addr); - } else if (OpCodes.OP_EQ.equals(op)) { - code = OpCode.create(op).setAdress(addr); - } else if (OpCodes.OP_GT.equals(op)) { - code = OpCode.create(op).setAdress(addr); - } else if (OpCodes.OP_GTE.equals(op)) { - code = OpCode.create(op).setAdress(addr); - } else if (OpCodes.OP_LT.equals(op)) { - code = OpCode.create(op).setAdress(addr); - } else if (OpCodes.OP_LTE.equals(op)) { - code = OpCode.create(op).setAdress(addr); - } else if (OpCodes.OP_MOD.equals(op)) { - code = OpCode.create(op).setAdress(addr); - } else if (OpCodes.OP_MUL.equals(op)) { - code = OpCode.create(op).setAdress(addr); - } else if (OpCodes.OP_NEQ.equals(op)) { - code = OpCode.create(op).setAdress(addr); - } else if (OpCodes.OP_NOT.equals(op)) { - code = OpCode.create(op).setAdress(addr); - } else if (OpCodes.OP_OR.equals(op)) { - code = OpCode.create(op).setAdress(addr); - } else if (OpCodes.OP_SUB.equals(op)) { - code = OpCode.create(op).setAdress(addr); - } else if (OpCodes.PRINT.equals(op)) { - code = OpCode.create(op).setAdress(addr); - } else if (OpCodes.PRINT_STR.equals(op)) { - len = stream.read(buf, 0, 4); - if (len != 4) { - error("输入错误。"); - } - code = OpCode.create(op, getString(Utility.toInt(buf, 0))) - .setAdress(addr); - - } else if (OpCodes.SET_VAR.equals(op)) { - len = stream.read(buf, 0, 4); - if (len != 4) { - error("输入错误。"); - } - code = OpCode.create(op, getString(Utility.toInt(buf, 0))) - .setAdress(addr); - } - - if (code == null) { - error("错误的指令"); - } - - cmds.addLast(addr, code); - return code; - } - - private void next() throws IOException { - if (current.getNext() == null) { - getCode(); - } - exec(current.getNext()); - } - - private void jump(long addr) throws IOException { - if (cmds.containsKey(addr)) { - exec(cmds.get(addr)); - } else { - while (true) { - if (addr == getCode().getAddress()) { - exec(cmds.get(addr)); - break; - } - } - } - } - - private void exec(LinkedNode node) throws IOException { - current = node; - OpCode code = node.getValue(); - - if (OpCodes.BEGIN_BLOCK.equals(code.getCode())) { - next(); - } else if (OpCodes.CONDITION_JUMP.equals(code.getCode())) { - if (toBoolean(environment.stack.pop())) { - jump(code.getElement(0).getAddress()); - } else { - jump(code.getElement(1).getAddress()); - } - } else if (OpCodes.JUMP_FLASE.equals(code.getCode())) { - if (!toBoolean(environment.stack.pop())) { - jump(code.getElement(0).getAddress()); - } - } else if (OpCodes.JUMP_TRUE.equals(code.getCode())) { - if (toBoolean(environment.stack.pop())) { - jump(code.getElement(0).getAddress()); - } - } else if (OpCodes.DOM.equals(code.getCode())) { - error("非法指令"); - } else if (OpCodes.END_BLOCK.equals(code.getCode())) { - next(); - } else if (OpCodes.EXIT.equals(code.getCode())) { - this.running = false; - } else if (OpCodes.JUMP.equals(code.getCode())) { - jump(code.getElement(0).getAddress()); - } else if (OpCodes.LOAD_NUMBER.equals(code.getCode())) { - environment.stack.push(code.getNumber()); - } else if (OpCodes.LOAD_VAR.equals(code.getCode())) { - String key = new String(code.getBytes()); - if (key == null || "".equals(key) || !environment.args.containsKey(key)) { - throw new java.lang.RuntimeException("变量未定义:" + key); - } - environment.stack.push(environment.args.get(key)); - } else if (OpCodes.LOAD_INTEGER.equals(code.getCode())) { - environment.stack.push(code.getLong()); - } else if (OpCodes.LOAD_METHOD.equals(code.getCode())) { - String key = new String(code.getBytes()); - environment.stack.push(getMethod(environment.stack.pop(), key, code.getInt())); - } else if (OpCodes.LOAD_PROPERTY.equals(code.getCode())) { - String key = new String(code.getBytes()); - environment.stack.push(getProperty(environment.stack.pop(), key)); - } else if (OpCodes.LOAD_STR.equals(code.getCode())) { - String str = new String(code.getBytes()); - switch (str) { - case FLASE: - environment.stack.push(false); - break; - case TRUE: - environment.stack.push(true); - break; - case NULL: - environment.stack.push(null); - break; - default: - environment.stack.push(str); - break; - } - - } else if (OpCodes.CALL.equals(code.getCode())) { - Object result = call(code.getInt()); - if (result != null && result instanceof Void) { - } else { - environment.stack.push(result); - } - } else if (OpCodes.LOAD_ITERATOR.equals(code.getCode())) { - environment.stack.push(this.toIterator(environment.stack.pop())); - } else if (OpCodes.INDEXER.equals(code.getCode())) { - Object result = call(code.getInt()); - if (result != null && result instanceof Void) { - - } else { - environment.stack.push(result); - } - } else if (OpCodes.NOP.equals(code.getCode())) { - //pass - } else if (OpCodes.OP_ADD.equals(code.getCode()) - || OpCodes.OP_SUB.equals(code.getCode()) - || OpCodes.OP_MUL.equals(code.getCode()) - || OpCodes.OP_DIV.equals(code.getCode()) - || OpCodes.OP_MOD.equals(code.getCode()) - || OpCodes.OP_GT.equals(code.getCode()) - || OpCodes.OP_GTE.equals(code.getCode()) - || OpCodes.OP_LT.equals(code.getCode()) - || OpCodes.OP_LTE.equals(code.getCode())) { - Object b = environment.stack.pop(); - Object a = environment.stack.pop(); - environment.stack.push(number_op(code.getCode(), a, b)); - } else if (OpCodes.OP_AND.equals(code.getCode()) || OpCodes.OP_OR.equals(code.getCode())) { - Object b = environment.stack.pop(); - Object a = environment.stack.pop(); - environment.stack.push(logic_op(code.getCode(), a, b)); - } else if (OpCodes.OP_EQ.equals(code.getCode())) { - Object b = environment.stack.pop(); - Object a = environment.stack.pop(); - if (a != null) { - environment.stack.push(a.equals(b)); - } else if (b != null) { - environment.stack.push(b.equals(a)); - } else { - environment.stack.push(a == b); - } - } else if (OpCodes.OP_NEQ.equals(code.getCode())) { - Object b = environment.stack.pop(); - Object a = environment.stack.pop(); - if (a != null) { - environment.stack.push(!a.equals(b)); - } else if (b != null) { - environment.stack.push(!b.equals(a)); - } else { - environment.stack.push(a != b); - } - } else if (OpCodes.OP_NOT.equals(code.getCode())) { - Object a = environment.stack.pop(); - if (a != null) { - environment.stack.push(!this.toBoolean(a)); - } else { - environment.stack.push(true); //空表示“非”,反则为真? - } - } else if (OpCodes.PRINT.equals(code.getCode())) { - Object ob = environment.stack.pop(); - - print(ob); - } else if (OpCodes.PRINT_STR.equals(code.getCode())) { - printStr(code.getBytes()); - } else if (OpCodes.SET_VAR.equals(code.getCode())) { - String name = new String(code.getBytes()); - Object val = environment.stack.pop(); - environment.args.put(name, val); - } - } - - private void print(Object obj) { - if(obj==null){ - return; - } - try { - printStr(obj.toString().getBytes(charsetName)); - } catch (UnsupportedEncodingException ex) { - throw new java.lang.RuntimeException(ex); - } - } - - private void printStr(byte[] bytes) { - try { - output.write(bytes); - } catch (IOException ex) { - throw new java.lang.RuntimeException(ex); - } - //System.out.print(new String(bytes)); - } - - private boolean toBoolean(Object obj) { - if (obj == null) { - return false; - } else if (obj instanceof Boolean) { - return (boolean) obj; - } - - return Boolean.class.cast(obj); - } - - private Object getMethod(Object obj, String name, int argCount) throws IOException { - Class clazz = obj.getClass(); - if (clazz.isPrimitive()) { - error("数据类型不匹配,不是一个效果的对象。"); - } - Object result = null; - - Method[] methods = clazz.getMethods(); - for (Method m : methods) { - if (m.getName().equals(name) && m.getParameterCount() == argCount) { - if (result != null) { - error("对象存在多个同名成员函数," + name); - } - result = m; - break;//TODO:对象存在多个同名成员函数????? - } - } - - if (result == null) { - error("成员方法未找到或不存在," + name); - } else { - //stack.push(argCount); - environment.stack.push(obj);//返回栈顶,供调用使用 - } - return result; - } - - private Object getProperty(Object obj, String name) throws IOException { - Class clazz = obj.getClass(); - if (clazz.isPrimitive()) { - error("数据类型不匹配,不是一个效果的对象。"); - } - Object result = null; - - String tmp = null; - if (name.startsWith("get") && name.length() >= 4) { - if (!Character.isUpperCase(name.charAt(0))) { - tmp = "get" + Character.toUpperCase(name.charAt(0)) + name.substring(1); - } - } else { - tmp = "get" + Character.toUpperCase(name.charAt(0)) + name.substring(1); - } - - if (tmp != null) { - Method[] methods = clazz.getMethods(); - for (Method m : methods) { - if (m.getName().equalsIgnoreCase(tmp)) { - if (result != null) { - error("存在多个对象成员," + tmp); - } - result = m; - } - } - } - if (result == null) { - Field[] fields = clazz.getFields(); - for (Field m : fields) { - if (m.getName().equalsIgnoreCase(name)) { - if (result != null) { - error("存在多个对象成员," + name); - } - result = m; - } - } - } - - if (result == null) { - error("属性未找到或不存在," + name); - } else { - //stack.push(0); - environment.stack.push(obj);//返回栈顶,供调用使用 - - } - return result; - } - - private Object call(int argCount) { - Object[] params = new Object[argCount]; - for (int i = argCount - 1; i >= 0; i--) { - params[i] = environment.stack.pop(); - } - Object member = environment.stack.pop(); - Object host = null; - if (member instanceof Method) { - Method call = (Method) member; - //int len=call.getParameterCount(); - - if (!Modifier.isStatic(call.getModifiers())) { - host = environment.stack.pop(); - } - Class[] types = call.getParameterTypes(); - for (int i = 0; i < argCount; i++) { - params[i] = Utility.cast(types[i], params[i]); - } - call.setAccessible(true); - try { - return call.invoke(host, params); - } catch (InvocationTargetException ex) { - throw new java.lang.RuntimeException(ex.getTargetException()); - //error("调用函数失败," + ex.getMessage() + "。" + call.getName()); - } catch (Exception ex) { - throw new java.lang.RuntimeException(ex); - //error("调用函数失败," + ex.getMessage() + "。" + call.getName()); - } - } else if (member instanceof Field) { - Field field = (Field) member; - if (!Modifier.isStatic(field.getModifiers())) { - host = environment.stack.pop(); - } - try { - return field.get(host); - } catch (Exception ex) { - error("调用属性(字段)方法函数失败," + ex.getMessage() + "。" + field.getName()); - } - } - error("调用函数失败,对象不匹配。"); - return null; - } - - private Object number_op(OpCodes op, Object a, Object b) { - - double av = Utility.toDouble(a); - double bv = Utility.toDouble(b); - - if (OpCodes.OP_ADD.equals(op)) { - return Utility.asNumber(Math.max(Utility.geTypeCode(a.getClass()), - Utility.geTypeCode(b.getClass())), - av + bv); - } else if (OpCodes.OP_DIV.equals(op)) { - return Utility.asNumber(Math.max(Utility.geTypeCode(a.getClass()), - Utility.geTypeCode(b.getClass())), - av / bv); - } else if (OpCodes.OP_GT.equals(op)) { - return av > bv; - } else if (OpCodes.OP_GTE.equals(op)) { - return av >= bv; - } else if (OpCodes.OP_LT.equals(op)) { - return av < bv; - } else if (OpCodes.OP_LTE.equals(op)) { - return av <= bv; - } else if (OpCodes.OP_MOD.equals(op)) { - return Utility.asNumber(Math.max(Utility.geTypeCode(a.getClass()), - Utility.geTypeCode(b.getClass())), - av % bv); - } else if (OpCodes.OP_MUL.equals(op)) { - return Utility.asNumber(Math.max(Utility.geTypeCode(a.getClass()), - Utility.geTypeCode(b.getClass())), - av * bv); - } else if (OpCodes.OP_SUB.equals(op)) { - return Utility.asNumber(Math.max(Utility.geTypeCode(a.getClass()), - Utility.geTypeCode(b.getClass())), - av - bv); - } - this.error("数据类型不匹配,不能作数值运算。"); - return null; - } - - private boolean logic_op(OpCodes op, Object a, Object b) { - - if (OpCodes.OP_AND.equals(op)) { - return this.toBoolean(a) && this.toBoolean(b); - } else if (OpCodes.OP_OR.equals(op)) { - return this.toBoolean(a) || this.toBoolean(b); - } - - error("数据类型不匹配,不能作数值运算。"); - - return false; - } - - private Object toIterator(Object obj) { - if (obj == null) { - obj = new Object[0]; - } - - if (obj instanceof Iterable) { - return ((Iterable) obj).iterator(); - } else if (obj instanceof Map) { - return ((Iterable) ((Map) obj).entrySet()).iterator(); - } else if (obj.getClass().isArray()) { - final Object array = obj; - final int size = Array.getLength(obj); - return new Iterator() { - int current = 0; - - @Override - public boolean hasNext() { - return current < size; - } - - @Override - public Object next() { - return Array.get(array, current++); - } - - }; - } - this.error("give object is a non-terable object." + obj.getClass()); - return obj; - } - -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/mano/otpl/emit/OpCode.java b/del/mano-server-projects/open-tpl/src/main/java/mano/otpl/emit/OpCode.java deleted file mode 100644 index 6c4c35a..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/mano/otpl/emit/OpCode.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. - */ -package mano.otpl.emit; - -import java.io.IOException; -import java.io.OutputStream; - -/** - * - * @author jun - */ -public class OpCode { - - private long address; - private OpCode[] elements; - private OpCodes opcode; - private String arg; - private double decArg; - private long longArg; - private int intArg; - private byte[] bytesArg; - protected OpCode() { - - } - - public OpCode setAdress(long addr) { - address = addr; - return this; - } - - public long getAddress() { - return address; - } - - public OpCode getElement(int index) { - if (index < 0) { - throw new IllegalArgumentException(); - } - if (this.elements == null || this.elements.length <= index) { - return null; - } - return this.elements[index]; - } - - public String getString(){ - return this.arg; - } - - public double getNumber(){ - return this.decArg; - } - - public long getLong(){ - return this.longArg; - } - public int getInt(){ - return this.intArg; - } - public byte[] getBytes(){ - return this.bytesArg; - } - - public OpCodes getCode() { - return this.opcode; - } - public static OpCode label() { - return create(OpCodes.NOP); - } - public static OpCode create(OpCodes opcode, OpCode... elements) { - OpCode code = new OpCode(); - code.opcode = opcode; - code.elements = elements; - return code; - } - - public static OpCode create(OpCodes opcode, String arg) { - OpCode code = new OpCode(); - code.opcode = opcode; - code.arg = arg; - return code; - } - - public static OpCode create(OpCodes opcode, long arg) { - OpCode code = new OpCode(); - code.opcode = opcode; - code.longArg = arg; - return code; - } - - public static OpCode create(OpCodes opcode, int arg) { - OpCode code = new OpCode(); - code.opcode = opcode; - code.intArg = arg; - return code; - } - - public static OpCode create(OpCodes opcode, double arg) { - OpCode code = new OpCode(); - code.opcode = opcode; - code.decArg = arg; - return code; - } - public static OpCode create(OpCodes opcode, byte[] arg) { - OpCode code = new OpCode(); - code.opcode = opcode; - code.bytesArg = arg; - return code; - } - - public static OpCode create(OpCodes opcode, int i,String s) { - OpCode code = new OpCode(); - code.opcode = opcode; - code.intArg = i; - code.arg = s; - return code; - } - public static OpCode create(OpCodes opcode, int i,byte[] b) { - OpCode code = new OpCode(); - code.opcode = opcode; - code.intArg = i; - code.bytesArg=b; - return code; - } -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/mano/otpl/emit/OpCodes.java b/del/mano-server-projects/open-tpl/src/main/java/mano/otpl/emit/OpCodes.java deleted file mode 100644 index b872cbe..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/mano/otpl/emit/OpCodes.java +++ /dev/null @@ -1,281 +0,0 @@ -/* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. - */ -package mano.otpl.emit; - -//http://msdn.microsoft.com/zh-cn/library/system.reflection.emit.opcodes(v=vs.110).aspx -import mano.util.Utility; - -/** - * - * @author jun - */ -public enum OpCodes { - - /** - * 什么都不做。 - */ - NOP(0, "nop"), - /** - * IL文件的头信息。 - *

- * IL原形:标识([MANO-IL]7)版本(2)字符编码类型(1)原文件最后修改时间(8)IL生成时间(8),共26字节。

- */ - DOM(1, "dom"), - /** - * 打印一个指定长度的字符串。 - *

- * IL原形:地址(8)操作(2)字符串长度(4)数据(n),共 14+n 字节。

- */ - PRINT_STR(2, "ptstr"), - /** - * 从栈顶弹出一个对象并打印。 - *

- * IL原形:地址(8)操作(2),共 10 字节。

- */ - PRINT(3, "pt"), - /** - * 表示一个块的开始。 块的开始会初始化一个独立的变量存储区。 - *

- * IL原形:地址(8)操作(2),共 10 字节。

- */ - //@Deprecated - BEGIN_BLOCK(4, "nop"), - /** - * 表示一个块的结束。 块的结束会销毁当前独立的变量存储区。 - *

- * IL原形:地址(8)操作(2)块开始地址(8),共 18 字节。

- */ - @Deprecated - END_BLOCK(5, "nop"), - /** - * 表示无条件跳到指定地址。 - *

- * IL原形:地址(8)操作(2)目标地址(8),共 18 字节。

- */ - JUMP(6, "jmp"), - /** - * 从栈顶弹出一个对象并判断真假,并跳到指定地址。 - *

- * IL原形:地址(8)操作(2)条件为真的地址(8)条件为假的地址(8),共 26 字节。

- */ - CONDITION_JUMP(7, "jmp_c"), - /** - * 根据索引从变量集合中获取一个对象,并压入栈顶。 - *

- * IL原形:地址(8)操作(2)索引长度(4)字符串索引(n),共 14+n 字节。

- */ - LOAD_VAR(8, "ldloc"), - /** - * 从栈顶弹出一个对象,获取其成员函数,并压入栈顶。 - *

- * IL原形:地址(8)操作(2)参数个数(4)名称长度(4)名称(n),共 18+n 字节。

- */ - LOAD_METHOD(9, "ldm_m"), - /** - * 从栈顶弹出一个对象,获取其成员属性,并压入栈顶。 - *

- * IL原形:地址(8)操作(2)索引长度(4)名称(n),共 14+n 字节。

- */ - LOAD_PROPERTY(10, "ldm_p"), - /** - * 载入一个数字,并压入栈顶。 - *

- * IL原形:地址(8)操作(2)数字(8),共 18 字节。

- */ - LOAD_NUMBER(11, "ldu_db"), - /** - * 载入一个整数,并压入栈顶。 - *

- * IL原形:地址(8)操作(2)数字(8),共 18 字节。

- */ - LOAD_INTEGER(12, "ldu_l"), - /** - * 载入一个字符串,并压入栈顶。 - *

- * IL原形:地址(8)操作(2)字符串长度(4)数据(n),共 14+n 字节。

- */ - LOAD_STR(13, "ldstr"), - /** - * 从栈顶弹出一个对象,根据索引从成员中获取一个对象,并压入栈顶。decimal - *

- * IL原形:地址(8)操作(2)索引长度(4)名称(n),共 14+n 字节。

- */ - INDEXER(14, "ldm_i"), - /** - * 从栈顶弹出一个函数对象,执行并将返回值(如果有)压入栈顶。 - *

- * IL原形:地址(8)操作(2),共 10 字节。

- */ - CALL(15, "call"), - /** - * 从栈顶弹出两个对象,相加并将结果压入栈顶。 - *

- * IL原形:地址(8)操作(2),共 10 字节。

- */ - OP_ADD(16, "add"), - /** - * 从栈顶弹出两个对象,相减并将结果压入栈顶。 - *

- * IL原形:地址(8)操作(2),共 10 字节。

- */ - OP_SUB(17, "sub"), - /** - * 从栈顶弹出两个对象,相乘减并将结果压入栈顶。 - *

- * IL原形:地址(8)操作(2),共 10 字节。

- */ - OP_MUL(18, "mul"), - /** - * 从栈顶弹出两个对象,相除并将结果压入栈顶。 - *

- * IL原形:地址(8)操作(2),共 10 字节。

- */ - OP_DIV(19, "div"), - /** - * 从栈顶弹出两个对象,相除取余并将结果压入栈顶。 - *

- * IL原形:地址(8)操作(2),共 10 字节。

- */ - OP_MOD(20, "mod"), - /** - * 从栈顶弹出两个对象,进行等于比较并将结果压入栈顶。 - *

- * IL原形:地址(8)操作(2),共 10 字节。

- */ - OP_EQ(21, "eq"), - /** - * 从栈顶弹出两个对象,进行不等于比较并将结果压入栈顶。 - *

- * IL原形:地址(8)操作(2),共 10 字节。

- */ - OP_NEQ(22, "neq"), - /** - * 从栈顶弹出两个对象,进行大于等于比较并将结果压入栈顶。 - *

- * IL原形:地址(8)操作(2),共 10 字节。

- */ - OP_GTE(23, "gte"), - /** - * 从栈顶弹出两个对象,进行小于等于比较并将结果压入栈顶。 - *

- * IL原形:地址(8)操作(2),共 10 字节。

- */ - OP_LTE(24, "lte"), - /** - * 从栈顶弹出两个对象,进行大于比较并将结果压入栈顶。 - *

- * IL原形:地址(8)操作(2),共 10 字节。

- */ - OP_GT(25, "gt"), - /** - * 从栈顶弹出两个对象,进行小于比较并将结果压入栈顶。 - *

- * IL原形:地址(8)操作(2),共 10 字节。

- */ - OP_LT(26, "lt"), - /** - * 从栈顶弹出一个对象,进行取反并将结果压入栈顶。 - *

- * IL原形:地址(8)操作(2),共 10 字节。

- */ - OP_NOT(27, "not"), - /** - * 从栈顶弹出两个对象,进行“与”运算并将结果压入栈顶。 - *

- * IL原形:地址(8)操作(2),共 10 字节。

- */ - OP_AND(28, "and"), - /** - * 从栈顶弹出两个对象,进行“或”运算并将结果压入栈顶。 - *

- * IL原形:地址(8)操作(2),共 10 字节。

- */ - OP_OR(29, "or"), - /** - * 完成并退出执行。 - *

- * IL原形:地址(8)操作(2),共 10 字节。

- */ - EXIT(30, "exit"), - /** - * 从栈顶弹出一个对象,并将该对幅值给索引的变量 。 - *

- * IL原形:地址(8)操作(2)索引长度(4)名称(n),共 14+n 字节。

- */ - SET_VAR(31, "stloc"), - /** - * 从栈顶弹出一个对象,取相反数并将结果压入栈顶。???? - *

- * IL原形:地址(8)操作(2),共 10 字节。

- */ - @Deprecated - OP_OPPOSITE(32, "opp"), - /** - * 从栈顶弹出一个对象,转换为迭代器并将结果压入栈顶。 - *

- * IL原形:地址(8)操作(2),共 10 字节。

- */ - LOAD_ITERATOR(33, "ldcur"), - /** - * 从栈顶弹出一个对象,如果该值为true则跳到指定地址。 - *

- * IL原形:地址(8)操作(2)目标地址(8),共 18 字节。

- */ - JUMP_TRUE(34, "jmp_t"), - /** - * 从栈顶弹出一个对象,如果该值为flast则跳到指定地址。 - *

- * IL原形:地址(8)操作(2)目标地址(8),共 18 字节。

- */ - JUMP_FLASE(35, "jmp_f"), - /** - * 从栈顶弹出一个对象。 - *

- * IL原形:地址(8)操作(2),共 10 字节。

- */ - OP_POP(36, "pop"),/** - * 包含一个外部IL文件并执行。 - *

- * IL原形:地址(8)操作(2)字符串长度(4)数据(n),共 14+n 字节。

- */ - INCLUDE(37, "inc"), - //http://msdn.microsoft.com/zh-cn/library/34dk387t.aspx - /* 定义一个宏用于DEBUG调试。 - *

- * IL原形:地址(8)操作(2)原行号(4)文件名长度(4)文件名(n),共 18+n 字节。

- */ - LINE(38, "line"),; - - private final short value; - private final String name; - - private OpCodes(int val, String op) { - value = (short) val; - name = op; - } - - public String getName() { - return name; - } - - public short getValue() { - return this.value; - } - - public static OpCodes parse(byte[] bytes, int index) { - short val = Utility.toShort(bytes, index); - for (OpCodes code : OpCodes.values()) { - if (val == code.value) { - return code; - } - } - throw new mano.InvalidOperationException(); - } - - public final boolean equals(OpCodes other) { - return this.value == other.value; - } -} diff --git a/del/mano-server-projects/open-tpl/src/main/java/mano/otpl/emit/Tuple.java b/del/mano-server-projects/open-tpl/src/main/java/mano/otpl/emit/Tuple.java deleted file mode 100644 index 76c23a9..0000000 --- a/del/mano-server-projects/open-tpl/src/main/java/mano/otpl/emit/Tuple.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. - */ - -package mano.otpl.emit; - -import java.util.Collection; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.ListIterator; - -/** - * - * @author jun - */ -public class Tuple extends OpCode implements List { - - LinkedList list=new LinkedList<>(); - - @Override - public int size() { - return list.size(); - } - - @Override - public boolean isEmpty() { - return list.isEmpty(); - } - - @Override - public boolean contains(Object o) { - return list.contains(o); - } - - @Override - public Iterator iterator() { - return list.iterator(); - } - - @Override - public Object[] toArray() { - return list.toArray(); - } - - @Override - public T[] toArray(T[] a) { - return list.toArray(a); - } - - @Override - public boolean add(OpCode e) { - return list.add(e); - } - - @Override - public boolean remove(Object o) { - return list.remove(o); - } - - @Override - public boolean containsAll(Collection c) { - return list.containsAll(c); - } - - @Override - public boolean addAll(Collection c) { - return list.addAll(c); - } - - @Override - public boolean addAll(int index, Collection c) { - return list.addAll(index, c); - } - - @Override - public boolean removeAll(Collection c) { - return list.removeAll(c); - } - - @Override - public boolean retainAll(Collection c) { - return list.retainAll(c); - } - - @Override - public void clear() { - list.clear(); - } - - @Override - public OpCode get(int index) { - return list.get(index); - } - - @Override - public OpCode set(int index, OpCode element) { - return list.set(index, element); - } - - @Override - public void add(int index, OpCode element) { - list.add(index, element); - } - - @Override - public OpCode remove(int index) { - return list.remove(index); - } - - @Override - public int indexOf(Object o) { - return list.indexOf(o); - } - - @Override - public int lastIndexOf(Object o) { - return list.lastIndexOf(o); - } - - @Override - public ListIterator listIterator() { - return list.listIterator(); - } - - @Override - public ListIterator listIterator(int index) { - return list.listIterator(index); - } - - @Override - public List subList(int fromIndex, int toIndex) { - return list.subList(fromIndex, toIndex); - } - - - -} diff --git a/del/mano-server-projects/pom.xml b/del/mano-server-projects/pom.xml deleted file mode 100644 index e2ecf08..0000000 --- a/del/mano-server-projects/pom.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - 4.0.0 - com.diosay - mano-server-projects - 1.0-SNAPSHOT - pom - - ../mano - mano-web - open-tpl - mano-server - - - UTF-8 - 1.8 - 1.8 - - ManoServer Projects - \ No newline at end of file diff --git a/del/mano.project/mano-tplib/nb-configuration.xml b/del/mano.project/mano-tplib/nb-configuration.xml deleted file mode 100644 index 99bddf6..0000000 --- a/del/mano.project/mano-tplib/nb-configuration.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - ManoLicense - - diff --git a/del/mano.project/mano-tplib/pom.xml b/del/mano.project/mano-tplib/pom.xml deleted file mode 100644 index 0369681..0000000 --- a/del/mano.project/mano-tplib/pom.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - 4.0.0 - - com.diosay - mano.project - 1.0-SNAPSHOT - - mano-tplib - jar - - - com.alibaba - fastjson - 1.1.42 - - - ${project.groupId} - mano - ${project.version} - - - - 1.7 - 1.7 - - \ No newline at end of file diff --git a/del/mano.project/mano-tplib/src/main/java/com/diosay/tplib/FastJsonConverter.java b/del/mano.project/mano-tplib/src/main/java/com/diosay/tplib/FastJsonConverter.java deleted file mode 100644 index 0f9ad29..0000000 --- a/del/mano.project/mano-tplib/src/main/java/com/diosay/tplib/FastJsonConverter.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. - */ -package com.diosay.tplib; - -import com.alibaba.fastjson.*; -import com.alibaba.fastjson.serializer.SerializerFeature; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import mano.data.json.*; - -/** - * @see https://github.com/alibaba/fastjson - * @author johnwhang - */ -public class FastJsonConverter implements JsonConverter { - - @Override - public JsonOption getOption(String name) { - return null; - } - - @Override - public String serialize(Object src) throws JsonException { - try { - return JSON.toJSONString(src); - } catch (Throwable ex) { - throw new JsonException(ex); - } - } - - @Override - public String serialize(Object src, Map options) throws JsonException { - try { - List list = new ArrayList(); - for (Object obj : options.values()) { - if (obj != null && obj instanceof SerializerFeature) { - list.add((SerializerFeature) obj); - } - } - return JSON.toJSONString(src, list.toArray(new SerializerFeature[0])); - } catch (Throwable ex) { - throw new JsonException(ex); - } - } - - @Override - public Object deserialize(String json) throws JsonException { - try { - return JSON.parseObject(json); - } catch (Throwable ex) { - throw new JsonException(ex); - } - } - - @Override - public Object deserialize(String json, Map options) throws JsonException { - try { - return JSON.parseObject(json); - } catch (Throwable ex) { - throw new JsonException(ex); - } - } - - @Override - public T deserialize(String json, Class clazz) throws JsonException { - try { - return JSON.parseObject(json, clazz); - } catch (Throwable ex) { - throw new JsonException(ex); - } - } - - @Override - public T deserialize(String json, Class clazz, Map options) throws JsonException { - try { - return JSON.parseObject(json, clazz); - } catch (Throwable ex) { - throw new JsonException(ex); - } - } -} diff --git a/del/mano.project/pom.xml b/del/mano.project/pom.xml deleted file mode 100644 index 8cfff85..0000000 --- a/del/mano.project/pom.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - 4.0.0 - com.diosay - mano.project - 1.0-SNAPSHOT - pom - Mano :: Projects - - ../mano - ../mano-server-projects/mano-web - ../mano-server-projects/open-tpl - ../mano-server-projects/mano-server - ../maven-manoserver-plugin - mano-tplib - - - UTF-8 - - \ No newline at end of file diff --git a/del/maven-manoserver-plugin/nbactions.xml b/del/maven-manoserver-plugin/nbactions.xml deleted file mode 100644 index 9ab1b2b..0000000 --- a/del/maven-manoserver-plugin/nbactions.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - CUSTOM-deploy - deploy - - deploy - - - diff --git a/del/maven-manoserver-plugin/pom.xml b/del/maven-manoserver-plugin/pom.xml deleted file mode 100644 index b756324..0000000 --- a/del/maven-manoserver-plugin/pom.xml +++ /dev/null @@ -1,53 +0,0 @@ - - - 4.0.0 - com.diosay - maven-manoserver-plugin - maven-plugin - 1.0-SNAPSHOT - Mano :: Server Maven Mojo - http://maven.apache.org - - - org.apache.maven - maven-plugin-api - 3.0.3 - - - ${project.groupId} - open-tpl - 1.4.0-BETA - - - - UTF-8 - 1.8 - 1.8 - - - - - org.apache.maven.plugins - maven-plugin-plugin - 3.3 - - - - - true - - - - - - - releases - http://127.0.0.1:8081/nexus/content/repositories/releases - - - snapshots - http://127.0.0.1:8081/nexus/content/repositories/snapshots - - - - \ No newline at end of file diff --git a/del/maven-manoserver-plugin/src/main/java/com/diosay/maven/manoserver/plugin/DeployMojo.java b/del/maven-manoserver-plugin/src/main/java/com/diosay/maven/manoserver/plugin/DeployMojo.java deleted file mode 100644 index 9c280f2..0000000 --- a/del/maven-manoserver-plugin/src/main/java/com/diosay/maven/manoserver/plugin/DeployMojo.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. - */ -package com.diosay.maven.manoserver.plugin; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.apache.maven.plugin.AbstractMojo; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugin.MojoFailureException; - -/** - * - * @author jun - * @phase install - * @goal deploy - */ -public class DeployMojo extends AbstractMojo { - - /** - * @parameter expression=”${aSystemProperty}” - * default-value=”${anExpression}” - */ - private String buildDirectory; - - /** - * @parameter expression=”${aSystemProperty}” - * default-value=”${anExpression}” - */ - private String resourceDirectory; - - /** - * @parameter expression=”${aSystemProperty}” - * default-value=”${anExpression}” - */ - private String libDirectory; - - @Override - public void execute() throws MojoExecutionException, MojoFailureException { - - this.getLog().info("------------------------------------------------------------------------"); - this.getLog().info("Mano Web Application Deploy"); - this.getLog().info("------------------------------------------------------------------------"); - - File src = new File(resourceDirectory); - if (!src.exists() || !src.isDirectory()) { - this.getLog().error(new IOException("源目录不存在或不是目录:" + resourceDirectory)); - } else { - this.getLog().info("copying " + src + " to " + buildDirectory); - try { - this.getLog().info("deleting " + buildDirectory); - Utility.deleteFolder(buildDirectory); - Utility.copyFolder(src, new File(buildDirectory)); - } catch (IOException ex) { - this.getLog().error(ex); - } - - this.getLog().info("copying " + libDirectory + " to " + buildDirectory + "/WEB-INF/lib"); - try { - this.getLog().info("deleting " + buildDirectory + "/WEB-INF/lib"); - Utility.deleteFolder(buildDirectory + "/WEB-INF/lib"); - Utility.copyFolder(new File(libDirectory), new File(buildDirectory + "/WEB-INF/lib")); - } catch (IOException ex) { - this.getLog().error(ex); - } - } - this.getLog().info("done"); - } - - static class Utility { - - public static void copyFile(String src, String target) throws IOException { - copyFile(new File(src), new File(target)); - } - - public static void copyFile(File src, File target) throws IOException { - if (!src.exists() || !src.isFile()) { - throw new FileNotFoundException("源文件不存或不是文件:" + src); - } - - if (target.exists() && target.isFile()) { - target.delete(); - } - - File parent = target.getParentFile(); - if (!parent.exists() || (parent.exists() && !parent.isDirectory())) { - parent.mkdirs(); - } - - target.createNewFile(); - - try (FileInputStream input = new FileInputStream(src)) { - try (FileOutputStream out = new FileOutputStream(target)) { - out.getChannel().transferFrom(input.getChannel(), 0, input.getChannel().size()); - } - } - } - - public static void copyFolder(String src, String target) throws IOException { - copyFolder(new File(src), new File(target)); - } - - public static void copyFolder(File src, File target) throws IOException { - if (!src.exists() || !src.isDirectory()) { - throw new FileNotFoundException("源目录不存在或不是目录:" + src); - } - if (!target.exists() || !target.isDirectory()) { - if (!target.mkdirs()) { - throw new IOException("创建目标目录失败:" + target); - } - } - for (File child : src.listFiles()) { - if (child.isDirectory()) { - copyFolder(src.toString() + "/" + child.getName(), target.toString() + "/" + child.getName()); - } else if (child.isFile()) { - copyFile(src.toString() + "/" + child.getName(), target.toString() + "/" + child.getName()); - } - } - } - - public static void deleteFile(String filename) { - new File(filename).delete(); - } - - public static void deleteFolder(String filename) { - deleteFolder(new File(filename)); - } - - public static void deleteFolder(File file) { - if (file.exists() && file.isDirectory()) { - for (File child : file.listFiles()) { - if (child.isFile()) { - child.delete(); - } else { - deleteFolder(child); - } - } - file.delete(); - } - - } - } - -} diff --git a/del/maven-manoserver-plugin/src/main/java/com/diosay/maven/manoserver/plugin/OtpCompileMojo.java b/del/maven-manoserver-plugin/src/main/java/com/diosay/maven/manoserver/plugin/OtpCompileMojo.java deleted file mode 100644 index 42bc4da..0000000 --- a/del/maven-manoserver-plugin/src/main/java/com/diosay/maven/manoserver/plugin/OtpCompileMojo.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. - */ -package com.diosay.maven.manoserver.plugin; - -import com.diosay.otpl.CompilationContext; -import com.diosay.otpl.runtime.Interpreter; -import java.io.File; -import java.io.IOException; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.apache.maven.plugin.AbstractMojo; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugin.MojoFailureException; - -/** - * - * @author junhwong - */ -public class OtpCompileMojo extends AbstractMojo { - - /** - * @parameter expression=”${aSystemProperty}” - * default-value=”${anExpression}” - */ - private String otplTemplateSourceDirectory; - /** - * @parameter expression=”${aSystemProperty}” - * default-value=”${anExpression}” - */ - private String otplTargetDirectory; - - @Override - public void execute() throws MojoExecutionException, MojoFailureException { - - this.getLog().info("------------------------------------------------------------------------"); - this.getLog().info("OTPL Template Pakaging..."); - this.getLog().info("------------------------------------------------------------------------"); - File targetDir = new File(otplTargetDirectory); - File sourceDir = new File(otplTemplateSourceDirectory); - if (!sourceDir.exists() || !sourceDir.isDirectory()) { - this.getLog().error("模板根路径不存在"); - return; - } else if (!sourceDir.canRead()) { - this.getLog().error("模板根路径不能读"); - return; - } - try { - if (!targetDir.exists() || !targetDir.createNewFile()) { - - this.getLog().error("模板编译目标路径不存在,尝试创建失败!"); - return; - } else if (!targetDir.canRead() || !targetDir.canWrite()) { - this.getLog().error("模板根路径不能读或写"); - return; - } - } catch (Exception ex) { - this.getLog().debug(ex); - return; - } - CompilationContext context = new CompilationContext() { - - @Override - public String getSourcePath() { - return otplTemplateSourceDirectory; - } - - @Override - public String getTargetPath() { - return otplTargetDirectory; - } - - }; - Interpreter interpreter = new Interpreter(); - sourceDir.list((dir, name) -> { - try { - this.v(interpreter, context, "~/" + name, dir.toString(), name); - } catch (Exception ex) { - this.getLog().debug(ex); - } - return false; - }); - - } - - void v(Interpreter interpreter, CompilationContext context, String parent, String path, String name) throws Exception { - File file = new File(path + "/" + name); - if (!file.exists()) { - } else if (file.isFile()) { - interpreter.compileFile(context, parent + "/" + name); - } else if (file.isDirectory()) { - file.list((dir, name2) -> { - try { - this.v(interpreter, context, parent + "/" + name, dir.toString(), name2); - } catch (Exception ex) { - this.getLog().debug(ex); - } - return false; - }); - } - } -} diff --git a/del/maven-manoserver-plugin/src/main/java/com/diosay/maven/manoserver/plugin/RunMojo.java b/del/maven-manoserver-plugin/src/main/java/com/diosay/maven/manoserver/plugin/RunMojo.java deleted file mode 100644 index 3d8c7d7..0000000 --- a/del/maven-manoserver-plugin/src/main/java/com/diosay/maven/manoserver/plugin/RunMojo.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. - */ -package com.diosay.maven.manoserver.plugin; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.UUID; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.apache.maven.plugin.AbstractMojo; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugin.MojoFailureException; -//http://blog.sina.com.cn/s/blog_3e3e61fb0100k08z.html -//http://www.kankanews.com/ICkengine/archives/78579.shtml -//http://java-xp.iteye.com/blog/1625574 -//http://blog.csdn.net/yuxinleipp/article/details/7633600 - -/** - * - * @author jun - * @phase install - * @goal run - */ -public class RunMojo extends AbstractMojo { - - /** - * @parameter expression=”${aSystemProperty}” - * default-value=”${anExpression}” - */ - private String serverDirectory; - /** - * @parameter expression=”${aSystemProperty}” - * default-value=”${anExpression}” - */ - private String resourceDirectory; - - /** - * @parameter expression=”${aSystemProperty}” - * default-value=”${anExpression}” - */ - private String libDirectory; - private final String template = ""; - - @Override - public void execute() throws MojoExecutionException, MojoFailureException { - this.getLog().info("------------------------------------------------------------------------"); - this.getLog().info("Mano Server Run"); - this.getLog().info("------------------------------------------------------------------------"); - - String content = String.format(template, resourceDirectory, libDirectory); - File cfgPath = new File(serverDirectory + "/conf/apps"); - if (!cfgPath.exists() || !cfgPath.isDirectory()) { - cfgPath.mkdirs(); - } - File cfg = new File(serverDirectory + "/conf/apps/" + Integer.toHexString(UUID.randomUUID().hashCode()) + ".xml"); - try { - cfg.createNewFile(); - try (FileOutputStream out = new FileOutputStream(cfg)) { - out.write(content.getBytes("utf-8")); - } - } catch (IOException ex) { - this.getLog().debug(ex); - } - - Runtime.getRuntime().addShutdownHook(new Thread(() -> { - getLog().debug("deletting " + cfg); - cfg.delete(); - })); - - Process process = null; - try { - //this.getPluginContext()."cmd.exe /C start " + - process = Runtime.getRuntime().exec(serverDirectory + "/bin/run.bat"); - //http://blog.163.com/zhao_jinggui/blog/static/169620429201161163711467/ - final InputStream err = process.getErrorStream(); - final InputStream in = process.getInputStream(); - - new Thread(() -> { - while (true) { - try { - System.err.print((char) err.read()); - } catch (IOException ex) { - this.getLog().debug(ex); - break; - } - } - }).start(); - - new Thread(() -> { - while (true) { - try { - System.out.print((char) in.read()); - } catch (IOException ex) { - this.getLog().debug(ex); - break; - } - } - }).start(); - - process.waitFor(); - err.close(); - in.close(); - process.destroy(); - - } catch (IOException ex) { - if (process != null) { - process.destroyForcibly(); - } - ex.printStackTrace(System.out); - } catch (InterruptedException ex) { - if (process != null) { - process.destroyForcibly(); - } - getLog().debug("deletting " + cfg); - cfg.delete(); - } - getLog().debug("deletting " + cfg); - cfg.delete(); - System.out.println("manoserver exit."); - } - - @Override - protected void finalize() throws Throwable{ - System.out.println("manoserver exit."); - super.finalize(); - - } - -} diff --git a/del/test-webapp-projects/pom.xml b/del/test-webapp-projects/pom.xml deleted file mode 100644 index 550b6cc..0000000 --- a/del/test-webapp-projects/pom.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - 4.0.0 - com.diosay - test-webapp-projects - 1.0-SNAPSHOT - pom - Test Webapp Projects - - test-webapp-model - test-webapp - test-webapp-dao - - - UTF-8 - 1.8 - 1.8 - - - \ No newline at end of file diff --git a/del/test-webapp-projects/test-webapp-dao/nbactions.xml b/del/test-webapp-projects/test-webapp-dao/nbactions.xml deleted file mode 100644 index 9ab1b2b..0000000 --- a/del/test-webapp-projects/test-webapp-dao/nbactions.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - CUSTOM-deploy - deploy - - deploy - - - diff --git a/del/test-webapp-projects/test-webapp-dao/pom.xml b/del/test-webapp-projects/test-webapp-dao/pom.xml deleted file mode 100644 index 51ea4ce..0000000 --- a/del/test-webapp-projects/test-webapp-dao/pom.xml +++ /dev/null @@ -1,40 +0,0 @@ - - - 4.0.0 - - com.diosay - test-webapp-projects - 1.0-SNAPSHOT - - test-webapp-dao - jar - - - org.hibernate - hibernate-core - 4.3.6.Final - - - mysql - mysql-connector-java - 5.1.31 - - - org.apache.hadoop - hadoop-project - 2.1.1-beta - pom - - - - - releases - http://127.0.0.1:8081/nexus/content/repositories/releases - - - snapshots - http://127.0.0.1:8081/nexus/content/repositories/snapshots - - - - \ No newline at end of file diff --git a/del/test-webapp-projects/test-webapp-dao/src/main/java/com/diosay/test/webapp/dao/SessionHelper.java b/del/test-webapp-projects/test-webapp-dao/src/main/java/com/diosay/test/webapp/dao/SessionHelper.java deleted file mode 100644 index 1a14ba6..0000000 --- a/del/test-webapp-projects/test-webapp-dao/src/main/java/com/diosay/test/webapp/dao/SessionHelper.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. - */ -package com.diosay.test.webapp.dao; - -import java.net.URL; -import org.hibernate.SessionFactory; -import org.hibernate.boot.registry.StandardServiceRegistry; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.cfg.Configuration; - -/** - * - * @author jun - */ -public class SessionHelper { - - public static SessionFactory getSessionFactory(URL url) { - Configuration cfg = new Configuration().configure(url); - StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()); - StandardServiceRegistry ssr = ssrb.build(); - java.sql.Date d; - return cfg.buildSessionFactory(ssr); - } - -} diff --git a/del/test-webapp-projects/test-webapp-model/nbactions.xml b/del/test-webapp-projects/test-webapp-model/nbactions.xml deleted file mode 100644 index 9ab1b2b..0000000 --- a/del/test-webapp-projects/test-webapp-model/nbactions.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - CUSTOM-deploy - deploy - - deploy - - - diff --git a/del/test-webapp-projects/test-webapp-model/pom.xml b/del/test-webapp-projects/test-webapp-model/pom.xml deleted file mode 100644 index 2e6b02a..0000000 --- a/del/test-webapp-projects/test-webapp-model/pom.xml +++ /dev/null @@ -1,40 +0,0 @@ - - - 4.0.0 - - com.diosay - test-webapp-projects - 1.0-SNAPSHOT - - test-webapp-model - Test Webapp Model - jar - - - ${project.groupId} - test-webapp-dao - ${project.version} - - - - - - src/main/java - - - **/*.hbm.xml - - - - - - - releases - http://127.0.0.1:8081/nexus/content/repositories/releases - - - snapshots - http://127.0.0.1:8081/nexus/content/repositories/snapshots - - - \ No newline at end of file diff --git a/del/test-webapp-projects/test-webapp-model/src/main/java/com/diosay/test/webapp/model/Product.hbm.xml b/del/test-webapp-projects/test-webapp-model/src/main/java/com/diosay/test/webapp/model/Product.hbm.xml deleted file mode 100644 index 80a1a31..0000000 --- a/del/test-webapp-projects/test-webapp-model/src/main/java/com/diosay/test/webapp/model/Product.hbm.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - diff --git a/del/test-webapp-projects/test-webapp-model/src/main/java/com/diosay/test/webapp/model/Product.java b/del/test-webapp-projects/test-webapp-model/src/main/java/com/diosay/test/webapp/model/Product.java deleted file mode 100644 index 2171b7c..0000000 --- a/del/test-webapp-projects/test-webapp-model/src/main/java/com/diosay/test/webapp/model/Product.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.diosay.test.webapp.model; - -/* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. - */ - - - -/** - * - * @author jun - */ -public class Product { - private int id; - public int getId(){ - return id; - } - public void setId(int val){ - id=val; - } - private String name; - public String getName(){ - return name; - } - public void setName(String val){ - name=val; - } -} diff --git a/del/test-webapp-projects/test-webapp/nb-configuration.xml b/del/test-webapp-projects/test-webapp/nb-configuration.xml deleted file mode 100644 index 3501df9..0000000 --- a/del/test-webapp-projects/test-webapp/nb-configuration.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - 1.7-web - - diff --git a/del/test-webapp-projects/test-webapp/nbactions.xml b/del/test-webapp-projects/test-webapp/nbactions.xml deleted file mode 100644 index a018199..0000000 --- a/del/test-webapp-projects/test-webapp/nbactions.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - CUSTOM-manoserver:deploy - manoserver:deploy - - manoserver:deploy - - - - CUSTOM-manoserver:run - manoserver:run - - manoserver:run - - - diff --git a/del/test-webapp-projects/test-webapp/pom.xml b/del/test-webapp-projects/test-webapp/pom.xml deleted file mode 100644 index cfecefe..0000000 --- a/del/test-webapp-projects/test-webapp/pom.xml +++ /dev/null @@ -1,124 +0,0 @@ - - - 4.0.0 - - com.diosay - test-webapp-projects - 1.0-SNAPSHOT - - test-webapp - - jar - Test Webapp - - - - C:\Users\jun\Desktop\server\test - - E:\repositories\java\mano\mano-server-projects\mano-server\target\build - ${project.build.directory}/endorsed - ${basedir}/webapp/WEB-INF/conf/manoserver.proerties - - - - - - com.diosay - mano - 1.0-SNAPSHOT - compile - - - ${project.groupId} - test-webapp-model - ${project.version} - - - - - - - - - com.diosay - maven-manoserver-plugin - 1.0-SNAPSHOT - - ${basedir}/src/main/webapp - ${basedir}/target/build/lib - ${build.dir} - ${server.dir} - - - - - org.apache.maven.plugins - maven-dependency-plugin - - - - copy-dependencies - install - - copy-dependencies - - - ${basedir}/target/build/lib - true - false - false - - - - - - maven-resources-plugin - 2.6 - - - - copy-resources-conf - install - - copy-resources - - - ${basedir}/target/build/lib - - - ${basedir}/target - - ${project.artifactId}*.jar - - - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.1 - - 1.8 - 1.8 - - ${endorsed.dir} - - - - - - - diff --git a/del/test-webapp-projects/test-webapp/src/main/java/com/diosay/test/webapp/App.java b/del/test-webapp-projects/test-webapp/src/main/java/com/diosay/test/webapp/App.java deleted file mode 100644 index 6be30d8..0000000 --- a/del/test-webapp-projects/test-webapp/src/main/java/com/diosay/test/webapp/App.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. - */ -package com.diosay.test.webapp; - -import mano.web.WebApplication; - -/** - * - * @author jun - */ -public class App extends WebApplication { - - @Override - protected void onDestory() { - super.onDestory(); - } - - /** - * 用于DEBUG的启动方法。 - * @param vargs - */ - public static void main(String[] vargs) { - ServerStartupArgs args = createStartupArgs(); - args.libDirectory="E:\\repositories\\java\\mano\\test-webapp-projects\\test-webapp\\target\\build\\lib"; - args.serverDirectory="E:\\repositories\\java\\mano\\mano-server-projects\\mano-server\\target\\build"; - args.webappDirectory="E:\\repositories\\java\\mano\\test-webapp-projects\\test-webapp\\src\\main\\webapp"; - startDebugServer(args); - } - -} diff --git a/del/test-webapp-projects/test-webapp/src/main/java/com/diosay/test/webapp/CheckLogin.java b/del/test-webapp-projects/test-webapp/src/main/java/com/diosay/test/webapp/CheckLogin.java deleted file mode 100644 index e1afd72..0000000 --- a/del/test-webapp-projects/test-webapp/src/main/java/com/diosay/test/webapp/CheckLogin.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. - */ -package com.diosay.test.webapp; - -import mano.web.ViewContext; -import mano.web.ActionFilter; -import mano.web.HttpSession; - -/** - * - * @author jun - */ -public class CheckLogin implements ActionFilter { - - @Override - public boolean onActionExecuting(ViewContext context) { - if("home".equalsIgnoreCase(context.getController()) && "login".equalsIgnoreCase(context.getAction())){ - return true; - } - - HttpSession session = context.getContext().getSession(); - if (session == null || session.get("sun") == null) { - context.getContext().getResponse().redirect("/home/login"); - return false; - } - return true; - } - - @Override - public boolean onActionExecuted(ViewContext context) { - return true; - } - -} diff --git a/del/test-webapp-projects/test-webapp/src/main/java/com/diosay/test/webapp/controllers/Home.java b/del/test-webapp-projects/test-webapp/src/main/java/com/diosay/test/webapp/controllers/Home.java deleted file mode 100644 index a65a8f8..0000000 --- a/del/test-webapp-projects/test-webapp/src/main/java/com/diosay/test/webapp/controllers/Home.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.diosay.test.webapp.controllers; - -import java.io.IOException; -import mano.http.HttpPostFile; -import mano.web.Controller; -import mano.web.PathParam; -import mano.web.UrlMapping; - -/** - * - * @author jun - */ -@UrlMapping -public class Home extends Controller { - - @UrlMapping - public void index() { - this.getLogger().info("=====:index:" + this.session("uid")); - - view(); - } - - @UrlMapping - public void login() { - this.getLogger().info("=====:login:" + this.query("tid")); - view(); - } - - @UrlMapping - public void doLogin() throws IOException { - - HttpPostFile f = this.file("fn"); - if (f != null) { - set("postfile", f.getOriginal()); - f.savaAs(this.getContext().getServer().mapPath("upfile/abc") + f.getExtension()); - } - set("posttext", this.form("username")); - this.session("sun", this.form("username")); - view(); - - /* - URL url=null; - try { - url = new File(this.getContext().getServer().mapPath("WEB-INF/hibernate.cfg.xml")).toURI().toURL(); - } catch (MalformedURLException ex) { - this.getLogger().error(null, ex); - return; - } - - - - Session session =SessionHelper.getSessionFactory(url).openSession(); - Product entity = new Product(); - Transaction trans = session.beginTransaction(); - session.save(entity); - trans.commit(); - session.flush(); - session.close(); - this.text(entity.getId()+"");*/ - } - - @UrlMapping("/foo/{id}") - void foo(@PathParam("id") int id) { - this.text("foo:" + id); - } - - @UrlMapping("/bar/{id}") - void bar(@PathParam("id") long id) { - this.text("bar:" + id); - } - -} diff --git a/del/test-webapp-projects/test-webapp/src/main/java/com/diosay/test/webapp/controllers/My.java b/del/test-webapp-projects/test-webapp/src/main/java/com/diosay/test/webapp/controllers/My.java deleted file mode 100644 index d53d17e..0000000 --- a/del/test-webapp-projects/test-webapp/src/main/java/com/diosay/test/webapp/controllers/My.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.diosay.test.webapp.controllers; - -import com.diosay.test.webapp.CheckLogin; -import mano.web.Controller; -import mano.web.Filter; -import mano.web.UrlMapping; - -/** - * - * @author jun - */ -public class My extends Controller { - - @Filter(CheckLogin.class) - @UrlMapping - void index() { - set("sun", session("sun")); - view(); - } -} diff --git a/del/test-webapp-projects/test-webapp/src/main/webapp/WEB-INF/hibernate.cfg.xml b/del/test-webapp-projects/test-webapp/src/main/webapp/WEB-INF/hibernate.cfg.xml deleted file mode 100644 index ec794dc..0000000 --- a/del/test-webapp-projects/test-webapp/src/main/webapp/WEB-INF/hibernate.cfg.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - - true - - jdbc:mysql://localhost:3306/test - - root - - rootroot - - com.mysql.jdbc.Driver - - 1 - - thread - - org.hibernate.dialect.MySQLDialect - - create - - - - - - \ No newline at end of file diff --git a/del/test-webapp-projects/test-webapp/src/main/webapp/WEB-INF/mano.web.xml b/del/test-webapp-projects/test-webapp/src/main/webapp/WEB-INF/mano.web.xml deleted file mode 100644 index 14ba18e..0000000 --- a/del/test-webapp-projects/test-webapp/src/main/webapp/WEB-INF/mano.web.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - web_application - 0.0.0.0 - org\.osgi\.framework\.**{[\w_\.]+} - ~/WEB-INF/lib,~/WEB-INF/classes - private - com.diosay.test.webapp.App - - - - - org.osgi.framework.** - - - - ~/WEB-INF/hibernate.cfg.xml - true - controller.package.rule_section - - -
- */test-webapp-*.jar -
-
- - - -
diff --git a/del/test-webapp-projects/test-webapp/src/main/webapp/WEB-INF/manoserver.properties b/del/test-webapp-projects/test-webapp/src/main/webapp/WEB-INF/manoserver.properties deleted file mode 100644 index ab67c8d..0000000 --- a/del/test-webapp-projects/test-webapp/src/main/webapp/WEB-INF/manoserver.properties +++ /dev/null @@ -1,38 +0,0 @@ -#server.props -server.dir=~/ -ext.dependencies=path,"path path" -ext.exports=name:type,name:type - -service.http_service.class=mano.http.HttpService -service.http_service.address = 0.0.0.0:9999 -service.http_service.disabled=false - -#http.service -.buffer.size=4k -.connection.max=1024 -request.controller=home -request.action=index -module.static.class=class -module.static.extction.js=text/js - - -#commit -logging.root.name=Root_Logger -logging.root.level=ALL -logging.root.handler.def.class=Console_Handler -logging.root.handler.def.level=ALL -logging.root.handler.def.formatter=Default_formatter - -#web.props -.name=default_application -.host=*.9999 -.path=/ -logging.handlers=com.jar,com.jar - -#mapping -type=mime - - - - - diff --git a/del/test-webapp-projects/test-webapp/src/main/webapp/index.html b/del/test-webapp-projects/test-webapp/src/main/webapp/index.html deleted file mode 100644 index 58b4d02..0000000 --- a/del/test-webapp-projects/test-webapp/src/main/webapp/index.html +++ /dev/null @@ -1,10 +0,0 @@ - - - - Start Page h - - - -

Hello World!

- - diff --git a/del/test-webapp-projects/test-webapp/src/main/webapp/views/home/dologin.html b/del/test-webapp-projects/test-webapp/src/main/webapp/views/home/dologin.html deleted file mode 100644 index 412eb28..0000000 --- a/del/test-webapp-projects/test-webapp/src/main/webapp/views/home/dologin.html +++ /dev/null @@ -1,13 +0,0 @@ - - - - jump - - - - -

POST TEXT:

-

POST FILE:{{postfile}}

-
login completed.enter my page({{sun}})
- - diff --git a/del/test-webapp-projects/test-webapp/src/main/webapp/views/home/index.html b/del/test-webapp-projects/test-webapp/src/main/webapp/views/home/index.html deleted file mode 100644 index e5007eb..0000000 --- a/del/test-webapp-projects/test-webapp/src/main/webapp/views/home/index.html +++ /dev/null @@ -1,16 +0,0 @@ - - - - - test - - - - - - - diff --git a/del/test-webapp-projects/test-webapp/src/main/webapp/views/home/login.html b/del/test-webapp-projects/test-webapp/src/main/webapp/views/home/login.html deleted file mode 100644 index 631983c..0000000 --- a/del/test-webapp-projects/test-webapp/src/main/webapp/views/home/login.html +++ /dev/null @@ -1,22 +0,0 @@ - - - - login - - - - -
-
-
    -
  • username
  • -
  • - - -
  • -
-
-
- - diff --git a/del/test-webapp-projects/test-webapp/src/main/webapp/views/my/index.html b/del/test-webapp-projects/test-webapp/src/main/webapp/views/my/index.html deleted file mode 100644 index 5fbcfdc..0000000 --- a/del/test-webapp-projects/test-webapp/src/main/webapp/views/my/index.html +++ /dev/null @@ -1,11 +0,0 @@ - - - - welcome - - - - -
your login name:{{sun}}
- -