Apache Groovy: the language and the ecosystem
-
Upload
kostas-saidis -
Category
Technology
-
view
1.446 -
download
3
Transcript of Apache Groovy: the language and the ecosystem
Apache Groovy:the language and its ecosystem
Kostas Saidis, Agapios Avramidis
www.niovity.com
9th FOSSCOMMFree and Open Source Software Communities Meeting
April 16, 2016
Outline
Apache GroovyTop 10reasonsto use it
TheEcosystem
Niovity
We are a software companyusing a Java/Groovy/Javascript stack
Niovity Butterfly
We offer a web-based repository platformfor end-to-end data management
Our clients include Academic Libraries, Public Benefit Foundations, Research Institutes and Private Companies
www.OpenDataCloud.gr
2nd PrizePublic Open Data Hackathon 2014
Target audience
FOSS hackersthat the Java Platformand have a little experience withdynamic languages*
* like Javascript, Ruby, Python or Perl
Target audience
FOSS hackersthat dynamic languagesand have a little experience with theJava Platform
The Java what?
The Java Platform
1. The Java language2. The Java development kit (JDK)3. The Java virtual machine (JVM)
The JVM is the key component!
The JVM goes Polyglot
The Java Virtual MachineI A rock-solid, enterprise-grade runtime environment that can
execute multiple languages (not only Java).I Groovy, Javascript, Ruby, Python, Scala, Clojure, Kotlin, Fantom
and many others...
Most of the additional JVM languages are dynamic ones!
Dynamic LanguagesI Execute many common programming behaviors at runtime –in
contrast to static languages that perform them duringcompilation.
I Dynamic type checking.I Dynamic method dispatch†.I Support meta-programming (compiled constructs can be
modified programmatically at runtime).
†made faster with the invokedynamic bytecode instruction introduced in Java 7.
Flame War
Static vs Dynamic
Groovy
The best of both worlds in the JVM
Part I
Meet Apache GroovyA feature-rich, Java-friendly, dynamic language for the Java Platform
Groovy Tools
groovy-lang.org
1. groovyc: Compliles groovy sources to JVM bytecode (class files).2. groovysh: Executes code interactively (REPL).3. groovyConsole: GUI app for interactive code execution.4. groovy: Executes groovy scripts (you can use it like bash, perl,
python, etc).5. groovydoc: Generates documentation (like javadoc).6. Grape: An embedded jar dependency manager.
@groovylang #groovylang
The best place to start
Start from the Groovy console (GUI app)
Or the Groovy Web Console
Why Groovy
Top 10 + 1 reasons to use Groovy
Why Groovy #1
Groovy feels like a superset of Java with a simpler syntax
I Designed as a companion language for Java: Groovy issyntactically aligned with Java.
I Augments Java with additional features.I Literals for lists, maps, ranges, regular expressions, string
interpolation with GStrings.I GDK libraries extend JDK libraries in so many helpful ways.I Supported by all major Java IDEs (Eclipse, IntelliJ, Netbeans).
Groovy is Java on Steroids!
Groovy powerful switch statement1 switch(val) {2 case ”String”: //a string3 break4 case 10..100: //a range5 break6 case Date: //a date instance7 break8 case ~/gw+/: //a reg−ex9 break
10 case [’A’, ’B’]: //a list11 break12 case { it instanceOf Number && it > Integer.MAX_VALUE }13 //a closure14 break15 default:16 //the default, treated as an ”else” in Groovy.17 }
New methods introduced in Java libraries
List files recursively
groovy −e ”new File(’.’).eachFileRecurse { println it }”
I The method eachFileRecurse has been added to thejava.io.File class.
I Also an example of executing code given directly as text. Alldynamic languages support this.
A better syntax for common things
Example1 //lists2 List<Integer> list = [1, 2, 3]3 assert list[0] == 14 //operator overloading5 list << 46 assert list.size() == 47 //maps8 Map<String, String> map = [’one’:’1’, ”two”: ”2”, three:’3’]9 assert list[1] == map[’two’] as Integer
10 map.one = ’none’11 //GStrings12 String s = ”string”13 println ”value of s = $s”14 //Java ordinary methods are here15 map.put(s, ’4’)16 //with optional parentheses17 map.put s, 4
Why Groovy #2
Groovy is Object-oriented
I Supports Java Interfaces, Classes and Enums.I With some additional conventions and facilities (e.g. Groovy
properties) that make our life easier.I Supports Traits: a controlled way to implement multiple
inheritance, avoiding the diamond issue.
POGOs: Fat-free POJOs
Employee.groovy1 class Person {2 String name3 String surname4 }5 Person p = new Person(name:”N”, surname:”S”)6 assert p.name == ”N”7 assert p.getName() == ”N”8 test.surname = ”F”9 test.setSurname(”F”)
Traits
Maximize reuse1 interface Greeter {2 String greet()3 }4 trait Someone implements Greeter {5 String name6 String greet() { ”Hello, I’m $name, a ${class.getName()}!” }7 }8 trait Robot implements Greeter {9 String id
10 String greet() { ”Hello, I’m $id, a ${class.getName()}!” }11 }12 class Person implements Someone {13 String surname14 }15 class Cyborg implements Someone, Robot {16 String greet() { System.currentTimeMillis() % 2 == 1 ?
Someone.super.greet() : Robot.super.greet() }17 }
Why Groovy #3
Groovy supports Closures smartly and elegantly
A closure is an anonymous function together with a referencingenvironment.
Think of closures as anonymous blocks of code that:I can accept parameters or return a value,I can be assigned to variables,I can be passed as arguments,I capture the variables of their surrounding lexical scope.
Example1 //a closure assigned to a variable2 def multiplier = { Number x, Number y −> x * y }3 //invocation of the closure4 assert multiplier(2, 3) == 65 //partial application6 def doubler = multiplier.curry(2)7 assert doubler(3) == 68 //another doubler9 def otherDoubler = { it * 2 } //it −> the first arg
10 otherDoubler(3) == doubler(3)11 //closure as the last argument pattern12 void method(X x, Y y, Closure c)13 def c = { println ’booh booh’ }14 //invoke the method15 method(x, y, c)16 //alternate, more readable syntax17 method(x, y) { println ’booh booh’ }
Collection Manipulation1 //a groovy list (ArrayList behind the scenes)2 def list = [12, 2, 34, 4, 15]3 //Collection.collect(Closure c) − extra method available in
Groovy JDK4 //So, given a closure5 def inc = { it + 1 }6 //we can invoke7 list.collect(inc) == [13, 3, 35, 5, 16]8 //or pass the closure code directly9 assert list.collect{ it + 1 } == [13, 3, 35, 5, 16]
10 //some more fun11 list.findAll{ it > 10 }.groupBy{ it % 2 == 0 ? ’even’ : ’odd’ }
== [even:[12, 34], odd:[15]]
Owner and delegate1 class Test {2 long x = 23 def xTimes = { l −> x * l }4 }5 Test test = new Test()6 assert test.xTimes.owner == test7 assert test.xTimes.delegate == test8 test.xTimes(3) == 69 test.x = 3
10 test.xTimes(3) == 911 def map = [x:4]12 assert test.xTimes.resolveStrategy == Closure.OWNER_FIRST13 test.xTimes.resolveStrategy = Closure.DELEGATE_FIRST14 test.xTimes.delegate = map15 assert test.xTimes(3) == 12
Why Groovy #4
Groovy supports meta-proramming
I Annotations and AST transformations: compile-timemeta-programming.
I Meta-object protocol: runtime metaprogramming.
Compile-time meta-programming
Annotations example1 @Canonical Person {2 String name3 String surname4 }5 //@Canonical = @EqualsAndHashCode, @ToString and
@TupleConstructor6 def p1 = new Person(name:”N”, surname:”S”)7 //but also8 def p2 = new Person(”N”, ”S”)9 //Groovy == is Java’s equals()
10 assert p1 == p2
Runtime meta-programming
Introduce a new method in Strings1 String.metaClass.isUpperCase = {2 delegate.toCharArray().every{ Character.isUpperCase(it) }3 }4 String.metaClass.isLowerCase = {5 !delegate.isUpperCase()6 }7 assert ”JAVA”.isUpperCase()8 assert ”groovy”.isLowerCase()
Why Groovy #5
Groovy offers seamless integration with Java
I Syntactically correct Java will work in Groovy (with somegotchas).
I You get all groovy magic by just adding a jar in the classpath.I Call Groovy from Java == call Java from Java.I Joint compilation: mix Java and Groovy.
Mix Java and Groovy
Fetcher.java1 public interface Fetcher<V> {2 V fetch();3 }
Person.groovy1 @Canonical class Person implements Fetcher<String>{2 String name3 String surname4 @Override5 String toString() { ”$surname, $name” }6 @Override7 String fetch() { toString() }8 }
Mix Java and Groovy
UsingPerson.java1 public class UsingPerson {2 public static void main(String[] args) {3 Person p = new Person(”Theodoros”, ”Kolokotronis”);4 System.out.println(p.fetch());5 }6 }
Joint compilation
> groovyc Fetcher.java Person.groovy UsingPerson.java −j
> java −cp groovy−all.jar:. UsingPerson
> Kolokotronis, Theodoros
Why Groovy #6
Groovy is a Java-powered scripting language
Echo.java1 public class Echo {2 public static void main(String[] args) {3 if (args != null && args.length > 0) {4 //for Java < 8 you need a third−party library5 System.out.println(String.join(” ”, args));6 }7 }8 }
Echo.groovy (no boilerplate)1 if (args) {2 println args.join(’ ’)3 }
Querying a MySQL database using JDBC
db.groovy1 @GrabConfig(systemClassLoader=true)2 @Grab(’mysql:mysql−connector−java:5.1.6’)3 import groovy.sql.Sql4 try {5 def sql = Sql.newInstance(args[0], args[1], args[2], ”com.mysql
.jdbc.Driver”)6 def query=”select count(*) as c, date(cDate) as d from table
group by d order by c”7 sql.eachRow(query) { row −> println ”${row.c}:${row.d}” }8 }9 catch(e) { e.printStackTrace() }
Exploit the full power of Java effectively
Isn’t this Groovy or what?
> groovy db jdbc:mysql://localhost:3306/test test test123
Output1 9427:2004−08−202 6615:2004−10−293 5498:2004−10−084 5103:2004−08−315 4864:2004−10−146 4675:2004−10−317 4583:2004−10−058 4570:2004−08−219 4339:2004−09−30
10 4235:2004−10−30
Why Groovy #7
Groovy is well-suited for implementing custom DSLsDomain-Specific Languages are tailored to expressing a particularproblem.
For ExampleI Regular expressions: a DSL for text pattern matching.I SQL: a DSL for querying and managing relational data.
Groovy-based DSLs: builders, template engines and more.
FOSSCOMM 2016 Programme
The data1 def presentations = [2 [3 date : ’2016−04−16’,4 start: ’10:30’,5 end : ’11:00’,6 title: ’Welcome’,7 who : [’Software Libre Society’]8 ],9 [
10 date : ’2016−04−16’,11 start: ’16:00’,12 end : ’17:00’,13 title: ’Apache Groovy: the language and the ecosystem’,14 who : [’Agapios Avramidis’, ’Kostas Saidis’]15 ]16 ]
FOSSCOMM 2016 Programme
Groovy MarkupTemplateEngine1 yieldUnescaped ’<!DOCTYPE html>’2 html(lang:’el’) {3 head {4 meta (’http−equiv’:’...’)5 title (’FOSSCOMM 2016’)6 }7 body {8 [’2016−04−16’, ’2016−04−17’].each { date −>9 h1 (date)
10 list.findAll{it.date == date}.sort{it.start}.each{ p−>11 div {12 span (”${p.start} − ${p.end} − ”)13 big (p.title)14 br()15 strong (p.who.join(’,’))16 }17 }18 }19 }20 }
FOSSCOMM 2016 Programme
The generated HTML1 <!DOCTYPE html><html lang=’el’>2 <head>3 <meta http−equiv=’...’/><title>FOSSCOMM 2016</title>4 </head><body>5 <h1>2016−04−16</h1><div>6 <span>10:30 − 11:00 − </span><big>Welcome</big><br
/><strong>Software Libre Society</strong>7 </div><div>8 <span>16:00 − 17:00 − </span><big>Apache Groovy: the
language and the ecosystem</big><br/><strong>Agapios Avramidis,Kostas Saidis</strong>
9 </div><h1>2016−04−17</h1>10 </body>11 </html>
Why Groovy #8
Groovy supports optional type checking and static compilation
I In Groovy, most of the type checking is performed at runtime.I Use @TypeChecked & @CompileStatic annotations to maximize
static checks during compilation.I @TypeChecked performs static type checking, yet it
dispatches methods through the MOP (permits runtimemeta-programming).
I @CompileStatic = @TypeChecked+ “static” method linking (noMOP); is the closest you can get to javac-generated bytecode(in both behavior & performance).
Default type checking behavior
Example1 class Test {2 def s13 Integer s2 = 20164 void test() {5 s1 = ”fosscomm”6 assert s1.class == String.class7 s1 = 20168 s1.class == Integer.class9 s2 = ”fosscomm” //fails at runtime
10 }11 }12 new Test().test()
Enable static type checking
Example1 import groovy.transform.TypeChecked2 @TypeChecked class Test {3 def s14 Integer s2 = 20165 void test() {6 s1 = ”fosscomm”7 assert s1.class == String.class8 s1 = 20169 s1.class == Integer.class
10 s2 = ”fosscomm” //fails at compile−time11 }12 }13 new Test().test()
Languages and Typing
A statically-typed language resolves the types of variables duringcompilation you cannot change the type of a variable. Java, opt.Groovy
A dynamically-typed language resolves the types of variables atruntime you can change the type of a variable. Ruby, opt. Groovy
A strongly-typed language guarantees type conformance youcan’t coerce a variable to a wrong type. Java, Ruby, Groovy
A weakly-typed language has type abstractions that leak you canscrew everything up in all possible ways. C
Why Groovy #9
Groovy runs on Android
I Java on Android is very verbose(i.e. anonymous inner classes)I Use groovy 2.4.+ (smaller core jar, grooid compiler)I Supported by Gradle (plugin groovyx.grood.groovy-android) and
Android StudioI Groovy dynamic features can be used but avoid generating
classes at runtimeI Use @CompileStatic and properly configure ProGuard to be safe
Java and groovy on Android
Java1 button.setOnClickListener(new View.OnClickListener() {2 @Override3 void onClick(View v) {4 startActivity(intent);5 }6 });
Groovy1 button.onClickListener = { startActivity(intent) }
Why Groovy #10
A mature open source technology that is here to stay!
I More than a decade long history‡.I Free and Open Source Software (Apache License v2).I Joined the ASF in 2015.
‡Groovy was the first “second language” proposed for the JVM (back in 2004).
Why Groovy #10 + 1
Groovy has a vibrant community and ecosystem
Everything that runs on the JVM is part of the Groovy ecosystem.
Including all Java tools, libraries and frameworks out there!
Thank you!
Just kidding!
Part II
The Groovy EcosystemAwesome tools, libraries and frameworks written in Groovy
or for Groovy§
§We are only including projects with commit activity in 2016. Apologies if we missed some!
All things groovy
SysAdmin & DevOps
Building & Testing
Web & Cloud
Desktop & Mobile
Documents & Pages
Concurrency
Other
All projects are licensed under the Apache Software Foundation License v2, expect noted otherwise.
SysAdmin & DevOps
sdkmanA tool for managing different versions of SDKs
At a glance
sdkmanI Install, switch, remote and listing candidate SDKsI Inspired by RVM and rbenvI Written in bash and requires curl and unzipI Easy to install ( curl -s http://get.sdkman.io | bash)I Command line client (CLI) and APIsI Website
Example
List Candidatessdk list
List all versions of Groovy
sdk list groovy
Install latest Groovy
sdk install groovy
CRaSHA Shell for the JVM
At a glance
ConceptsI Modes
I Standalone and Attach through attach API of Hotspot JVM)I Embedded (web apps)
I ConnectorsI JVM, SSH, Telnet, Web (requires WebSocket)
FeaturesI Connect to any JVM (ssh, telnet, web)I Completion, help, pipes.I Built-in commands (jmx, jdbc, thread, memory usage)I Extensible (create new commands in java or groovy)I Authentication (simple, Jaas, key-based)I Free and Open Source Software (LGPL v2.1)I Website
GroovyServReduces startup time of the JVM
At a glance
GroovyServI Quick startup of Groovy scripts (groovyClient)I Utilizes a JVM process running in background (server)I If a server is not running when a client is invoked, the client
runs a server in backgroundI Available in sdkmanI Website
sshoogrA DSL for working with remote SSH servers
Example1 import static com.aestasit.infrastructure.ssh.DefaultSsh.*2 remoteSession(’user:pass@host:port’) {3 exec ’ls −la’4 remoteFile(’/tmp/test.txt’).text = ’test’5 //uploading6 scp {7 from { localFile ”$buildDir/test.file” }8 into { remoteFile ’/tmp/test.file’ }9 }10 }
Groovy VFSA DSL that wraps the Apache Commons VFS
Example1 def vfs = new VFS()2 //simple copy3 vfs.cp ’ftp://foo.example/myfile’, ’sftp://bar.example/yourfile’4 vfs {5 // Lists all files on a remote site6 ls (’http://first.example’) { println it.name }7 // Streams the output8 cat (’http://first.example/myfile’) { strm−>9 println strm.text10 }11 // Create a new folder on a remote site12 mkdir ’sftp://second.example/my/new/folder’13 }
Building & Testing
GradleEmerge from build hell
At a glance
GradleI Combines the best of Ant, Ivy and Maven (files, dependencies,
conventions)I In a smart and extensible way (Deep API, Groovy DSL, Plugins)I Offering clean builds that are easy to read and maintainI Polyglot (not only Java)I Multi-project buildsI Incremental and parallel executionI Backed by Gradle IncI Website
Example build script
build.gradle1 apply plugin: ”java”2 //Introduces a set of Maven−style conventions3 //(tasks, source locations, dependency configurations, etc)4 group = ”org.foo.something”5 version = ”1.0−SNAPSHOT”6 repositories {7 //resolve all external dependencies via Maven central8 mavenCentral()9 }
10 dependencies {11 //each name (compile, testCompile, etc) refers to12 //a configuration introduced by the java plugin13 compile ”commons−io:commons−io:2.4”14 testCompile ”junit:junit:4.11”15 runtime files(”lib/foo.jar”, ”lib/bar.jar”)16 }
SpockThe enterprise-ready testing and specification framework
At a glance
SpockI Tool for performing unit/integration/functional tests for Java &
Groovy software.I Combines JUnit, Mockito and JBehave (units, mocks and BDD)
using a Groovy DSL.I Well-structured, given-then-when/setup-expect-where
specifications.I That read like plain English (and generate readable reports, too).I Clear insights of what went wrong.I Parameterized tests, data-driven specifications.I Website
Example spock spec
DataDrivenSpec1 class DataDrivenSpec extends Specification {2 def ”maximum of two numbers”() {3 expect:4 Math.max(a, b) == c5 where:6 a << [3, 5, 9]7 b << [7, 4, 9]8 c << [7, 5, 9]9 }
10 def ”minimum of #a and #b is #c”() {11 expect:12 Math.min(a, b) == c13 where:14 a | b || c15 3 | 7 || 316 5 | 4 || 417 9 | 9 || 918 }19 }
GebA browser automation tool
At a glance
GebI Tool for functional/web/acceptance testing (integration with
Spock, JUnit, TestNG).I Also, can be used for scripting, scraping and general browser
automation.I Build on top of WebDriver library (Selinium 2.0)I Provides a content definition DSL (jQuery-like)I Website
Geb from groovy1 import geb.Browser2 Browser.drive {3 go ”http://myapp.com/login”4 assert $(”h1”).text() == ”Please Login”5 $(”form.login”).with {6 username = ”admin”7 password = ”password”8 login().click()9 }
10 assert $(”h1”).text() == ”Admin Section”11 }
BetamaxTool for mocking external HTTP resources in tests
At a glance
BetamaxI Mock HTTP resources such as Web services or REST APIs.I Inspired by Ruby’s VCR.I Intercepts HTTP connections, stores their responses to “tapes”,
and replays previously recorded responses from the tape.I Tapes are stored to disk as YAML files. Different tests can have
different tapes.I Works well with Geb, JUnit and Spock. One liner to add it to
Gradle.I Website
Example
A Spock spec with Betamax1 class TwitterServiceSpec {2 @Rule Recorder recorder = new Recorder()3 def twitterService = new TwitterService()4 @Betamax(tape=”twitter”)5 def ”searches tweets ok”() {6 when:7 def tweets = twitterService.search(”#hashtag”)8 then:9 tweets.every{ it.text ~= /#hashtag/ }
10 }11 }
CodeNarcA static code analysis tool for groovy
At a glance
CodenarcI Analyzes and reports code for defects and inconsistenciesI Reporting (HTML, XML)I Contains a predefined set of rules (348)I Provides a framework for creating new rulesI Integration with other tools (Gradle, Maven, Grails, Sonar,
Jenkins, Grails, Griffon)I Website
Using Codenarc
build.gradle1 apply plugin: ’codenarc’2 codenarcMain {3 configFile file(’config/codenarc−rules.groovy’)4 }5 codenarcTest {6 configFile file(’config/codenarc−test−rules.groovy’)7 }
config/codenarc-rules.groovy1 ruleset {2 description ’Rules for my Groovy Gradle Project’3 ruleset(’rulesets/basic.xml’) { exclude ’ClassForName’ }4 LineLength { length = 150 }5 StatelessClass {6 name = ’StatelessDao’7 applyToClassNames = ’*Dao’8 }9 }
LazybonesProject creation tool that uses packaged templates
At a glance
LazybonesI Project creation tool that helps you bootstrap a project from a
template.I Lazybones templates are like Maven archetypes or Yeoman
generators.I Project templates can incorporate sub-templates.I Simple and effective.I Available in sdkman.I Website
Example
Install Lazybones
sdk install lazybones
Use Lazybones to create a project
lazybones create <template name> [template version] <target
directory> [options]
lazybones create java−app my−app −Ppackage=org.foo.bar −−with
−git
lazybones generate controller
Web & Cloud
Mainly Java Projects
Spring IOThe most widely used
Java server-sideframework.Backed by Pivotal.
Spring Boot supportsGroovy scripts.
Vert.xThe polyglot toolkit forreactive applications
on the JVM.Backed by the Eclipse
Foundation.
Full support for Groovy.
ElasticSearchThe Java distributedcluster for real-time
search.Backed by Elastic.
Supports Groovyserver-side scripts and a
Groovy client.
GrailsPowerful web application framework for the JVM
At a glance
GrailsI Convention over configuration, app profiles, reasonable
defaults, opinionated APIs, DSLs and more.I Inspired by Ruby on Rails.I Wraps Spring MVC and offers a GORM supporting Hibernate,
MongoDB, Neo4j, Cassandra & Redis.I Over a 100 plugins.I Available in sdkman.I Website
Example
Hello world Web app with Grails
grails create−app helloworld
cd helloworld
grails create−controller hello
1 package helloworld2 class HelloController {3 def index() {4 render ”Hello World!”5 }6 }
grails run−app
RatpackLean & powerful HTTP apps for the JVM
At a glance
RatpackI A set of libraries that facilitate fast, efficient, scalable and
evolvable HTTP apps.I Flexible and unopinionated.I Inspired by Sinatra, built on Netty networking engine.I Asynchronous, non-blocking, event-driven architecture (like
node.js).I Offers lazybones templates.I Website
Example
Hello world Web app with Ratpack1 @Grapes([2 @Grab(’io.ratpack:ratpack−groovy:1.2.0’),3 @Grab(’org.slf4j:slf4j−simple:1.7.12’)4 ])5 import static ratpack.groovy.Groovy.ratpack6 ratpack {7 handlers {8 get {9 render ”Hello World!”
10 }11 get(”:name”) {12 render ”Hello $pathTokens.name!”13 }14 }15 }
GlideA toolkit for Google App Engine
At a glance
GlideI Lets you develop and deploy applications to Google App Engine
JavaI Best suited for small-medium complexity appsI Provides a simple Webb App StructureI Has almost zero configurationI Supports hot reloadingI Uses GaelykI Available in sdkmanI Website
Desktop & Mobile
GriffonA framework for developing desktop apps
At a glance
GriffonI Inspired by GrailsI Convention over Configuration, Don’t Repeat Yourself (DRY), MVCI Testing supported out of the boxI Swing and JavaFX UI toolkitsI Extensible via pluginsI Website
griffon create−app my−app
GroovyFXGroovy bindings for JAVA FX 8
At a glance
GroovyFXI Aims to simplify the development of Java FX applicationsI Relies on groovy’s DSL features and AST transformations to
reduce boilerplate.I Provides a SceneGraphBuilder, which supports for all JavaFX
componentsI Each class in JavaFX has a corresponding GroovyFX node (i.e.
Scene class will be scene node)I Website
Example
Hello world GroovyFX1 import static groovyx.javafx.GroovyFX.start2 start {3 stage(title: ’GroovyFX Hello World’, visible: true) {4 scene(fill: BLACK, width: 500, height: 250) {5 hbox(padding: 60) {6 text(text: ’Groovy’, font: ’80pt sanserif’) {7 fill linearGradient(endX: 0, stops: [PALEGREEN,
SEAGREEN])8 }9 text(text: ’FX’, font: ’80pt sanserif’) {
10 fill linearGradient(endX: 0, stops: [CYAN, DODGERBLUE])
11 effect dropShadow(color: DODGERBLUE, radius: 25,spread: 0.25)
12 }13 }14 }15 }16 }
SwissKnifeAnnotation Library for Android
At a glance
SwissKnifeI Based on ButterKnife and AndroidAnnotationsI Relies on groovy AST transformationsI Inject resourcesI Inject views dynamicallyI Add callback methods to actionsI Execute in the UI thread or the backgroundI Website
Inject Resources1 @StringRes(R.string.msg)2 String msg3 @AnimationRes(R.anim.fade_in)4 Animation fadeInAnim
Inject views1 @InjectView(R.id.first_button)2 Button button13 @InjectView(R.id.list_view)4 ListView listView
Add callback method1 @OnClick(R.id.button)2 public void onButtonClicked(Button button) {3 Toast.makeText(this, ”Button clicked”, Toast.LENGTH_SHOT).
show()4 }
Documents & Pages
GrainStatic website generator
At a glance
GrainI Supports compression and minification for sourcesI Has built-in SASS/SCSS supportI Supports Markdown, reStructuredText and AsciiDoctorI Each static resource is represented as a Groovy map.I Resources can be processed with groovy code
(SiteConfig.groovy)I Website
Example
Resource mapper closure:Executed upon change1 resource_mapper = { resources −>2 resources.collect { Map resource −>3 if (resource.location =~/\/blog\/.*/) {4 // Select all the resources which5 // contain files placed under /blog dir6 // Rewrite url for blog posts7 def unParsedDate = resource.date8 def date = Date.parse(site.datetime_format, resource.date)9 .format(’yyyy/MM/dd/’)
10 def title = resource.title.toLowerCase()11 .replaceAll(”\\s+”,”−”)12 resource + [url: ”/blog/$date$title/”]13 } else {14 resource15 }16 }17 }
Groovy Document BuilderA DSL for creating Word & PDF documents
Example1 @Grab(’com.craigburke.document:pdf:0.4.14’)2 @Grab(’com.craigburke.document:word:0.4.14’)3 import com.craigburke.document.builder.PdfDocumentBuilder4 import com.craigburke.document.builder.WordDocumentBuilder5 def word = new WordDocumentBuilder(new File(’example.docx’))6 def pdf = new PdfDocumentBuilder(new File(’example.pdf’))7 word.create {8 document {9 paragraph ’Hello World (Word)’10 }11 }12 pdf.create {13 document {14 paragraph ’Hello World (PDF)’15 }16 }
Concurrency
RxGroovyGroovy Reactive Extensions for the JVM
At a glance
RxGroovyI ReactivX: APIs for asynchronous programming with observable
streams (aka ReactiveExtensions –Rx).I RxGroovy is the Groovy adapter of RxJava.I ReactiveX is a combination of the best ideas from the Observer
pattern, the Iterator pattern, and functional programming.I Website
Example
Fetch wikipedia articles asynchronously1 def fetchWikipediaArticle(String... articleNames) {2 return Observable.create { subscriber −>3 Thread.start {4 for (articleName in articleNames) {5 if (subscriber.unsubscribed) {6 return7 }8 subscriber.onNext(new URL(”http://en.wikipedia.org/wiki/
${articleName}”).text)9 }
10 if (!subscriber.unsubscribed) {11 subscriber.onCompleted()12 }13 }14 return subscriber15 }16 }17 fetchWikipediaArticle(”Tiger”, ”Elephant”)18 .subscribe { println it.substring(0, 100) }
GParsConcurrency and parallelism framework for the JVM
At a glance
GParsI Offers high-level concurrency and parallelism while leveraging
the multi-core hardware.I Map/ReduceI Fork/JoinI ActorsI DataflowI Software Transactional MemoryI And more..I Website
NextflowA DSL for data-driven computational pipelines
At a glance
NextflowI Polyglot dataflows on Linux.I Nextflow scripts are defined by composing many different
processes.I Each process can be written in any scripting language
supported by Linux.I Coordinate and synchronize the processes execution by simply
specifying their inputs and outputs.I Requires Java 7, easy to install (curl -fsSL get.nextflow.io |
bash).I Based on GPars.I Website
Example
helloworld.nf1 str = Channel.from(’hello’, ’hola’, ’bonjour’, ’ciao’)2 process printEnv {3 input:4 env HELLO from str5 ’’’6 echo $HELLO world!7 ’’’8 }
hello world!
ciao world!
bonjour world!
hola world!
Other
GrooscriptGroovy to Javascript transpiler
Example1 @Grab(’org.grooscript:grooscript:1.2.3’)2 import org.grooscript.GrooScript3 def groovy = ’’’4 def sayHello = { println ”Hello ${it}!” }5 sayHello(’Javascript’)6 ’’’7 println GrooScript.convert groovy8 //the JS9 var sayHello = function(it) {10 return gs.println(”Hello ” + (it) + ”!”);11 };12 gs.execCall(sayHello, this, [”Javascript”]);
Conclusion
A language that doesn’t affect the wayyou think about programming is not
worth knowing.
Alan Perlis (1922 - 1990)ACM Turing Award, 1966
Apache Groovy
The best language for diving into dynamic featuresfor Java hackers
The best language for diving into the Java platformfor Javascripters, Rubyists and Pythonistas¶
Perl hackers are diving into Perl 6, aren’t they?
¶after Rhino/Nashorn, JRuby and Jython respectively
Thank you
@niovity
Proudly powered byLATEX
Using the Beamer class &the Wronki theme (slightly modified).