m Groovy

Key Points

  1. Groovy is a dynamic language running on the JVM that fully integrates with Java
  2. Groovy is an ideal language for advanced data management that relies on dynamic metadata and metamodels
  3. Leverage Grade for builds and JCenter, Github, Mavencentral for libraries


References

Reference_description_with_linked_URLs____________________________Notes_______________________________________________________________


java basics swtc
Apache Groogy Documentation and Getting Started Info. ****
Groovy Learning Resources
Older Groovy Tutorial Good for Beginners - tutorialpoint - Groovy 2.4x
groovy folder test scripts gdrvGroovy tests scripts ***

https://objectcomputing.com/files/6415/6694/2515/slide_deck_
Groovy_3_and_Beyond_webinar.pdf

https://drive.google.com/open?id=1-BgJaeRWcU1Dl5Aa_-LUqNFDWkOUstYN

Groovy 3 and beyond slides
http://www.groovy-lang.org/closures.html#_groovy_closures_vs_
lambda_expressions
Groovy closures vs Lambda expressions

file:///C:/Users/Jim%20Mason/Google%20Drive/_docs/howto/groovy/regex%20-%20Regular%20Expressions%20-%20A%20Gentle%20
User%20Guide%20and%20Tutorial.pdf

Regex rules



Groovy and Data Science article - Paul King url

groovy-data-science-2022-javaadvent.com-Groovy and Data Science.pdf link


Perfect Data Science article for Grooy by Paul King ***

Slide_Deck_Groovy_for_Data_Science_Webinar.pdf

Groovy Data Science Tools - Paul King

Difference between Groovy Traits and InterfacesGroovy Traits vs Interfaces article
Groovy Annotation Concepts - TutorialsPoint
Groovy Beans PropertyChange Listeners - Event-driven software **use object properties and listeners to simulate dynamic events in models
groovy java differences geeksforgeeksgood basic summary

jim-mason-session-groovy-universal-scripting.pdf small

jim-mason-groovy-universal-scripting-handout.pdf large

jim-mason-session-groovy-universal-scripting.pdf focus on IBM i
code maven simple groovy examples


javadocs JDK 11  ***
Groovy 4x JDK extensions ***
Groovy docs ***


Groovy 3x changes
http://groovy-lang.org/releasenotes/groovy-3.0.htmlGroovy 3x supports Lambda expressions too
https://docs.groovy-lang.org/docs/groovy-3.0.0-rc-1/html/documentation/Groovy 3x documentation
Groovy 4x changes
https://groovy-lang.org/releasenotes/groovy-4.0.htmlGroovy 4 Release Notes
https://speakerdeck.com/paulk/groovy-roadmap?slide=1Groovy Roadmap 2021


GORM


http://daviddawson.me/blog/2017/09/06/groovy-gorm-shell-script.htmlGorm shell scripting - David Dawson




DSL

https://www.slideshare.net/glaforge/going-to-mars-with-groovy-domainspecific-languages

DSL-groovydsls-Going-to-Mars-with-groovy-DSL-guillaumelaforge-16-9-120426080807-phpapp01.pdf file

Groovy DSL - Going to Mars - Guillaume LaForge - 2009 ***
https://www.slideshare.net/paulk_asert/groovy-dsls-from-beginner-to-expertGroovy DSLs - Paul King, Guillaume LaForge - detailed
https://www.slideshare.net/glaforge/practical-groovy-dslGroovy DSLs in Practice - Guillaume LaForge - good
https://www.slideshare.net/NexThoughts/groovy-dsl-62615687DSL in Groovy - short
https://www.slideshare.net/paulbowler/dsls-with-groovyDSLs with Groovy - Paul Bowler
https://blog.mrhaki.com/2009/08/groovy-goodness-bound-and-constrained.htmlGroovy Bound properties for property change event notifications


Groovy Frameworks

https://examples.javacodegeeks.com/core-java/spock-tutorial-beginners/Groovy Spock Tutorial for use case tests: given, when, then, so
https://gebish.org/Geb - web automation w WebDriver, JQuery, Objects
Gradle
https://docs.gradle.org/current/userguide/getting_started.htmlGradle Getting Started
https://gradle.org/guides/Gradle basics
https://docs.gradle.org/current/userguide/declaring_repositories.htmlGradle for builds
https://circleci.com/docs/2.0/language-java/CircleCi gradle builds
Libraries

Mavencentral for libraries

Github for libraries

JCenter for Java libs


Testing

Unit tests
http://spockframework.org/spock/docs/1.3/all_in_one.htmlSpock Test framework

GEB https test framework


Groovy Sample Files

gtest6.groovy

My Groovy DBA test examples

ls /Volumes/GoogleDrive/'My Drive'/_work/learn/blearn-pc   -l | more 

MAC gdrive file access from shell - can create alias


Groovy compiler
Compiling and Running Groovy article 





















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 your PATH 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


  1. Groovy uses and extends a Java JDK
  2. Groovyc compiles Groovy source to executable classes with an option to capture the generated java source
  3. Groovysh compiles Groovy source to execute from a command line
  4. GroovyConsole provides a simple developer UI to build, test Groovy code and libraries
  5. code can be dynamic or compiled and executes on a JVM
  6. variables and properties can be static or dynamically typed
  7. provides multiple programming models:  functional, object, object-oriented
  8. Groovy Beans have more capability than Java beans and MBeans
    1. Java MBeans are management extended Beans ( see basic tutorial on MBeans )
  9. Groovy extends the JDK with additional features and functions
  10. can model event streams quickly using Gbeans as event sources, listeners, handlers for workflow modeling
  11. Expando MetaClass allows dynamic class definitions at runtime ( a prototype model like JS and other languages )
  12. Supports both immediate bindings of client to object ( like Java ) or deferred binding 
  13. Excellent JSON and XML support to build, use those documents easily
  14. String interpolation using Gstrings generates strings using embedded variable expressions
  15. Dynamic compilation of code or strings to generate immediate executables at runtime ( provides "smart" system code generation dynamically )
  16. Custom compilation of metaprogramming capabilities safely using AST transformations
  17. AST Transformations provides Groovy with improved compile-time metaprogramming capabilities allowing powerful flexibility at the language level, without a runtime performance penalty
  18. 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.
  19. Spock testing language is a BDD DSL that goes beyond Selenium, Cucumber, Gherkin
  20. 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
//==============================
//x3001 Groovy expando metaclass for dynamic behavior ..

class FileUpdateMgr extends Expando {
}
FileUpdateMgr.metaClass.getDateNDaysFromNow = { days -> 
    def cal = new GregorianCalendar()
    cal.roll Calendar.DAY_OF_MONTH, days
    new java.text.SimpleDateFormat().format(cal.time)
}
def mgr = new FileUpdateMgr()
mgr.name = "Jim"
mgr.newDate = mgr.getDateNDaysFromNow(12)
println "$mgr.name "
println "newDate from now: $mgr.newDate"


Groovy Expando Classes packaged - gtwf1-test.groovy

Groovy Expando clases in 1 file
package swt;

class ModelUser extends Expando {
    def methodMissing = { String name, args -> console.println "method> " || name  };
    def orderType;
} 
class ModelSystem extends Expando {
    def pout = { amsg -> console.println amsg  };
} 

// test case

def auser = new ModelUser()
auser.setOrderType( "network" )
println auser.getOrderType()



def system = new ModelSystem()
system.pout( "print a method call")






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 **

groovy-beans-propertyChange-listeners-2022-blog.mrhaki.com-Groovy Goodness Bound and Constrained Properties in GroovyBeans.pdf

example

groovy beans propertyChange listeners
/*
   x111c groovy bound property example - https://blog.mrhaki.com/2009/08/groovy-goodness-bound-and-constrained.html
*/

import groovy.beans.*
 
class Car {
   int numberOfDoors
   @Vetoable String model
   @Vetoable String brand
   boolean automatic
   @Bindable double price
  
   String toString() {
     "[Car details => brand: '${brand}', model: '${model}', #doors: '${numberOfDoors}', automatic: '${automatic}', price: '${price}']"
   }
}

import groovy.beans.*
import java.beans.*
 
def toyota = new Car(brand: 'Toyota', model: 'Verso', price: 28919, numberOfDoors: 5)
toyota.propertyChange = {
 if (it.propertyName == 'price') {
  println "The price has changed. Inform sales the new price is '${it.newValue}'."
 }
}
toyota.vetoableChange = { PropertyChangeEvent pce ->
 if (pce.propertyName == "brand") {
  if (!(pce.newValue in ['Toyota', 'Lexus'])) {
   throw new PropertyVetoException('New value is not Toyota or Lexus', pce)
  }
 }
 if (pce.propertyName == "model") {
  if (pce.newValue ==~ /.*\d+.*/) {
   throw new PropertyVetoException('No numbers in model names allowed.', pce)
  }
 }
}
 
toyota.price = 30995
assert 30995 == toyota.price
 
toyota.brand = 'Lexus'
assert 'Lexus' == toyota.brand
 
try {
 toyota.brand = 'AUDI'
 assert false: 'We should not be able to set this value.'
} catch (PropertyVetoException e) {
 assert true
 println " could not set brand to AUDI. car brand is ${toyota.brand}"
}
 
try {
 toyota.model = 'A5'
 assert false: 'We should not be able to set this value.'
} catch (PropertyVetoException e) {
 assert true
 println " could not set model to A5. car model is ${toyota.model}"
}



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

https://www.javacodegeeks.com/2021/11/13-best-java-decompilers-for-download-and-online-use-for-java-developers.html




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

  1. open groovyconsole normally
  2. use CTL + O to open file selector window
  3. select a groovy file
  4. press Enter
  5. << file opens normally in groovy console


Candidate Solutions



Transform input string by line to output print stream

//===========================
// transform input string by line to output print stream

def s1 = """    originID: { type: mongoose.Schema.Types.ObjectId, ref: 'projects' },
    parentID: { type: String}, // Can be used to track the parent asset
    buyerAccountId: { type: mongoose.Schema.Types.ObjectId, ref: 'accounts', required: true },
    sellerAccountId: { type: mongoose.Schema.Types.ObjectId, ref: 'accounts', required: true }, //Can be null if direct buy from project
    paymentId: { type: String },
    paymentMethodId: { type: String },
    amount: { type: Number, required: true },
    orderNumber: { type: Number },
    paymentType: { type: String },
    pricePerUnit: { type: Number, required: true },
    qty: {type: Number, required: true, default: 0},
    description: {type: String},
    status: {type: String, required: true},
    productName: { type: String },
    buyerName: { type: String },
    sellerName: { type: String },
"""
def fields = []
def lines = s1.readLines()
lines.forEach{ 
fields = it.split(":");
println "    \"" + fields[0].replace(" ","") + "\":\"\",";
//println "    \"" + fields[0] + "\": true,";
}



Step-by-step guide for Example



sample code block

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.groovysimple expando tests
gtxt-cnv1.groovysimple text conversion using split separator strings






Recommended Next Steps