A groovy way to use the Java Virtual Machine
Overview
This is a hands-on introduction to the Groovy programming langauge. Effort was taken to sequence topics for faster learning.
Groovy development began in 2003 by James Strachan and Bob McWhirter. Groovy 1.0 was released in January 2, 2007.
The advantage of Groovy:
- Can run on a variety of operating systems (Linux, Windows, etc.)
- Create code faster than Java?
- Can use Java library classes, such as Grails for web apps
- Still use JVM (Groovy compiles to Java)
Social
http://groovy-lang.org is the Groovy language homepage, which is built from https://github.com/groovy/groovy-website
It’s called “Apache Groovy” because it’s an Apache open-source project. Apache runs conferences on the language. Some notable presentations:
- https://www.youtube.com/channel/UC-Vs_q9uWBlSx5NsDkxoGAQ gr8conf.eu by venkat@agiledeveloper.com @venkat_s Subramaniam
Docker Image
Docker images contain a complete environment:
https://github.com/groovy/docker-groovy
Install
Package Manager
Formerly known as GVM the Groovy enVironment Manager, SDKMan.io (inspired by RVM and rbenv tools widely used by the Ruby community) is a tool for Mac OSX, Linux or Cygwin (Unix-based system) users to manage parallel versions of multiple Software Development Kits. It provides a convenient Command Line Interface (CLI) and API for installing, switching, removing and listing Candidates.
-
Install sdkman by running the following command in your Unix terminal:
curl -s "https://get.sdkman.io" | bash
-
As instructed in the response:
source ~/.sdkman/bin/sdkman-init.sh
-
Use SDK to install the latest version of Grails (this guide uses 3.2.4):
sdk install grails 3.2.4
https://tutorials.techmytalk.com/2014/07/19/grails-understanding/
-
Choose ‘yes’ when sdkman prompts you to choose whether to set this version as the default.
-
Verify:
sdk help
The response reaches out through the internet for version news:
==== BROADCAST ================================================================= * 28/06/17: Kotlin 1.1.3 released on SDKMAN! #kotlin * 26/06/17: Grails 3.2.11 released on SDKMAN! #grailsfw * 26/06/17: Grails 3.3.0.RC1 released on SDKMAN! #grailsfw ================================================================================ Usage: sdk <command> [candidate] [version] sdk offline <enable|disable> commands: install or i <candidate> [version] uninstall or rm <candidate>
list or ls [candidate] use or u <candidate> [version] default or d <candidate> [version] current or c [candidate] upgrade or ug [candidate] version or v broadcast or b help or h offline [enable|disable] selfupdate [force] flush <candidates|broadcast|archives|temp> candidate : the SDK to install: groovy, scala, grails, gradle, kotlin, etc. use list command for comprehensive list of candidates eg: $ sdk list version : where optional, defaults to latest stable if not provided eg: $ sdk install groovy </pre> -
List versions of sdk installed:
sdk version
-
List versions of groovy availble for install:
sdk list groovy
At the : symbol, press q to quit out or spacebar.
-
See Java:
sdk current java
-
Install Java
sdk install java
-
Install Groovy
sdk install groovy
-
List all that has been installed:
sdk current
For more, see http://sdkman.io/usage.html
Install On Mac using HomeBrew
-
Homebrew install on Mac:
brew install groovy
A sample response on June 2017:
==> Using the sandbox ==> Downloading https://dl.bintray.com/groovy/maven/apache-groovy-binary-2.4.11.zip ######################################################################## 100.0% ==> Caveats You should set GROOVY_HOME: export GROOVY_HOME=/usr/local/opt/groovy/libexec ==> Summary 🍺 /usr/local/Cellar/groovy/2.4.11: 64 files, 27.6MB, built in 10 seconds
Windows
https://github.com/groovy/groovy-windows-installer
See http://www.groovy-lang.org/install.html
Verify Install
groovy
A sample response on June 2017:
error: neither -e or filename provided usage: groovy [options] [args] options: -a,--autosplit
split lines using splitPattern (default '\s') using implicit 'split' variable -b,--basescript Base class name for scripts (must derive from Script) -c,--encoding specify the encoding of the files -classpath Specify where to find the class files - must be first argument --configscript A script for tweaking the configuration options -cp,--classpath Aliases for '-classpath' -D,--define <name=value> define a system property -d,--debug debug mode will print out full stack traces --disableopt disables one or all optimization elements. optlist can be a comma separated list with the elements: all (disables all optimizations), int (disable any int based optimizations) -e -
Eclipse IDE and Maven setup
https://github.com/groovy/groovy-eclipse
Sample code
- Install a Git client.
-
Navigate to a working folder and:
git clone https://github.com/wilsonmar/groovy-samples cd groovy-samples
This section has you going through the several ways to run Groovy programs.
Verify compile
Skip to next topic while I’m working through an error with this section.
-
Compile to a Java class file containing Java byte code:
groovyc hello.groovy
-
List files to see “hello1.class” (and not hello.class) created because the class file name is defined within the code. This Java bytecode can be deployed to Java application servers (Jetty, Tomcat, JBoss, GlassFish, etc.).
PROTIP: A class file is created for each closure definition.
-
Execute the class (bytecode) file like any other Java ones:
On a Mac, notice the use of a colon:
java Hello1 -cp ~/gits/wilsonmar/groovy-samples/:.
On Windows, notice the use of semi-colon:
java Hello1 -cp C:\gits\wilsonmar\groovy-samples\;.
PROTIP: Capitalization counts in Java file names.
BLAH: This does not work now. I am getting error message “Error: Could not find or load main class hello1”
See http://javarevisited.blogspot.com/2015/04/error-could-not-find-or-load-main-class-helloworld-java.html
Groovy Console
-
In a Terminal:
groovyConsole
-
Select File Open, etc.
-
Press command + Q to Quit out of the program.
Groovy shell
NOTE: Groovy is a dynamic language wrapper to Java.
-
Open a new Groovy shell:
groovysh
- Click on the Terminal window again.
-
Print a line or other
println "hello"
-
List commands
:help
Notice there are two formats for the same command. For example, either
:exit
or the shorter:x
to exit. -
Exit the shell using a command starting with colon:
:x
-
Invoke the shell again:
Groovy coding doesn’t yet have an import keyword that will do a literal include of another file’s contents.
http://docs.groovy-lang.org/latest/html/documentation/#GroovyShell-load Load one or more files (or urls) into the buffer.
groovy:000> :load hello.groovy
PROTIP: The shell does not import groovy.transform.BaseScript
import groovy.transform.AnnotationCollector
Sample script
Let’s begin by looking at a simple script to see basic constructs of a Groovy program:
PROTIP: Underlines and # are OK in file names. No dashes or + in file names.
-
Open a script in the Groovy Playground:
https://groovy-playground.appspot.com/… which It is stored Git
BLAH: Nothing happens when I click Execute!
QUESTION: Does this happen for you?
Basic Groovy Coding
-
In a text editor, open file hello.groovy:
// hello.groovy class Hello1 { static void main(String[] args) { /* This program shows how to display hello world to console. */ System.out.println("Hello World") print "Hello " println('World') return System.exit(0) // CAUTION: This shuts down Jenkins println "Lines after return or System.exit(0) are never executed." } }
The print function does not add a new line.
The println function adds a new line.Groovy is based on Java. But in Groovy semicolons are required only to separate multiple functions on the same line.
PROTIP: System.exit(0)
Asserts
JUnit in Groovy is GUnit.
- https://tutorials.techmytalk.com/2014/07/19/grails-unittesting/
- http://groovy.codehaus.org/Testing+Guide
- http://www.ibm.com/developerworks/java/library/j-pg11094/
Functions
Using the def keyword in larger programs is important as it helps define the scope in which the variable can be found and can help preserve encapsulation.
Profiling
GProf was created in 2013 to determine which parts of a program are taking most of the execution time (like GNU gprof does for C, C++).
Closures
A closure in Groovy is an anonymous function. Execution of the definition is delayed until invoked.
// x and y are defined within the closure definition: def closureWithParameters = {x, y -> print(x +" and "+y)} // Not executed immediately. closureWithParameters.call("Hello ladies", "Hello gentlemen") // Prints
A closure in Groovy is an open, anonymous, block of code that can take arguments, return a value and be assigned to a variable.
“Higher-order functions” is a concept from mathematics where a function accepts other functions as its arguments, and can return functions as results.
In opposition to the formal definition of a closure, Closure in the Groovy language can also contain free variables which are defined outside of its surrounding scope.
- https://www.timroes.de/2015/06/28/groovy-tutorial-for-java-developers-part2-closures/
- https://www.youtube.com/watch?v=URkFOLywex4
- http://groovy-lang.org/closures.html
- https://dzone.com/articles/closures-groovy
- https://dzone.com/articles/higher-order-functions-groovy-
Functional Programming
- https://dzone.com/articles/functional-programming-groovy
Default Library Dependencies
NOTE: By default, Groovy includes these libraries, so you don’t need to explicitly import them:
import java.lang.* import java.util.* import java.io.* import java.net.* import groovy.lang.* import groovy.util.* import java.math.BigInteger import java.math.BigDecimal
Java Library Dependencies
Additional imports, just as with Java:
Grape for Dependency management for Groovy. Grape is built on Ivy, which is compatible with Maven, which automatically installs dependencies at runtime.
http://docs.groovy-lang.org/latest/html/documentation/grape.html
-
Using a Terminal at my groovy-samples folder, open file ImportGpsData.groovy
@GrabConfig(systemClassLoader=true) @Grapes([ @Grab( group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.6' ), @Grab('mysql:mysql-connector-java:5.1.6'), @Grab(group='joda-time', module='joda-time', version='2.3') ]) import groovyx.net.http.RESTClient import groovy.sql.Sql import org.joda.time.DateTime
-
Joda-time alternative to standard Java data and time libraries. It’s at mvnrepository.com/artifact/joda-time/joda-time/2.3
-
SQL to store and retrieve data from a database See https://gist.github.com/jpertino/801238
-
Google Guava
-
Apache Commons for logging
Functions in the library are used by statements such as:
def printableTime = new DateTime(it.time.toString()) def format = DateTimeFormat.forPattern('MM/dd/yyyy - hh:mm aa') println printableTime.toString(format)
-
- Run the program using it. Grape takes care of downloading it.
-
See what dependencies are available now:
grape list
-
To manually install:
grape install xmlwriter xmlwriter 2.2.2
-
To manually see all sub-dependencies:
grape resolve
FIXME: Errors
API
Templating
TODO:
Hello world this is ${something}
Use with Gradle
(based on Maven syntax)
Other source code:
- https://groovy.codehaus.org
- https://examples.javacodegeeks.com/jvm-languages/groovy/groovy-script-tutorial-beginners/ with objects and database access.
Data types are enforced at run-time, not compile time.
Libraries
Grails builds web servers written in Groovy.
Griffon builds desktop apps in Groovy.
Usage
Jenkins supports processing of Groovy scripts in post-build actions and as an action of the build.
Groovy’s flexible syntax enables it to develop DSLs (Domain-Specific Languages)
CA APM Command Center API Scripts manage log level of APM Agents.
IBM’s Urban Code/uDeploy works with a Groovy language via a plug-in to process XML files Docs
Metaprogramming
-
https://www.youtube.com/watch?v=UJhlp5P7Ec0
-
https://www.youtube.com/watch?v=vwysol6tipM Metaprogramming techniques
-
https://www.youtube.com/watch?v=vwysol6tipM&t=49s
Back ends
- Grails with Groovy
- Ratpack
-
Spring Boot
- gServ (Groovy specific library)
- Restlet Framework
Rock Stars
Guillaume Laforge (@glaforge), now Developer Advocate at Google. But when he was at Restlet presented this on 11 Dec 2015. has a swapi.io (Star Wars API) of planets, etc..
“A Groovy Journey in Open Source Land, presentation 29 August 2016
Video Tutorials
Jeremy Jarrell provides, back in 2014, a [3:37] Groovy Fundamentals video course on Pluralsight shows how to develop a Groovy application to parse GPS data from an XML file, insert it into a database, and correlate weather forecast data from forecast.io retrieved using a REST API.
Those with a Lynda subscription can view the Program with Groovy segment within the IntelliJ course.
What is Groovy? 2013
Other introductory tutorials:
- https://www.tutorialspoint.com/groovy/
- https://examples.javacodegeeks.com/jvm-languages/groovy/groovy-script-tutorial-beginners/
-
https://www.timroes.de/2015/06/27/groovy-tutorial-for-java-developers/
-
https://www.timroes.de/2015/06/28/groovy-tutorial-for-java-developers-part3-collections/
-
https://www.youtube.com/watch?v=KDCu1vEwPWo Groovy scripting for SOAPUI from SmartBear
- https://learnxinyminutes.com/docs/groovy/ Learn Groove in X Minutes
- http://groovy-lang.org/structure.html
- http://grails.asia/grails-tutorial-for-beginners-playing-with-groovy-language
- http://guides.grails.org/creating-your-first-grails-app/guide/index.html
- http://www.vogella.com/tutorials/Grails/article.html
Resources
-
http://thingsyoudidntknowaboutjenkins.tumblr.com/post/26585787635/built-in-groovy-scr ipting
-
https://www.youtube.com/watch?v=xzc-LoJ0mt0 Advanced Groovy Tips and Tricks</a> from SpringDeveloper