You are previewing Groovy in Action.
O'Reilly logo
Groovy in Action

Book Description

Groovy, the brand-new language for the Java platform, brings to Java many of the features that have made Ruby popular.

Groovy in Action

is a comprehensive guide to Groovy programming, introducing Java developers to the new dynamic features that Groovy provides. To bring you

Groovy in Action

, Manning again went to the source by working with a team of expert authors including both members and the Manager of the Groovy Project team. The result is the true definitive guide to the new Groovy language.

Groovy in Action introduces Groovy by example, presenting lots of reusable code while explaining the underlying concepts. Java developers new to Groovy find a smooth transition into the dynamic programming world. Groovy experts gain a solid reference that challenges them to explore Groovy deeply and creatively.

Because Groovy is so new, most readers will be learning it from scratch. Groovy in Action quickly moves through the Groovy basics, including:

  • Simple and collective Groovy data types

  • Working with Closures and Groovy Control Structures

  • Dynamic Object Orientation, Groovy style

Readers are presented with rich and detailed examples illustrating Groovy's enhancements to Java, including

  • How to Work with Builders and the GDK

  • Database programming with Groovy

Groovy in Action then demonstrates how to Integrate Groovy with XML, and provides,

  • Tips and Tricks

  • Unit Testing and Build Support

  • Groovy on Windows

An additional bonus is a chapter dedicated to Grails, the Groovy Web Application Framework.

Early PDF chapters of Groovy in Action are available from the Manning Early Access Program (MEAP) at http://www.manning.com/koenig. As part of this program, readers can also discuss the early manuscript with the author and help shape the manuscript as it's being developed by joining the Author Forum.

Table of Contents

  1. Copyright
    1. Dedication
  2. Foreword
  3. Preface
  4. Acknowledgments
  5. About this Book
    1. Roadmap
    2. Who should read this book?
    3. Code conventions
    4. Keeping up to date
    5. Author Online
  6. About the Authors
  7. About the Title
  8. About the Cover Illustration
  9. 1. Your way to Groovy
    1. 1.1. The Groovy story
      1. 1.1.1. What is Groovy?
      2. 1.1.2. Playing nicely with Java: seamless integration
        1. Seamless integration
        2. Syntax alignment
      3. 1.1.3. Power in your code: a feature-rich language
        1. Listing a file: closures and I/O additions
        2. Printing a list: collection literals and simplified property access
        3. XML handling the Groovy way: GPath with dynamic properties
      4. 1.1.4. Community-driven but corporate-backed
    2. 1.2. What Groovy can do for you
      1. 1.2.1. Groovy for Java professionals
      2. 1.2.2. Groovy for script programmers
      3. 1.2.3. Groovy for pragmatic programmers, extremos, and agilists
    3. 1.3. Running Groovy
      1. 1.3.1. Using groovysh for “Hello World”
        1. Display command
        2. Binding command
        3. Inspect command
      2. 1.3.2. Using groovyConsole
      3. 1.3.3. Using groovy
    4. 1.4. Compiling and running Groovy
      1. 1.4.1. Compiling Groovy with groovyc
      2. 1.4.2. Running a compiled Groovy script with Java
      3. 1.4.3. Compiling and running with Ant
    5. 1.5. Groovy IDE and editor support
      1. 1.5.1. IntelliJ IDEA plug-in
      2. 1.5.2. Eclipse plug-in
      3. 1.5.3. Groovy support in other editors
    6. 1.6. Summary
  10. 1. The Groovy language
    1. 2. Overture: The Groovy basics
      1. 2.1. General code appearance
        1. 2.1.1. Commenting Groovy code
        2. 2.1.2. Comparing Groovy and Java syntax
        3. 2.1.3. Beauty through brevity
      2. 2.2. Probing the language with assertions
      3. 2.3. Groovy at a glance
        1. 2.3.1. Declaring classes
        2. 2.3.2. Using scripts
        3. 2.3.3. GroovyBeans
        4. 2.3.4. Handling text
          1. GStrings
          2. Regular expressions
        5. 2.3.5. Numbers are objects
        6. 2.3.6. Using lists, maps, and ranges
          1. Lists
          2. Simple maps
          3. Ranges
        7. 2.3.7. Code as objects: closures
        8. 2.3.8. Groovy control structures
      4. 2.4. Groovy’s place in the Java environment
        1. 2.4.1. My class is your class
        2. 2.4.2. GDK: the Groovy library
        3. 2.4.3. The Groovy lifecycle
          1. Groovy class generation at work
          2. Groovy is dynamic
      5. 2.5. Summary
    2. 3. The simple Groovy datatypes
      1. 3.1. Objects, objects everywhere
        1. 3.1.1. Java’s type system—primitives and references
        2. 3.1.2. Groovy’s answer—everything’s an object
        3. 3.1.3. Interoperating with Java—automatic boxing and unboxing
        4. 3.1.4. No intermediate unboxing
      2. 3.2. The concept of optional typing
        1. 3.2.1. Assigning types
        2. 3.2.2. Static versus dynamic typing
      3. 3.3. Overriding operators
        1. 3.3.1. Overview of overridable operators
        2. 3.3.2. Overridden operators in action
        3. 3.3.3. Making coercion work for you
          1. Supported argument types
          2. Promoting more specific arguments
          3. Handling more general arguments with double dispatch
          4. Groovy’s conventional behavior
      4. 3.4. Working with strings
        1. 3.4.1. Varieties of string literals
        2. 3.4.2. Working with GStrings
        3. 3.4.3. From Java to Groovy
      5. 3.5. Working with regular expressions
        1. 3.5.1. Specifying patterns in string literals
          1. Symbols
        2. 3.5.2. Applying patterns
          1. Common regex pitfalls
        3. 3.5.3. Patterns in action
        4. 3.5.4. Patterns and performance
        5. 3.5.5. Patterns for classification
      6. 3.6. Working with numbers
        1. 3.6.1. Coercion with numeric operators
        2. 3.6.2. GDK methods for numbers
      7. 3.7. Summary
    3. 4. The collective Groovy datatypes
      1. 4.1. Working with ranges
        1. 4.1.1. Specifying ranges
        2. 4.1.2. Ranges are objects
        3. 4.1.3. Ranges in action
      2. 4.2. Working with lists
        1. 4.2.1. Specifying lists
        2. 4.2.2. Using list operators
          1. The subscript operator
          2. Adding and removing items
          3. Control structures
        3. 4.2.3. Using list methods
          1. Manipulating list content
          2. Accessing list content
        4. 4.2.4. Lists in action
      3. 4.3. Working with maps
        1. 4.3.1. Specifying maps
        2. 4.3.2. Using map operators
        3. 4.3.3. Maps in action
      4. 4.4. Notes on Groovy collections
        1. 4.4.1. Understanding concurrent modification
        2. 4.4.2. Distinguishing between copy and modify semantics
      5. 4.5. Summary
    4. 5. Working with closures
      1. 5.1. A gentle introduction to closures
      2. 5.2. The case for closures
        1. 5.2.1. Using iterators
        2. 5.2.2. Handling resources
          1. A common Java approach: use inner classes
          2. An alternative Java approach: the Template Method pattern
      3. 5.3. Declaring closures
        1. 5.3.1. The simple declaration
        2. 5.3.2. Using assignments for declaration
        3. 5.3.3. Referring to methods as closures
        4. 5.3.4. Comparing the available options
      4. 5.4. Using closures
        1. 5.4.1. Calling a closure
        2. 5.4.2. More closure methods
          1. Reacting on the parameter count
          2. How to curry favor with a closure
          3. Classification via the isCase method
          4. Remaining methods
      5. 5.5. Understanding scoping
        1. 5.5.1. The simple variable scope
        2. 5.5.2. The general closure scope
        3. 5.5.3. Scoping at work: the classic accumulator test
      6. 5.6. Returning from closures
      7. 5.7. Support for design patterns
        1. 5.7.1. Relationship to the Visitor pattern
        2. 5.7.2. Relationship to the Builder pattern
        3. 5.7.3. Relationship to other patterns
      8. 5.8. Summary
    5. 6. Groovy control structures
      1. 6.1. The Groovy truth
        1. 6.1.1. Evaluating Boolean tests
        2. 6.1.2. Assignments within Boolean tests
      2. 6.2. Conditional execution structures
        1. 6.2.1. The humble if statement
        2. 6.2.2. The conditional ?: operator
        3. 6.2.3. The switch statement
          1. The switch structure
          2. Switch with classifiers
        4. 6.2.4. Sanity checking with assertions
          1. Producing informative failure messages
          2. Insure code with inline unit tests
          3. Relationships to other assertions
      3. 6.3. Looping
        1. 6.3.1. Looping with while
        2. 6.3.2. Looping with for
      4. 6.4. Exiting blocks and methods
        1. 6.4.1. Normal termination: return/break/continue
        2. 6.4.2. Exceptions: throw/try-catch-finally
      5. 6.5. Summary
    6. 7. Dynamic object orientation, Groovy style
      1. 7.1. Defining classes and scripts
        1. 7.1.1. Defining fields and local variables
          1. Declaring variables
          2. Referencing and dereferencing fields
        2. 7.1.2. Methods and parameters
          1. Advanced naming
        3. 7.1.3. Safe dereferencing with the ?. operator
        4. 7.1.4. Constructors
          1. Positional parameters
          2. Named parameters
          3. Implicit constructors
      2. 7.2. Organizing classes and scripts
        1. 7.2.1. File to class relationship
        2. 7.2.2. Organizing classes in packages
          1. Classpath
          2. Packages
          3. Imports
          4. Type aliasing
        3. 7.2.3. Further classpath considerations
      3. 7.3. Advanced OO features
        1. 7.3.1. Using inheritance
        2. 7.3.2. Using interfaces
        3. 7.3.3. Multimethods
      4. 7.4. Working with GroovyBeans
        1. 7.4.1. Declaring beans
        2. 7.4.2. Working with beans
          1. Accessor methods
          2. Field access with .@
          3. Bean-style event handling
        3. 7.4.3. Using bean methods for any object
        4. 7.4.4. Fields, accessors, maps, and Expando
      5. 7.5. Using power features
        1. 7.5.1. Querying objects with GPaths
        2. 7.5.2. Injecting the spread operator
        3. 7.5.3. Mix-in categories with the use keyword
      6. 7.6. Meta programming in Groovy
        1. 7.6.1. Understanding the MetaClass concept
        2. 7.6.2. Method invocation and interception
        3. 7.6.3. Method interception in action
      7. 7.7. Summary
  11. 2. Around the Groovy library
    1. 8. Working with builders
      1. 8.1. Learning by example—using a builder
      2. 8.2. Building object trees with NodeBuilder
        1. 8.2.1. NodeBuilder in action—a closer look at builder code
        2. 8.2.2. Understanding the builder concept
        3. 8.2.3. Smart building with logic
      3. 8.3. Working with MarkupBuilder
        1. 8.3.1. Building XML
        2. 8.3.2. Building HTML
      4. 8.4. Task automation with AntBuilder
        1. 8.4.1. From Ant scripts to Groovy scripts
        2. 8.4.2. How AntBuilder works
        3. 8.4.3. Smart automation scripts with logic
      5. 8.5. Easy GUIs with SwingBuilder
        1. 8.5.1. Reading a password with SwingBuilder
        2. 8.5.2. Creating Swing widgets
        3. 8.5.3. Arranging your widgets
        4. 8.5.4. Referring to widgets
        5. 8.5.5. Using Swing actions
        6. 8.5.6. Using models
        7. 8.5.7. Putting it all together
          1. Gathering requirements
          2. Getting prepared
          3. Implementation
          4. Assessment
      6. 8.6. Creating your own builder
        1. 8.6.1. Subclassing BuilderSupport
        2. 8.6.2. The DebugBuilder example
      7. 8.7. Summary
    2. 9. Working with the GDK
      1. 9.1. Working with Objects
        1. 9.1.1. Interactive objects
          1. Object information in strings
          2. Accessing properties
          3. Invoking methods dynamically
        2. 9.1.2. Convenient Object methods
        3. 9.1.3. Iterative Object methods
      2. 9.2. Working with files and I/O
        1. 9.2.1. Traversing the filesystem
        2. 9.2.2. Reading from input sources
        3. 9.2.3. Writing to output destinations
        4. 9.2.4. Filters and conversions
        5. 9.2.5. Streaming serialized objects
      3. 9.3. Working with threads and processes
        1. 9.3.1. Groovy multithreading
        2. 9.3.2. Integrating external processes
      4. 9.4. Working with templates
        1. 9.4.1. Understanding the template format
        2. 9.4.2. Templates in action
        3. 9.4.3. Advanced template issues
      5. 9.5. Working with Groovlets
        1. 9.5.1. Starting with “hello world”
        2. 9.5.2. The Groovlet binding
        3. 9.5.3. Templating Groovlets
      6. 9.6. Summary
    3. 10. Database programming with Groovy
      1. 10.1. Basic database operations
        1. 10.1.1. Setting up for database access
          1. Installing a database
          2. First contact
          3. DriverManager versus DataSource
        2. 10.1.2. Executing SQL
          1. Creating the database schema
          2. Inserting data
          3. Updating and deleting data
        3. 10.1.3. Fetching data
          1. Fetching a row at a time with eachRow
          2. Fetching a ResultSet with query
          3. Fetching all rows at once
          4. Fetching metadata
        4. 10.1.4. Putting it all together
      2. 10.2. DataSets for SQL without SQL
        1. 10.2.1. Using DataSet operations
        2. 10.2.2. DataSets on database views
      3. 10.3. Organizing database work
        1. 10.3.1. Architectural overview
        2. 10.3.2. Specifying the application behavior
        3. 10.3.3. Implementing the infrastructure
          1. Implementing DbHelper
          2. Implementing DataAccessObject
          3. Implementing AthleteDAO
        4. 10.3.4. Using a transparent domain model
        5. 10.3.5. Implementing the application layer
      4. 10.4. Groovy and ORM
      5. 10.5. Summary
    4. 11. Integrating Groovy
      1. 11.1. Getting ready to integrate
        1. 11.1.1. Integrating appropriately
        2. 11.1.2. Setting up dependencies
      2. 11.2. Evaluating expressions and scripts with GroovyShell
        1. 11.2.1. Starting simply
        2. 11.2.2. Passing parameters within a binding
        3. 11.2.3. Generating dynamic classes at runtime
        4. 11.2.4. Parsing scripts
        5. 11.2.5. Running scripts or classes
        6. 11.2.6. Further parameterization of GroovyShell
          1. Choosing a parent classloader
          2. Configuring the compilation
      3. 11.3. Using the Groovy script engine
        1. 11.3.1. Setting up the engine
        2. 11.3.2. Running scripts
        3. 11.3.3. Defining a different resource connector
      4. 11.4. Working with the GroovyClassLoader
        1. 11.4.1. Parsing and loading Groovy classes
        2. 11.4.2. The chicken and egg dependency problem
          1. Example problem
          2. Removing the dependency cycle
          3. Building the solution in phases
        3. 11.4.3. Providing a custom resource loader
        4. 11.4.4. Playing it safe in a secured sandbox
          1. The Java security model
          2. GroovyCodeSource and the security manager
          3. GroovyShell and GroovyClassLoader with GroovyCodeSource
      5. 11.5. Spring integration
        1. 11.5.1. Wiring GroovyBeans
        2. 11.5.2. Refreshable beans
        3. 11.5.3. Inline scripts
      6. 11.6. Riding Mustang and JSR-223
        1. 11.6.1. Introducing JSR-223
        2. 11.6.2. The script engine manager and its script engines
        3. 11.6.3. Compilable and invocable script engines
      7. 11.7. Choosing an integration mechanism
      8. 11.8. Summary
    5. 12. Working with XML
      1. 12.1. Reading XML documents
        1. 12.1.1. Working with a DOM parser
          1. Getting the document
          2. Walking the DOM
          3. Making DOM groovier
        2. 12.1.2. Reading with a Groovy parser
          1. Commonalities between XmlParser and XmlSlurper
          2. Differences between XmlParser and XmlSlurper
        3. 12.1.3. Reading with a SAX parser
        4. 12.1.4. Reading with a StAX parser
      2. 12.2. Processing XML
        1. 12.2.1. In-place processing
        2. 12.2.2. Streaming processing
          1. Unmodified piping
          2. Heating up to HTML
        3. 12.2.3. Combining with XPath
          1. Understanding XPath
          2. Using the XPath API
          3. Leveraging additional Java XML processing technologies
      3. 12.3. Distributed processing with XML
        1. 12.3.1. An overview of web services
        2. 12.3.2. Reading RSS and ATOM
        3. 12.3.3. Using a REST-based API
        4. 12.3.4. Using XML-RPC
        5. 12.3.5. Applying SOAP
          1. Doing SOAP with plain Groovy
          2. Simplifying SOAP access with the GroovySOAP module
          3. Publishing a SOAP service with GroovySOAP
      4. 12.4. Summary
  12. 3. Everyday Groovy
    1. 13. Tips and tricks
      1. 13.1. Things to remember
        1. 13.1.1. Equality versus identity
        2. 13.1.2. Using parentheses wisely
        3. 13.1.3. Returning from methods and closures
        4. 13.1.4. Calling methods in builder code
        5. 13.1.5. Qualifying access to “this”
          1. Disambiguation in Java
          2. Disambiguation in Groovy
        6. 13.1.6. Considering number types
        7. 13.1.7. Leveraging Ant
          1. Using Ant from Groovy
          2. Using Groovy from Ant
        8. 13.1.8. Scripts are classes but different
          1. Script naming
          2. Script inclusion
      2. 13.2. Useful snippets
        1. 13.2.1. Shuffling a collection
        2. 13.2.2. Scrambling text with regular expressions
        3. 13.2.3. Console progress bar
        4. 13.2.4. Self-commenting single-steps
        5. 13.2.5. Advanced GString usage
      3. 13.3. Using groovy on the command line
        1. 13.3.1. Evaluating a command-line script
        2. 13.3.2. Using print and line options
        3. 13.3.3. Using the listen mode
        4. 13.3.4. In-place editing from the command line
      4. 13.4. Writing automation scripts
        1. 13.4.1. Supporting command-line options consistently
          1. The standard option handling
          2. Declaring command-line options
          3. Working with options
          4. The Mailman example
        2. 13.4.2. Expanding the classpath with RootLoader
          1. Starting Java is considered tricky
          2. Groovy starters
        3. 13.4.3. Scheduling scripts for execution
      5. 13.5. Example automation tasks
        1. 13.5.1. Scraping HTML pages
        2. 13.5.2. Automating web actions
        3. 13.5.3. Inspecting version control
        4. 13.5.4. Pragmatic code analysis
        5. 13.5.5. More points of interest
      6. 13.6. Laying out the workspace
        1. 13.6.1. IDE setup
        2. 13.6.2. Debugging
          1. Exploiting groovyc
          2. Groovy runtime inspection
          3. Using debugging tools
          4. Jdb session transcript
        3. 13.6.3. Profiling
        4. 13.6.4. Refactoring
      7. 13.7. Summary
    2. 14. Unit testing with Groovy
      1. 14.1. Getting started
        1. 14.1.1. Writing tests is easy
        2. 14.1.2. GroovyTestCase: an introduction
        3. 14.1.3. Working with GroovyTestCase
      2. 14.2. Unit-testing Groovy code
      3. 14.3. Unit-testing Java code
      4. 14.4. Organizing your tests
      5. 14.5. Advanced testing techniques
        1. 14.5.1. Testing made groovy
        2. 14.5.2. Stubbing and mocking
          1. Example problem: collaborator construction
          2. Stubbing out the collaborator
          3. Stub expectations
          4. Comparing stubs and mocks
        3. 14.5.3. Using GroovyLogTestCase
      6. 14.6. IDE integration
        1. 14.6.1. Using GroovyTestSuite
        2. 14.6.2. Using AllTestSuite
        3. 14.6.3. Advanced IDE integration
      7. 14.7. Tools for Groovy testing
        1. 14.7.1. Code coverage with Groovy
        2. 14.7.2. JUnit extensions
      8. 14.8. Build automation
        1. 14.8.1. Build integration with Ant
        2. 14.8.2. Build integration with Maven
      9. 14.9. Summary
    3. 15. Groovy on Windows
      1. 15.1. Downloading and installing Scriptom
      2. 15.2. Inside Scriptom
        1. 15.2.1. Introducing Jacob
        2. 15.2.2. Instantiating an ActiveX component
        3. 15.2.3. Invoking methods
        4. 15.2.4. Accessing properties and return values
        5. 15.2.5. Event support
      3. 15.3. Real-world scenario: automating localization
        1. 15.3.1. Designing our document format
        2. 15.3.2. Designing the thesaurus spreadsheet
        3. 15.3.3. Creating a Word document
        4. 15.3.4. Producing the final document
      4. 15.4. Further application automation
        1. 15.4.1. Accessing the Windows registry
          1. 15.4.2. Rolling out your own automation system
      5. 15.5. Where to get documentation
      6. 15.6. Summary
    4. 16. Seeing the Grails light
      1. 16.1. Setting the stage
        1. 16.1.1. Installing Grails
        2. 16.1.2. Getting your feet wet
      2. 16.2. Laying out the domain model
        1. 16.2.1. Thinking through the use cases
        2. 16.2.2. Designing relations
      3. 16.3. Implementing the domain model
        1. 16.3.1. Scaffolding domain classes
        2. 16.3.2. Scaffolding views and controllers
        3. 16.3.3. Testing the web application
        4. 16.3.4. Completing the domain model
      4. 16.4. Customizing the views
        1. 16.4.1. Bootstrapping data
        2. 16.4.2. Working with Groovy Server Pages
        3. 16.4.3. Working with tag libraries
      5. 16.5. Working with controllers and finder methods
      6. 16.6. Elaborating the model
      7. 16.7. Working with the session
      8. 16.8. Finishing up
        1. 16.8.1. Validating constraints
        2. 16.8.2. Deploying the application
        3. 16.8.3. Farewell
  13. A. Installation and documentation
    1. A.1. Installation
    2. A.2. Obtaining up-to-date documentation
      1. A.2.1. Using online resources
      2. A.2.2. Subscribing to mailing lists
      3. A.2.3. Connecting to forum and chat
  14. B. Groovy language info
    1. B.1. Keyword list
  15. C. GDK API quick reference
    1. C.1. Arrays and primitives
    2. C.2. The java.lang package
    3. C.3. The java.math package
    4. C.4. The java.util and java.sql packages
    5. C.5. The java.util.regex packag
    6. C.6. The java.io package
    7. C.7. The java.net package
  16. D. Cheat sheets
    1. D.1. Lists
    2. D.2. Closures
    3. D.3. Regular expressions
    4. D.4. Unit testing
    5. D.5. Mocks and stubs
    6. D.6. XML GPath notation