Groovy for Domain-Specific Languages

Groovy for Domain-Specific Languages
eBook: $26.99
Formats: PDF, PacktLib, ePub and Mobi formats
save 15%!
Print + free eBook + free PacktLib access to the book: $71.98    Print cover: $44.99
save 6%!
Free Shipping!
UK, US, Europe and selected countries in Asia.
Also available on:
Table of Contents
Sample Chapters

Build your own Domain Specific Languages on top of Groovy Integrate your existing Java applications using Groovy-based Domain Specific Languages (DSLs) Develop a Groovy scripting interface to Twitter A step-by-step guide to building Groovy-based Domain Specific Languages that run seamlessly in the Java environment

Book Details

Language : English
Paperback : 312 pages [ 235mm x 191mm ]
Release Date : June 2010
ISBN : 184719690X
ISBN 13 : 9781847196903
Author(s) : Fergal Dearle
Topics and Technologies : All Books, Application Development, Java, Open Source

Table of Contents

Chapter 1: Introduction to DSL and Groovy
Chapter 2: Groovy Quick Start
Chapter 3: Groovy Closures
Chapter 4: Example DSL: GeeTwitter
Chapter 5: Power Groovy DSL features
Chapter 6: Existing Groovy DSLs
Chapter 7: Building a Builder
Chapter 8: Implementing a Rules DSL
Chapter 9: Integrating it all
  • Chapter 1: Introduction to DSL and Groovy
    • DSL: New name for an old idea
      • The evolution of programming languages
        • General-purpose languages
        • Spreadsheets and 4GLs
      • Language-oriented programming
      • Who are DSLs for?
        • A DSL for process engineers
        • Stakeholder participation
      • DSL design and implementation
      • External versus internal DSL
      • Operator overloading
    • Groovy
      • A natural fit with the JVM
      • Groovy language features
        • Static and optional typing
        • Native support for lists and maps
        • Closures
        • Groovy operator overloading
        • Regular expression support
        • Optional syntax
        • Groovy markup
    • Summary
  • Chapter 2: Groovy Quick Start
    • How to find and install Groovy
    • Running Groovy
      • The Groovy script engine—groovy
      • Shebang scripts
      • The Groovy shell: groovysh
      • The Groovy console: groovyConsole
      • The Groovy compiler: groovyc
    • Groovy IDE and editor integration
      • Netbeans
      • Eclipse
      • IntelliJ IDEA
      • Other IDEs and editors
    • Introducing the Groovy Language
      • Module structure
      • Groovy shorthand
        • Assumed imports
        • Default visibility, optional semicolon
        • Optional parentheses and types
        • Optional return keyword
      • Assertions
      • Autoboxing
      • Strings
      • Regular expressions
      • Methods and closures
      • Control structures
        • Groovy truth
        • Ternary and Elvis operators
        • Switch statement
        • Loops
      • Collections
        • Ranges
        • Lists
        • Maps
      • Operators
        • Spread and spread-dot
        • Null safe dereference
        • Operator overloading
    • Summary
  • Chapter 3: Groovy Closures
    • What is a closure
    • Closures and collection methods
    • Closures as method parameters
      • Method parameters as DSL
      • Forwarding parameters
    • Calling closures
    • Finding a named closure field
    • Closure parameters
      • Parameters and the doCall method
      • Passing multiple parameters
      • Enforcing zero parameters
      • Default parameter values
      • Curried parameters
    • Closure return values
    • Closure scope
      • this, owner, and delegate
    • Summary
  • Chapter 4: Example DSL: GeeTwitter
    • Twitter
    • Working with the Twitter APIs
      • Using Twitter4J Java APIs
        • Tweeting
        • Direct messages
        • Searching
        • Following
    • Groovy improvements
      • A Groovier way to find friends
        • Groovy searching
    • Removing boilerplate
      • Refactoring
        • Fleshing out GeeTwitter
      • Improving search
    • Adding a command-line interface
    • Adding built-in methods
    • Summary
  • Chapter 5: Power Groovy DSL features
    • Named parameters
      • Named parameters in DSLs
    • Builders
      • Builder design pattern
      • Using Groovy Builders
        • MarkupBuilder
      • Namespaced XML
      • GroovyMarkup and the builder design pattern
      • Using program logic with builders
      • Builders for every occasion
        • NodeBuilder
    • SwingBuilder
      • Griffon: Builders as DSL
    • Method pointers
    • Metaprogramming and the Groovy MOP
      • Reflection
        • Groovy Reflection shortcuts
      • Expandos
      • Categories
      • Metaclass
        • Pretended methods (MetaClass.invokeMethod)
      • Understanding this, delegate, and owner
    • How Builders work
    • ExpandoMetaClasses
      • Replacing methods
      • Adding or overriding static methods
      • Dynamic method naming
      • Adding overloaded methods
      • Adding constructors
    • Summary
  • Chapter 6: Existing Groovy DSLs
    • The Grails Object Relational Mapping (GORM)
      • Grails quick start
      • The grails-app directory
        • DataSource configuration
      • Building a GORM model
        • Using domain classes
      • Modeling relationships
        • Associations
        • Composition
        • Inheritance
      • Querying
        • Dynamic finders
        • GORM as a DSL
    • Gant
      • Ant
      • AntBuilder
      • Gant and AntBuilder
    • ATDD, BDD with GSpec, EasyB, and Spock
      • GSpec
      • EasyB
      • Spock
        • Blocks
      • BDD DSL style
    • Summary
  • Chapter 7: Building a Builder
    • Builder code structure
      • Closure method calls
        • Resolve Strategy: OWNER_FIRST
      • Pretended methods
        • invokeMethod
        • methodMissing
      • Closure delegate
    • BuilderSupport
      • BuilderSupport hook methods
      • A database builder
    • FactoryBuilderSupport
    • Summary
  • Chapter 8: Implementing a Rules DSL
    • Groovy bindings
      • Exploiting bindings in DSLs
        • Closures as built-in methods
        • Closures as repeatable blocks
        • Using a specification parameter
        • Closures as singleton blocks
        • Using binding properties to form context
        • Storing and communicating results
        • Bindings and the GORM DataSource DSL
    • Building a Rewards DSL
      • Designing the DSL
        • BroadbandPlus
        • Reward types
        • The Reward DSL
        • Handling events: deferred execution
        • Convenience methods and shorthand
        • The Offers
        • The RewardService class
        • The BroadbandPlus application classes
        • Testing with GroovyTestCase
    • Summary
  • Chapter 9: Integrating it all
    • Mixing and matching Groovy and Java
      • Calling Groovy from Java
        • POJOs and POGOs
      • Calling Java from Groovy
      • Privacy concerns
      • Interfaces in Java and Groovy
      • Resolving dependencies
      • Dependency injection with Spring
    • GroovyClassLoader
      • Integrating scripts
      • GroovyShell
        • CompilerConfiguration
      • GroovyScriptEngine
    • Summary

Fergal Dearle

Fergal is a seasoned software development professional with 23 years of experience in software product development across a wide variety of technologies. He is currently principal consultant with his own software development consulting company, Dearle Technologies Ltd., engaged in design, development, and architecture for new software products for client companies. In the past Fergal has worked in lead architect and developer roles for Candle Corporation on the OMEGAMON product which is now part of IBMs Tivoli product suite as development manager for the Unix implementations of Lotus 1-2-3. In the early 1990s Fergal lead the team at Glockenspiel that developed CommonView, the first object-oriented UI framework for Microsoft Windows. The team was awarded one of the first ever Jolt Productivity Awards by Dr Dobbs Journal.

The book has plenty of sample code, which I found well constructed and easy to read, and I believe the book hit it's target. The strengths of using Groovy for Domain Specific Languages are drawn out, and the Groovy language is given a thorough overview. I think this book covered a lot of ground and did it well.

Code Downloads

Download the code and support files for this book.

Submit Errata

Please let us know if you have found any errors not listed on this list by completing our errata submission form. Our editors will check them and add them to this list. Thank you.


- 13 submitted: last submission 24 Sep 2013

Errata type: Technical | Page number: 88 | Errata date: 12 July 11 The code contains the comment: // Ensure twitter-4j-2.0.3.jar is in classpath But the correct jar file is: // Ensure twitter4j-2.0.3.jar is in classpath Please delete the hyphen.

On page 15, Replace "ComplexNumber& ComplexNumber::operator=(const ComplexNumber& num) { real = num.real; imag = num.imag; return *this; }" with "ComplexNumber& ComplexNumber::operator+(const ComplexNumber& num) { real += num.real; imag += num.imag; return *this; }"

  Errata type: Technical | Page number: 93 | Errata date: 29th April, 2013 The methods eachFriend() and eachFollowers() need to declare an additional   argument, twitter. This should be the first argument. This error is fixed in   the sample code. Secondly, the book lists these methods as static, but in the sample code the   methods are not static.  

Errata type: Technical | Page number: 40 | Errata date: 21st April, 2013 The first two lines of the code sample at top of page should be: customer = new Customer() customer.setName(“Brian Beausang”) Note _only_ the first letter "c" must be lower-case! The following would also work: Customer customer = new Customer() Again: note the order of capitalization: uppercase, lowercase, uppercase!

Errata type: Technical | Page number: 19 | Errata date: 21st April, 2013 Before the Closure section, the out for the output for Groovy Version 1.5.8 should be: ["fileUnder":"Software Development", "title":"Groovy for DSL", "author":"Fergal Dearle"] Groovy for DSL Groovy for DSL

Errata type: Technical | Page number: 43 | Errata date: 21st April, 2013 The second code example has problem with capitalization; either one of the following two lines will work: Customer customer = new Customer(name:“Daniel Dewdney”) customer = new Customer(name:“Daniel Dewdney”) Errata type: Technical | Page number: 93 | Errata date: 29th April, 2013

Errata type: Technical | Page number: 27 | Errata date: 21st April, 2013 To run a script from a command line, use "$groovy HelloWorld.groovy" instead of "$groovy Hello.groovy".

Errata type: Code | Page number: 27 | Errata date: 6th May, 2013 In the example on "Regular expression support", instead of matcher = string =~ " +", use matcher = lorem =~ " +".

Errata type: Typo | Page number: 69

The code at the bootom of the page:
  println i

should be:

  println it

Errata type: Code | Page number: 107

In the last paragraph:

It also provides a method CompilationConfiguration. setScripBaseClass(), which allows us to provide an alternative subclass of Script to be used for the base class of our script instance.

setScripBaseClass() should be setScriptBaseClass()

Errata type: Code | Page number: 66

In the Forward Parameters section - the closure is
closureMethodString("Dolly") { name ->
println "Hello, ${it}"

The println should be println "Hello ${name}" - because the parameter is a named parameter and not the default.

Errata type: Typo | Page number: 55

"In principal, any object that has a hashCode..."

should be

"In principle, any object that has a hashCode..."

Errata Type: Code Page No: 49

// If else syntax if (condition) { … } the else statement is missing.

It should be
// If else syntax if (condition) { … } else { }

Errata Type: Typo Page No: 52

"traditional Java for(initializer: condition: increment) style of looping"

It Should be

"traditional Java for(initializer; condition; increment) style of looping"

Errata type: Code related Pg no 236

It is: = Account.&credit

It should be: = account.&credit

Sample chapters

You can view our sample chapters and prefaces of this title on PacktLib or download sample chapters in PDF format.

Frequently bought together

Groovy for Domain-Specific Languages +    Beginning OpenVPN 2.0.9 =
50% Off
the second eBook
Price for both: $44.10

Buy both these recommended eBooks together and get 50% off the cheapest eBook.

What you will learn from this book

Learn Groovy scripting designed to get Java programmers using Groovy quickly Use the meta-programming features in Groovy to build your own DSLs Learn everything you need to know about Groovy markup and build your own Groovy builders to simplify your application development Build effective DSLs using operator overloading and Groovy categories Work with Groovy closures Get to grips with the working of Groovy on the JVM and integrate Groovy with your Java applications

In Detail

You may already be aware that the Java virtual machine runs on everything from the largest mainframe to the smallest microchip and supports almost every conceivable application. What you may not realize is that to develop software in some of these scenarios requires a targeted, single purpose language, a Domain Specific Language. The popular scripting language Groovy can be used to create a Domain Specific Language that can run directly on the JVM alongside regular Java code.This comprehensive tutorial will take you through the design and development of Groovy-based Domain Specific Languages. It is a complete guide to the development of several mini-DSLs with a lot of easy-to-understand examples. This book will help you to gain all of the skills needed to develop your own Groovy-based DSLs, as it guides you from the basics through to the more complex meta-programming features of Groovy. The focus is on how the Groovy language can be used to construct domain-specific mini-languages. Practical examples are used throughout to de-mystify the seemingly complex language features and to show how they can be used to create simple and elegant DSLs. The examples include a quick and simple Groovy DSL to interface with Twitter.The book concludes with a chapter focusing on integrating Groovy-based DSLs in such a way that the scripts can be readily incorporated into the readers' own Java applications. The overall goal of this book is to take Java developers through the skills and knowledge they need to start building effective Groovy-based DSLs to integrate into their own applications.

This practical guide will teach you how to build Domain Specific Languages in Groovy that integrate seamlessly with your Java applications


This book is a practical tutorial, walking the reader through examples of building DSLs with Groovy covering meta-programming with Groovy. Some complex concepts are covered in the book but we go through these in a clear and methodically way so that readers will gain a good working knowledge of the techniques involved.

Who this book is for

This book is for Java software developers who have an interest in building domain scripting into their Java applications. No knowledge of Groovy is required, although it will be helpful. The book does not teach Groovy, but quickly introduces the basic ideas of Groovy. An experienced Java developer should have no problems with these and move quickly on to the more involved aspects of creating DSLs with Groovy. No experience of creating a DSL is required.The book should also be useful for experienced Groovy developers who have so far only used Groovy DSLs such as Groovy builders and would like to start building their own Groovy-based DSLs.

Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software