A Groovy DSL from Scratch in Two Hours
Through DZone I found Architecture Rules, a lovely little framework that abstracts JDepend. Architecture Rules is configured via its own XML schema.
Join the DZone community and get the full member experience.
Join For FreeToday is my lucky day. Through DZone I found Architecture Rules, a lovely little framework that abstracts JDepend.
Architecture Rules is configured via its own XML schema. Here's an example:
<architecture>
<configuration>
<sources no-packages="exception">
<source not-found="exception">spring.jar</source>
</sources>
<cyclicaldependency test="true"/>
</configuration>
<rules>
<rule id="beans-web">
<comment>
org.springframework.beans.factory cannot depend on
org.springframework.web
</comment>
<packages>
<package>org.springframework.beans.factory</package>
</packages>
<violations>
<violation>org.springframework.web</violation>
</violations>
</rule>
<rule id="must-fail">
<comment>
org.springframework.orm.hibernate3 cannot depend on
org.springframework.core.io
</comment>
<packages>
<package>org.springframework.orm.hibernate3</package>
</packages>
<violations>
<violation>org.springframework.core.io</violation>
</violations>
</rule>
</rules>
</architecture>
On top of the nice configuration API I wrote my own Groovy DSL. And I did it in 2 hours.
architecture {
// cyclic dependency check enabled by default
jar "spring.jar"
rules {
"beans-web" {
comment = "org.springframework.beans.factory cannot depend on org.springframework.web"
'package' "org.springframework.beans"
violation "org.springframework.web"
}
"must-fail" {
comment = "org.springframework.orm.hibernate3 cannot depend on org.springframework.core.io"
'package' "org.springframework.orm.hibernate3"
violation "org.springframework.core.io"
}
}
}
Now I will show you how I've build this DSL so you can learn how you can write your own.
This DSL like many others in Groovy uses the Builder syntax: method calls that take a Closure
as argument. As a reminder, a Closure
is at the same time a function and an object. You can call and execute it as a function and call methods and properties as an object.
To support this builder syntax you have to write methods that take as last argument a groovy.lang.Closure
object:
// example of builder syntax
someMethod {
}
// signature of method that will be called
// can be void or return an object, that's up to you
void someMethod(Closure cl) {
// do some other work
cl() // call Closure object
}
The first step is to create a class that will evaluate DSL configuration files. I've called it GroovyArchitecture
:
class GroovyArchitecture {
static void main(String[] args) {
runArchitectureRules(new File("architecture.groovy"))
}
static void runArchitectureRules(File dsl) {
Script dslScript = new GroovyShell().parse(dsl.text)
}
}
The GroovyArchitecture
class will evaluate a DSL file and get a groovy.lang.Script
object. If the class is launched through its main()
method it will read the architecture.groovy
file in the current directory.
Now that I've got the skeleton in place I have to add the first method that will be called by the DSL script: the architecture()
method.
The first method is usually the trickiest to implement, as when the script is executed this method will be called on the Script
object. Needless to say this object does not have an architecture()
method. Groovy does provide a way to add it through the MOP or Meta-Object Protocol.
Difficult words for an easy enough technique. Each object in Groovy has a MetaClass
object that handles all method calls that are executed on that object. What we need to do is create a custom MetaClass
object and assign it to the script object.
class GroovyArchitecture {
static void main(String[] args) {
runArchitectureRules(new File("architecture.groovy"))
}
static void runArchitectureRules(File dsl) {
Script dslScript = new GroovyShell().parse(dsl.text)
dslScript.metaClass = createEMC(dslScript.class, {
ExpandoMetaClass emc ->
})
dslScript.run()
}
static ExpandoMetaClass createEMC(Class clazz, Closure cl) {
ExpandoMetaClass emc = new ExpandoMetaClass(clazz, false)
cl(emc)
emc.initialize()
return emc
}
}
Let's go over this step by step. I've added the createEMC()
method which creates a groovy.lang.ExpandoMetaClass
object, initializes it and returns it (lines 16 to 23). Before initializing it the object is passed to a Closure
(line 19). This Closure
is passed as an argument to the createEMC()
method (lines 8 to 12).
I'm using the Closure
as a callback to customize the ExpandoMetaClass
object while hiding the details of creating and configuring it. The return value of the createEMC()
method is assigned to the metaClass
property of the DSL Script
object (line 8).
I'm also calling the run()
method on the DSL Script
object to execute the DSL script (line 13).
The ExpandoMetaClass
class comes with Groovy 1.1 and later and allows us to add custom methods via the Meta-Object Protocol. In other words, we can add any method we want to any object we want by assigning an ExpandoMetaClass
object to the metaClass
property of another object.
Now, how to add these methods then? I need to configure the ExpandoMetaClass
object:
class GroovyArchitecture {
static void main(String[] args) {
runArchitectureRules(new File("architecture.groovy"))
}
static void runArchitectureRules(File dsl) {
Script dslScript = new GroovyShell().parse(dsl.text)
dslScript.metaClass = createEMC(dslScript.class, {
ExpandoMetaClass emc ->
emc.architecture = {
Closure cl ->
}
})
dslScript.run()
}
static ExpandoMetaClass createEMC(Class clazz, Closure cl) {
ExpandoMetaClass emc = new ExpandoMetaClass(clazz, false)
cl(emc)
emc.initialize()
return emc
}
}
I'm assigning a Closure
to the architecture
property of the ExpandoMetaClass
object (lines 11 to 15). This Closure
will be the implementation of the architecture()
method and will also determine the arguments that method accepts. By assigning the architecture
property I've added this method to the DSL script via the MOP: architecture(Closure)
.
So, right now I can execute this DSL script without errors:
// architecture.groovy file
architecture {
}
Next step is to add the Architecture Rules classes to the mix.
import com.seventytwomiles.architecturerules.configuration.Configuration
import com.seventytwomiles.architecturerules.services.CyclicRedundancyServiceImpl
import com.seventytwomiles.architecturerules.services.RulesServiceImpl
class GroovyArchitecture {
static void main(String[] args) {
runArchitectureRules(new File("architecture.groovy"))
}
static void runArchitectureRules(File dsl) {
Script dslScript = new GroovyShell().parse(dsl.text)
Configuration configuration = new Configuration()
configuration.doCyclicDependencyTest = true
configuration.throwExceptionWhenNoPackages = true
dslScript.metaClass = createEMC(dslScript.class, {
ExpandoMetaClass emc ->
emc.architecture = {
Closure cl ->
}
})
dslScript.run()
new CyclicRedundancyServiceImpl(configuration)
.performCyclicRedundancyCheck()
new RulesServiceImpl(configuration).performRulesTest()
}
static ExpandoMetaClass createEMC(Class clazz, Closure cl) {
ExpandoMetaClass emc = new ExpandoMetaClass(clazz, false)
cl(emc)
emc.initialize()
return emc
}
}
The Configuration
class takes the configuration for the Architecture Rules framework. I'm assigning two useful default values (lines 12 to 14). The CyclicRedundancyServiceImpl
and RulesServiceImpl
classes perform the actual checks on the source code (lines 27 and 29).
The next step is to add the location of classes or JARs. I want to extend the DSL like this:
// architecture.groovy file
architecture {
classes "target/classes"
jar "myLibrary.jar"
}
Adding these two methods is more straightforward since I don't have to use ExpandoMetaClass
anymore. Instead, I'm assigning a delegate to the Closure
object that is passed as argument when executing the architecture()
method.
Before assigning a delegate however I have to create a new class: ArchitectureDelegate
. Any methods and properties that are called inside the Closure
will be delegated to an ArchitectureDelegate
object. Hence, the ArchitectureDelegate
class has to provide two methods: classes(String)
and jar(String)
.
import com.seventytwomiles.architecturerules.configuration.Configuration
class ArchitectureDelegate {
private Configuration configuration
ArchitectureDelegate(Configuration configuration) {
this.configuration = configuration
}
void classes(String name) {
this.configuration.addSource new SourceDirectory(name, true)
}
void jar(String name) {
classes name
}
}
As you can see the classes()
and jar()
methods are actual methods on the ArchitectureDelegate
class. Next step is to assign an ArchitectureDelegate
object as delegate to the Closure
passed to the architecture()
method.
import com.seventytwomiles.architecturerules.configuration.Configuration
import com.seventytwomiles.architecturerules.services.CyclicRedundancyServiceImpl
import com.seventytwomiles.architecturerules.services.RulesServiceImpl
class GroovyArchitecture {
static void main(String[] args) {
runArchitectureRules(new File("architecture.groovy"))
}
static void runArchitectureRules(File dsl) {
Script dslScript = new GroovyShell().parse(dsl.text)
Configuration configuration = new Configuration()
configuration.doCyclicDependencyTest = true
configuration.throwExceptionWhenNoPackages = true
dslScript.metaClass = createEMC(dslScript.class, {
ExpandoMetaClass emc ->
emc.architecture = {
Closure cl ->
cl.delegate = new ArchitectureDelegate(configuration)
cl.resolveStrategy = Closure.DELEGATE_FIRST
cl()
}
})
dslScript.run()
new CyclicRedundancyServiceImpl(configuration)
.performCyclicRedundancyCheck()
new RulesServiceImpl(configuration).performRulesTest()
}
static ExpandoMetaClass createEMC(Class clazz, Closure cl) {
ExpandoMetaClass emc = new ExpandoMetaClass(clazz, false)
cl(emc)
emc.initialize()
return emc
}
}
The Closure
's delegate
property takes the ArchitectureDelegate
object (line 22). The resolveStrategy
property is set to Closure.DELEGATE_FIRST
(line 23). This means any method or property called inside the Closure
will be delegated to the ArchitectureDelegate
object. I call the Closure
on line 25.
Time to add the rules()
method to the DSL:
// architecture.groovy file
architecture {
classes "target/classes"
jar "myLibrary.jar"
rules {
}
}
Where to add this method? To the delegate object of course.
import com.seventytwomiles.architecturerules.configuration.Configuration
class ArchitectureDelegate {
private Configuration configuration
ArchitectureDelegate(Configuration configuration) {
this.configuration = configuration
}
void classes(String name) {
this.configuration.addSource new SourceDirectory(name, true)
}
void jar(String name) {
classes name
}
void rules(Closure cl) {
cl.delegate = new RulesDelegate(configuration)
cl.resolveStrategy = Closure.DELEGATE_FIRST
cl()
}
}
Adding the rules()
method to the DSL syntax is as easy as adding the rules()
method to the ArchitectureDelegate
class (line 18 to 23). And so on. Each new Closure
in the DSL gets its own delegate object. You'll find the DSL script and the parsing code attached to this post.
Happy coding!
Opinions expressed by DZone contributors are their own.
Comments