m Groovy
Key Points
- Groovy is a dynamic language running on the JVM that fully integrates with Java
- Groovy is an ideal language for advanced data management that relies on dynamic metadata and metamodels
- Leverage Grade for builds and JCenter, Github, Mavencentral for libraries
References
Groovy Overviews
Udemy Complete Groovy Developer Course - updated for 4x - 2022
https://www.udemy.com/course/apache-groovy/
Groovy Tutorial For Beginners
https://www.youtube.com/watch?v=vDtENU-3Lwo
We will cover these Topics throughout the course
Programming Fundamentals Environment Setup Groovy Programming Basic Syntax Groovy Data Types Groovy Variables Groovy Operators Loops in Groovy Decision Making in Groovy Methods In Groovy File I/O in Groovy Optionals Data Structures Date & Time Exception Handling Object Oriented Programming Generics Closures Groovy Database
Groovy Script Tutorial for Beginners
What is a Groovy Script?
Why Groovy?
Groovy History
Features of Groovy
How to install Groovy
Groovy Hello World Example
Groovy Variables
Groovy-Operators
Groovy-Loops
Groovy- Decision Making
Groovy List
Groovy Maps
Groovy- Closures
Groovy Builders and Slurpers - Json etc
GORM for data access
Groovy Vs. Java
Myths about Groovy
Cons of using Groovy
Groovy Tools
Groovy Setup
SDKMAN ??
BREW ??
BINARY install and configuration
These instructions describe how to install a binary distribution of Groovy.
First, Download a binary distribution of Groovy and unpack it into some file on your local file system.
Set your
GROOVY_HOME
environment variable to the directory you unpacked the distribution.Add
GROOVY_HOME/bin
to yourPATH
environment variable.Set your
JAVA_HOME
environment variable to point to your JDK. On OS X this is/Library/Java/Home
, on other unixes its often/usr/java
etc. If you’ve already installed tools like Ant or Maven you’ve probably already done this step.
You should now have Groovy installed properly. You can test this by typing the following in a command shell:
groovy –version
groovysh
Which should create an interactive groovy shell where you can type Groovy statements. Or to run the Swing interactive console type:
groovyConsole
To run a specific Groovy script type:
groovy SomeScript
setGroovy3.sh
cat setGroovy3.sh
#!/bin/bash
#
echo "----------- "
echo " setGroovy3.sh - adds Groov 3y home to path"
echo " "
#
# $GROOVY_HOME set
export MYSQL_JDBC=/Users/jimmason/_dev/lib/mysql-connector-java-5.1.34.jar
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk/Contents/Home
export GROOVY_HOME=/Users/jimmason/_dev/groovy3/;
export PATH=$PATH:$GROOVY_HOME:$GROOVY_HOME/bin
export CLASSPATH=$MYSQL_JDBC:$CLASSPATH
echo $PATH
Key Concepts
Summary of Key Groovy Concepts
https://en.wikipedia.org/wiki/Apache_Groovy#History
- Groovy uses and extends a Java JDK
- Groovyc compiles Groovy source to executable classes with an option to capture the generated java source
- Groovysh compiles Groovy source to execute from a command line
- GroovyConsole provides a simple developer UI to build, test Groovy code and libraries
- code can be dynamic or compiled and executes on a JVM
- variables and properties can be static or dynamically typed
- provides multiple programming models: functional, object, object-oriented
- Groovy Beans have more capability than Java beans and MBeans
- Java MBeans are management extended Beans ( see basic tutorial on MBeans )
- Groovy extends the JDK with additional features and functions
- can model event streams quickly using Gbeans as event sources, listeners, handlers for workflow modeling
- Expando MetaClass allows dynamic class definitions at runtime ( a prototype model like JS and other languages )
- Supports both immediate bindings of client to object ( like Java ) or deferred binding
- Excellent JSON and XML support to build, use those documents easily
- String interpolation using Gstrings generates strings using embedded variable expressions
- Dynamic compilation of code or strings to generate immediate executables at runtime ( provides "smart" system code generation dynamically )
- Custom compilation of metaprogramming capabilities safely using AST transformations
- AST Transformations provides Groovy with improved compile-time metaprogramming capabilities allowing powerful flexibility at the language level, without a runtime performance penalty
- Traits are a structural construct of the language that allows: composition of behaviors, runtime implementation of interfaces, behavior overriding, and compatibility with static type checking/compilation.
- Spock testing language is a BDD DSL that goes beyond Selenium, Cucumber, Gherkin
- Grooscript converts Groovy code to JavaScript code.[48] Although Grooscript has some limitations compared to Apache Groovy, it can use domain classes in both the server and the client.[49] Plugin support for Grails version 3.0 is provided, as well as online code conversions.[50]
Some key Groovy modeling scenarios
- from simple object models generate GORM classes and DDL in any database ( faster than building in data modeling tools or Erwin, System Architect, etc )
- generate prototype Web services and CRUD Web apps on the object models automatically to demo concepts to customers
- generate code dynamically at runtime based on event discovery for automated data conversion tooling
- use built-in event support and Expando metaclasses to generate dynamic event-driven workflows for clients
Grails - the fastest way to prototype services and Web UIs from executable object models in Groovy
- .. and then there's Grails ( better than Ruby on Rails )
- generates data access automatically to any database using Hibernate++
- generates service classes from object model classes
- generates CRUD Web UIs from object and service classes that support customized generation using templates
- I extended Grails to generate custom Web apps adding search to CRUD for ALL generations .. now SCRUD
Groovy Data Science libraries
Groovy - why I like it - Paul King
https://www.slideshare.net/paulk_asert/awesome-groovy
Object Computing - Groovy Data Science billable course
https://objectcomputing.com/services/training/catalog/grails/data-science-with-groovy
Using Groovy for Data Science - youtbue free
https://www.youtube.com/watch?v=rixvYN-DCPk
Groovy Data Science - Paul King - speakerdeck
https://speakerdeck.com/paulk/groovy-data-science
Groovy Tools - Paul King
https://www.slideshare.net/paulk_asert/industrial-strength-groovy-paul-king-may2009-1461116
Groovy data science concepts for beginners - Advent
https://www.javaadvent.com/2022/12/groovy-and-data-science.html
Groovy Expando - dynamic instance attributes, methods
Groovy Expando Classes packaged - gtwf1-test.groovy
Groovy Beans - Object Properties and Listeners model dynamic event use cases
use object properties and listeners to simulate dynamic events in models
Groovy Beans PropertyChange Listeners - Event-driven software **
example
Groovy Expando example with PropertyChange listeners - Jim
//ex-expando-events-gen-v1.groovy
ex-expando-events-gen-v1.groovy
x111c groovy bound property example - https://blog.mrhaki.com/2009/08/groovy-goodness-bound-and-constrained.html
shows the flexibility of event messaging in requirements modeling
Event >> Owner Jim detected car Lexus automatic transmission type changed to: true from: false
the car is [Car details => brand: 'Lexus', model: 'Verso', #doors: '5', automatic: 'true', price: '30995.0']
Event >> Owner Jim detected car Lexus price changed to: 44000.0 from: 30995.0
the car is [Car details => brand: 'Lexus', model: 'Verso', #doors: '5', automatic: 'true', price: '44000.0']
ex-expando-events-gen-v1.groovy file
Traits vs Interfaces
https://www.baeldung.com/groovy-traits
Traits are reusable components representing a set of methods or behaviors that we can use to extend the functionality of multiple classes.
For this reason, they're considered as interfaces, carrying both default implementations and state. All traits are defined using the trait keyword.
Groovy 3 Key Features
http://groovy-lang.org/releasenotes/groovy-3.0.html
supports JDK 11, JDK 9 and JDK 8 at runtime
onlyJDK 11, JDK 9 supported at build time
Java-style Lambda syntax
The Java syntax for lambda expressions is now supported.
Examples:
(1..10).forEach(e -> { println e })
assert (1..10).stream()
.filter(e -> e % 2 == 0)
.map(e -> e * 2)
.toList() == [4, 8, 12, 16, 20]
The normal variants are supported and Groovy adds additional features such as default parameter values:
// general form
def add = (int x, int y) -> { def z = y; return x + z }
assert add(3, 4) == 7
// curly braces are optional for a single expression
def sub = (int x, int y) -> x - y
assert sub(4, 3) == 1
// parameter types are optional
def mult = (x, y) -> x * y
assert mult(3, 4) == 12
// no parentheses required for a single parameter with no type
def isEven = n -> n % 2 == 0
assert isEven(6)
assert !isEven(7)
// no arguments case
def theAnswer = () -> 42
assert theAnswer() == 42
// any statement requires braces
def checkMath = () -> { assert 1 + 1 == 2 }
checkMath()
// example showing default parameter values (no Java equivalent)
def addWithDefault = (int x, int y = 100) -> x + y
assert addWithDefault(1, 200) == 201
assert addWithDefault(1) == 101
Groovy 4 Features
Groovy 4 Overview Slides - Paul King
https://speakerdeck.com/paulk/groovy-roadmap
Query on Groovy Records, DBs later
https://speakerdeck.com/paulk/groovy-roadmap?slide=27
Now FMR ( Filter Map Reduce is done using SELECT )
GINQ - Groovy Integrated Query
GINQ console example
Groovy Switch can use ranges etc
Built in Type Checkers
Groovy Macro Methods
https://github.com/bsideup/groovy-macro-methods-proposal
AST Transformations
AST Transformation List
Records with meta-annotations
Design by Contract concept
Groovy Builders and Slurpers
Groovy JsonBuilder example
https://stackoverflow.com/questions/51068636/groovy-map-to-json-list-of-objects
to serialize map to json object (string)
you can use
http://docs.groovy-lang.org/latest/html/gapi/groovy/json/JsonBuilder.html
import groovy.json.JsonBuilder
new JsonBuilder([test: 'test', test2: 'test2']).toPrettyString()
or
http://docs.groovy-lang.org/latest/html/gapi/groovy/json/JsonOutput.html
import groovy.json.JsonOutput
JsonOutput.prettyPrint(JsonOutput.toJson([test: 'test', test2: 'test2']))
Spock Test Framework
http://spockframework.org/spock/docs/1.3/all_in_one.html
Spock Web Console
Spock Web Console is a website that allows you to instantly view, edit, run, and even publish Spock specifications. It is the perfect place to toy around with Spock without making any commitments. So why not run Hello, Spock! right away?
Spock Sample Project
To try Spock in your local environment, clone or download/unzip the Spock Example Project. It comes with fully working Ant, Gradle, and Maven builds that require no further setup. The Gradle build even bootstraps Gradle itself and gets you up and running in Eclipse or IDEA with a single command. See the README for detailed instructions.
Spock Overview
Spock lets you write specifications that describe expected features (properties, aspects) exhibited by a system of interest. The system of interest could be anything between a single class and a whole application, and is also called the system under specification or SUS. The description of a feature starts from a specific snapshot of the SUS and its collaborators; this snapshot is called the feature’s fixture.
Create Java source from compiled Groovy bytecode
JDs - java decompiler can convert groovy bytecode to Java source
Potential Value Opportunities
Potential Challenges
Groovyc - compile groovy to generate class files
groovyc -h // see all help
run groovyc in app folder with groovy files, dump classes to a classes subfolder
cd /Volumes/GoogleDrive/'My Drive'/_work/learn/blearn-pc/groovy
groovyc -d classes < main groovy class or list of classes >
Bug> Groovyconsole can't open groovy file from menu or cli
bug> can't open a file from groovyconsole using the file menu
workaround> use CTL + O
- open groovyconsole normally
- use CTL + O to open file selector window
- select a groovy file
- press Enter
- << file opens normally in groovy console
Candidate Solutions
Transform input string by line to output print stream
Step-by-step guide for Example
sample code block
Groovy Work File examples
file_link________________________________________________________ | Desc_________________________________________________________________ |
---|---|
https://drive.google.com/drive/folders/1_y9qhu-4UgnAiATkp1ed J1EK6lh5NjyK?usp=sharing | gD/_work/jim_acer groovy files in sub folders |
https://drive.google.com/drive/folders/1AbPwYaJ2t6-Qmd vtKX8XkB_vQ8w0Pcf5?usp=sharing | gD/_work/jim_acer/work basic groovy examples |
https://drive.google.com/drive/folders/1ZrYWnd15y0X8rbziM 47WtvUCDziuY2rT?usp=sharing | gD/_work/learn/blearn-pc contains large groovy sample files |
gtest6.groovy | |
gtwf1-test.groovy | simple expando tests |
gtxt-cnv1.groovy | simple text conversion using split separator strings |