Groovy Training

Modified: 06/13/2008

  • Installing Groovy
    • Download Groovy binary
    • extract zip
    • set up GROOVY_HOME
    • ADD GROOVY_HOME\bin to PATH
    • test with "groovy -version"
  • Looking at Sample Groovy Code
    • First, let us look at some Java code. This Java code will print a greeting to the screen

      File: HelloJava.java

      public class HelloJava
      {
      
      public void greet()
      {
      System.out.println("Hello. My source code is Java.");
      }
      
      public static void main(String[] args)
      {
      HelloJava helloJava = new HelloJava();
      helloJava.greet();
      }
      
      }
      
    • Now, let us look at several examples of Groovy code that all do pretty much the same thing, display a greeting.

      File: Hello.groovy

      println "Hello groovy citizen."
      

      File: org\example\GroovyHelloInPackage.groovy

      package org.example
      
      println "Hello earth dweller."
      

      File: HelloHasClass.groovy

      class Greeter
      {
      
      void greet()
      {
      println("Good tidings.")
      }
      
      }
      
      Greeter greeter = new Greeter()
      greeter.greet()
      

      Notice that the class name does not have to match the Groovy file name.

      File: HelloWithMain.groovy

      static main(String[] args)
      {
      println "Hello fellow traveler."
      }
      
      

      File: HelloILookLikeJava.groovy

      public class HelloILookLikeJava
      {
      
      public void greet()
      {
      System.out.println("Hello, my source code looks like Java.");
      }
      
      public static void main(String[] args)
      {
      HelloILookLikeJava helloILookLikeJava = new HelloILookLikeJava();
      helloILookLikeJava.greet();
      }
      
      }
      
  • Running Groovy
    • Running Groovy Scripts (Uncompiled Groovy Source Code)
      • use groovy command on the command line
        groovy Hello.groovy
        

        or

        groovy Hello
        
      • Or if the script is in a package:
        groovy org/example/GroovyHelloInPackage.groovy
        

        or

        groovy org/example/GroovyHelloInPackage
        
      • Examples
        groovy target/classes/basics/begin/Hello
        groovy target/classes/basics/begin/org/example/GroovyHelloInPackage
        groovy target/classes/basics/begin/HelloHasClass
        groovy target/classes/basics/begin/HelloWithMain
        groovy target/classes/basics/begin/HelloILookLikeJava
        
      • Including Java "jar" file libraries (classpath)
        • You can place jar files in %HOMEPATH%\.groovy\lib
        • Use command line option "-classpath" or "-cp" to list the jar files
        • Set the CLASSPATH environment variable
      • The Groovy Shell
        groovysh
        
      • The Groovy Console
        groovyConsole
        
    • Compiling Groovy to class files (Bytecode)
      • use "groovyc" on the command line
        groovyc GroovyHello.groovy
        
        • If the Groovy script has a package:
          groovyc org/example/GroovyHello.groovy
          
      • Compiling Groovy with Ant
        • <groovyc> ant task
        • Further Information: http://groovy.codehaus.org/The+groovyc+Ant+Task
          <taskdef name="groovyc"
                  classname="org.codehaus.groovy.ant.Groovyc"
                  classpathref="my.classpath"/>
          
          ...
          
          <groovyc srcdir="${testSourceDirectory}" destdir="${testClassesDirectory}">
                  <classpath>
                          <pathelement path="${mainClassesDirectory}"/>
                          <pathelement path="${testClassesDirectory}"/>
                          <path refid="testPath"/>
                  </classpath>
                  <javac source="1.4" target="1.4" debug="on" />
          </groovyc>
          
          ...
          
          
    • Running compiled Groovy

      To run class files compiled from Groovy code, you will need to include the groovy-all-<version>.jar on the classpath.

      With JDK 6.0:

      java -cp .;E:\_dev\tools\groovy-1.6-beta-1\embeddable\* Hello
      

      With JDK 5.0 or below:

      java -cp .;E:\_dev\tools\groovy-1.6-beta-1\embeddable\groovy-all-1.6-beta-1.jar Hello
      
      • If the Groovy script has a package:

        With JDK 6.0:

        java -cp .;E:\_dev\tools\groovy-1.6-beta-1\embeddable\* org.example.GroovyHello
        

        With JDK 5.0 or below:

        java -cp .;E:\_dev\tools\groovy-1.6-beta-1\embeddable\groovy-all-1.6-beta-1.jar org.example.GroovyHello
        
    • Using Maven 2 for Groovy
    • Notes on providing a static main() in your code.

      TODO: If you provide a ...

  • Mixing Groovy and Java
    • Calling Java from Groovy
    • Calling Groovy from Java
    • Adding Groovy using Spring
  • Things you will see a lot in this training
    • println()
    • assert()
    • obj.dump()
    • obj.properties
    • obj.class
    • obj.class.name
    • obj.getClass()
    • obj.getClass().getName()
  • Default imports
    java.io.*
    java.lang.*
    java.math.BigDecimal
    java.math.BigInteger
    java.net.*
    java.util.*
    
    groovy.lang.*
    groovy.util.*
    
  • Statements
    prtinln "this is a statement"
    
    • Semi-colons are mostly optional
    • When calling methods that take parameters, the parenthesis are optional.
      prtinln("this is a statement")
      
      prtinln "this is a statement"
      
    • Calling methods that have zero parameters, the parenthesis are not optional.
      prtinln()
      
    • When calling JavaBean getter methods (except on Maps), there is special syntax support.
      obj.getClass().getName()
      

      becomes

      obj.class.name
      
    • When calling JavaBean setter methods (except on Maps???), there is special syntax support.
      bean.setName("Sam")
      

      becomes

      bean.name = "Sam"
      
  • Keywords

    Groovy has all of Java's keywords and some extra ones.

    • in
    • def
  • Strings
  • Numbers
  • Ranges
  • Variables
  • Operators
    • Safe Navigation
  • Looping and Branching
  • Try Catch
  • Groovy Truth
  • Methods
    • Passing name value pairs
  • Objects (POGOs)
    • Special syntax for calling property getters and setters
    • named parameters in constructors and methods
  • Closures
  • Special syntax for passing a Closure as a parameter in methods
  • List, Maps and Arrays
  • List and Map Iteration
    • each
    • eachWithIndex
    • find
    • findAll
    • join
    • collect
  • The GDK
    • identity()
    • with()
    • use()
    • as()
    • getProperties()
    • dump()
  • Operator Overloading
  • Groovy and File I/O
  • ConfigSlurper
  • Groovy Regular Expression Support
  • Gant
  • Groovy and SQL
  • Groovy Markup ???
    • MarkupBuilder
    • Creating HTML
  • Processing XML
    • GPath
    • XMLSlurper
    • TODO: XMLParser
  • Groovy SwingBuilder
  • Template
  • GSP
  • Unit Testing
    • assert
    • JUnit TestCase
    • GroovyTestCase
  • Method Pointers
  • Metaprogramming
    • method interception
    • closure delegates
    • custom builders
    • custom metaclass
    • Expando
    • metaClass / getMetaClass()
    • Adding methods to a Class at runtime
    • Adding methods to an Object at runtime
    • ExpandoMetaClass
      • invokeMethod
      • methodMissing
  • A Few Design Patterns in Groovy