Integrating It All
[ 340 ]
Ideally you want to be able to visualize the code you have just generated. In the
above Spock test, you will notice that I've added a CompilationConfiguration
class with a CompilationCustomizer to the GroovyClassLoader class. This
compilation customizer uses a visitor, AstNodeToScriptVisitor, that is part of
the groovyConsole sources. This visitor traverses the generated ASTNode tree and
generates a text view of the generated code:
class ASTLogCompilationCustomizer extends CompilationCustomizer {
final PrintStream out
ASTLogCompilationCustomizer(CompilePhase compilePhase,
PrintStream out) {
super(compilePhase)
this.out = out
}
void call(SourceUnit source, GeneratorContext context,
ClassNode classNode) throws CompilationFailedException {
StringWriter writer = new StringWriter()
new AstNodeToScriptVisitor(writer).visitClass(classNode)
out.println writer
}
}
Running the tests will produce an HTML report in the server/build/reports/tests
directory. There is a link in the report to the standard output from the test, which
contains the pretty printed version of the generated code. This is tremendously
useful when debugging the generated output from an AST transformation.
The game server
Now we will look at building a simple game server that exploits the DSL. The
server is built upon Spring MVC using Spring Boot which is a convention over
configuration version of the Spring framework that allows you to get up and
running quickly—http://projects.spring.io/spring-boot/.
The server responds to HTTP requests via AJAX and returns JSONP. Each response
will contain the latest version of the game engine state along with a session ID and
the name of the next page to go to in the UI. In between requests, the session state is
stored in a MongoDB collection. Let's look at the Gradle file that builds this server:
buildscript {
repositories {
jcenter()
maven { url "http://repo.spring.io/libs-release" }
}
http://www.ebook3000.com