An introduction to Groovy for Java developers with real-life examples that present how Groovy helped us win the 2nd prize in the Open Public Data Hackathon 2014 (http://www.ydmed.gov.gr/hackathon/)
JavaCro 2016 - From Java to Groovy: Adventure Time!Iván López Martín
Groovy is a dynamic language for the JVM and the natural evolution for a Java developer because its flat learning curve. If you want to know why developing with Groovy is an Adventure Time, this is your talk. You'll learn with examples the main characteristics that make Groovy a powerful and versatile language: dynamic typing, closures, lists and maps handling, power asserts, builders, metaprogramming, scripting, DSL's, AST transformations,... and many more.I can guarantee you that after the talk you'll want to learn more about Groovy and use it in your day at work.
Apache Groovy is a powerful, optionally typed and dynamic language, with static-typing and static compilation capabilities, for the Java platform aimed at improving developer productivity thanks to a concise, familiar and easy to learn syntax. It integrates smoothly with any Java program, and immediately delivers to your application powerful features, including scripting capabilities, Domain-Specific Language authoring, runtime and compile-time meta-programming and functional programming.
In this presentation, we'll see how Groovy simplifies the life of Java Developers. Basically, this talk would be for beginners where I would introduce powerful Groovy concepts like - Groovy Collections, Closure, Traits etc.
Apache Groovy: the language and the ecosystemKostas Saidis
An overview of the Groovy language and its awesome ecosystem, advocating Groovy as the language of choice for (a) Java developers that want to dive into dynamic languages or (b) for Javascript, Ruby or Python developers that want to dive into the Java platform.
The presentation was given at the 9th FOSSCOMM (16-17 April 2016) organized by the Software Libre Sociecy of the University of Piraues.
JavaCro 2016 - From Java to Groovy: Adventure Time!Iván López Martín
Groovy is a dynamic language for the JVM and the natural evolution for a Java developer because its flat learning curve. If you want to know why developing with Groovy is an Adventure Time, this is your talk. You'll learn with examples the main characteristics that make Groovy a powerful and versatile language: dynamic typing, closures, lists and maps handling, power asserts, builders, metaprogramming, scripting, DSL's, AST transformations,... and many more.I can guarantee you that after the talk you'll want to learn more about Groovy and use it in your day at work.
Apache Groovy is a powerful, optionally typed and dynamic language, with static-typing and static compilation capabilities, for the Java platform aimed at improving developer productivity thanks to a concise, familiar and easy to learn syntax. It integrates smoothly with any Java program, and immediately delivers to your application powerful features, including scripting capabilities, Domain-Specific Language authoring, runtime and compile-time meta-programming and functional programming.
In this presentation, we'll see how Groovy simplifies the life of Java Developers. Basically, this talk would be for beginners where I would introduce powerful Groovy concepts like - Groovy Collections, Closure, Traits etc.
Apache Groovy: the language and the ecosystemKostas Saidis
An overview of the Groovy language and its awesome ecosystem, advocating Groovy as the language of choice for (a) Java developers that want to dive into dynamic languages or (b) for Javascript, Ruby or Python developers that want to dive into the Java platform.
The presentation was given at the 9th FOSSCOMM (16-17 April 2016) organized by the Software Libre Sociecy of the University of Piraues.
Slides from my talk at Greach 2014:
"Groovy is a dynamic language that provides different types of metaprogramming techniques. In this talk we’ll mainly see runtime metaprogramming. I’ll explain Groovy Meta-Object-Protocol (MOP), the metaclass, how to intercept method calls, how to deal with method missing and property missing, the use of mixins and categories. All of these topics will be explained with examples in order to understand them.
Also, I’ll talk a little bit about compile-time metaprogramming with AST Transformations. AST Transformations provide a wonderful way of manipulating code at compile time via modifications of the Abstract Syntax Tree. We’ll see a basic but powerful example of what we can do with AST transformations."
The code is available at: https://github.com/lmivan/greach2014
Introduction to Groovy runtime metaprogramming and AST transformsMarcin Grzejszczak
Introduction to Groovy runtime metaprogramming and AST transforms - by Marcin Grzejszczak author of the http://toomuchcoding.blogspot.com blog.
The sources can be found here
Mercurial Bitbucket - https://bitbucket.org/gregorin1987/too-much-coding/src/e5ab7c69ab7b2796075fd6f087fbf31346aa2d2b/Groovy/ast/?at=default
Git Github - https://github.com/marcingrzejszczak/too-much-coding/tree/master/Groovy/ast
A Recovering Java Developer Learns to GoMatt Stine
As presented at OSCON 2014.
The Go programming language has emerged as a favorite tool of DevOps and cloud practitioners alike. In many ways, Go is more famous for what it doesn’t include than what it does, and co-author Rob Pike has said that Go represents a “less is more” approach to language design.
The Cloud Foundry engineering teams have steadily increased their use of Go for building components, starting with the Router, and progressing through Loggregator, the CLI, and more recently the Health Manager. As a “recovering-Java-developer-turned-DevOps-junkie” focused on helping our customers and community succeed with Cloud Foundry, it became very clear to me that I needed to add Go to my knowledge portfolio.
This talk will introduce Go and its distinctives to Java developers looking to add Go to their toolkits. We’ll cover Go vs. Java in terms of:
* type systems
* modularity
* programming idioms
* object-oriented constructs
* concurrency
Groovy Domain Specific Languages - SpringOne2GX 2012Guillaume Laforge
Paul King, Andrew Eisenberg and Guillaume Laforge present about implementation of Domain-Specific Languages in Groovy, while at the SpringOne2GX 2012 conference in Washington DC.
Groovy's AST Transformation is a compile time meta-programming technique and allows developer to hook into compilation process and add new fields or methods, or modify existing methods.
Go 1.10 Release Party, featuring what's new in Go 1.10 and a few deep dives into how Go works.
Presented at the PDX Go Meetup on April 24th, 2018.
https://www.meetup.com/PDX-Go/events/248938586/
Golang basics for Java developers - Part 1Robert Stern
A short overview of Golang with Java comparison.
Part 1 of the series "Microservice development with Golang".
Contains hints and example links for potential Gophers
Metaprogramming is the writing of computer programs that write or manipulate other programs (or themselves) as their data. - Wikipedia
The Groovy language supports two flavors of metaprogramming:
# Runtime metaprogramming, and
# Compile-time metaprogramming.
The first one allows altering the class model and the behavior of a program at runtime, while the second only occurs at compile-time.
Slides from my talk at Greach 2014:
"Groovy is a dynamic language that provides different types of metaprogramming techniques. In this talk we’ll mainly see runtime metaprogramming. I’ll explain Groovy Meta-Object-Protocol (MOP), the metaclass, how to intercept method calls, how to deal with method missing and property missing, the use of mixins and categories. All of these topics will be explained with examples in order to understand them.
Also, I’ll talk a little bit about compile-time metaprogramming with AST Transformations. AST Transformations provide a wonderful way of manipulating code at compile time via modifications of the Abstract Syntax Tree. We’ll see a basic but powerful example of what we can do with AST transformations."
The code is available at: https://github.com/lmivan/greach2014
Introduction to Groovy runtime metaprogramming and AST transformsMarcin Grzejszczak
Introduction to Groovy runtime metaprogramming and AST transforms - by Marcin Grzejszczak author of the http://toomuchcoding.blogspot.com blog.
The sources can be found here
Mercurial Bitbucket - https://bitbucket.org/gregorin1987/too-much-coding/src/e5ab7c69ab7b2796075fd6f087fbf31346aa2d2b/Groovy/ast/?at=default
Git Github - https://github.com/marcingrzejszczak/too-much-coding/tree/master/Groovy/ast
A Recovering Java Developer Learns to GoMatt Stine
As presented at OSCON 2014.
The Go programming language has emerged as a favorite tool of DevOps and cloud practitioners alike. In many ways, Go is more famous for what it doesn’t include than what it does, and co-author Rob Pike has said that Go represents a “less is more” approach to language design.
The Cloud Foundry engineering teams have steadily increased their use of Go for building components, starting with the Router, and progressing through Loggregator, the CLI, and more recently the Health Manager. As a “recovering-Java-developer-turned-DevOps-junkie” focused on helping our customers and community succeed with Cloud Foundry, it became very clear to me that I needed to add Go to my knowledge portfolio.
This talk will introduce Go and its distinctives to Java developers looking to add Go to their toolkits. We’ll cover Go vs. Java in terms of:
* type systems
* modularity
* programming idioms
* object-oriented constructs
* concurrency
Groovy Domain Specific Languages - SpringOne2GX 2012Guillaume Laforge
Paul King, Andrew Eisenberg and Guillaume Laforge present about implementation of Domain-Specific Languages in Groovy, while at the SpringOne2GX 2012 conference in Washington DC.
Groovy's AST Transformation is a compile time meta-programming technique and allows developer to hook into compilation process and add new fields or methods, or modify existing methods.
Go 1.10 Release Party, featuring what's new in Go 1.10 and a few deep dives into how Go works.
Presented at the PDX Go Meetup on April 24th, 2018.
https://www.meetup.com/PDX-Go/events/248938586/
Golang basics for Java developers - Part 1Robert Stern
A short overview of Golang with Java comparison.
Part 1 of the series "Microservice development with Golang".
Contains hints and example links for potential Gophers
Metaprogramming is the writing of computer programs that write or manipulate other programs (or themselves) as their data. - Wikipedia
The Groovy language supports two flavors of metaprogramming:
# Runtime metaprogramming, and
# Compile-time metaprogramming.
The first one allows altering the class model and the behavior of a program at runtime, while the second only occurs at compile-time.
Leveraging the language, Use and abuse of Design Patterns, Web Services, Writing DSLs, Groovy Testing, Polyglot Groovy, Parallel Processing, Enterprise Groovy
Refactoring: Improve the design of existing codeValerio Maggio
Refactoring: Improve the design of existing code
Software Engineering class on main refactoring techniques and bad smells reported in the famous Fawler's book on this topic!
AldenMC's capability brochure - A sampling of clients, projects and overall services with examples of corporate branding, websites, presentations and print collateral.
Groovy speech I held last year for introducing a new JVM language as substitute of Java. Easy and intuitive, it offers new features unknow to its parent yet.
New language from Google, static safe compiler, with GC and as fast as C++ or Java, syntax simpler then Python - 2 hour-long tutorial and you can start code.
In this talk Serhii will talk about Go, also known as Golang – an open source language developed at Google and used in production by companies such as Docker, Dropbox, Facebook and Google itself. Go is now heavily used as a general-purpose programming language that’s a pleasure to use and maintain. This introductory talk contains many live demos of basic language concepts, concurrency model, simple HTTP-based endpoint implementation and, of course, tests using build-in framework. This presentation will be interesting for backend engineers and DevOps to understand why Go had become so popular and how it might help to build robust and maintanable services.
Agenda of the presentation:
1. Go is not C, not Java, not anything
2. Rob Pike argument
3. Main ideas and basics
4. Concurrency model
5. Tools
6. Issues
Similar to An Introduction to Groovy for Java Developers (20)
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
JMeter webinar - integration with InfluxDB and GrafanaRTTS
Watch this recorded webinar about real-time monitoring of application performance. See how to integrate Apache JMeter, the open-source leader in performance testing, with InfluxDB, the open-source time-series database, and Grafana, the open-source analytics and visualization application.
In this webinar, we will review the benefits of leveraging InfluxDB and Grafana when executing load tests and demonstrate how these tools are used to visualize performance metrics.
Length: 30 minutes
Session Overview
-------------------------------------------
During this webinar, we will cover the following topics while demonstrating the integrations of JMeter, InfluxDB and Grafana:
- What out-of-the-box solutions are available for real-time monitoring JMeter tests?
- What are the benefits of integrating InfluxDB and Grafana into the load testing stack?
- Which features are provided by Grafana?
- Demonstration of InfluxDB and Grafana using a practice web application
To view the webinar recording, go to:
https://www.rttsweb.com/jmeter-integration-webinar
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
UiPath Test Automation using UiPath Test Suite series, part 3DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 3. In this session, we will cover desktop automation along with UI automation.
Topics covered:
UI automation Introduction,
UI automation Sample
Desktop automation flow
Pradeep Chinnala, Senior Consultant Automation Developer @WonderBotz and UiPath MVP
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
Are you looking to streamline your workflows and boost your projects’ efficiency? Do you find yourself searching for ways to add flexibility and control over your FME workflows? If so, you’re in the right place.
Join us for an insightful dive into the world of FME parameters, a critical element in optimizing workflow efficiency. This webinar marks the beginning of our three-part “Essentials of Automation” series. This first webinar is designed to equip you with the knowledge and skills to utilize parameters effectively: enhancing the flexibility, maintainability, and user control of your FME projects.
Here’s what you’ll gain:
- Essentials of FME Parameters: Understand the pivotal role of parameters, including Reader/Writer, Transformer, User, and FME Flow categories. Discover how they are the key to unlocking automation and optimization within your workflows.
- Practical Applications in FME Form: Delve into key user parameter types including choice, connections, and file URLs. Allow users to control how a workflow runs, making your workflows more reusable. Learn to import values and deliver the best user experience for your workflows while enhancing accuracy.
- Optimization Strategies in FME Flow: Explore the creation and strategic deployment of parameters in FME Flow, including the use of deployment and geometry parameters, to maximize workflow efficiency.
- Pro Tips for Success: Gain insights on parameterizing connections and leveraging new features like Conditional Visibility for clarity and simplicity.
We’ll wrap up with a glimpse into future webinars, followed by a Q&A session to address your specific questions surrounding this topic.
Don’t miss this opportunity to elevate your FME expertise and drive your projects to new heights of efficiency.
Neuro-symbolic is not enough, we need neuro-*semantic*Frank van Harmelen
Neuro-symbolic (NeSy) AI is on the rise. However, simply machine learning on just any symbolic structure is not sufficient to really harvest the gains of NeSy. These will only be gained when the symbolic structures have an actual semantics. I give an operational definition of semantics as “predictable inference”.
All of this illustrated with link prediction over knowledge graphs, but the argument is general.
Elevating Tactical DDD Patterns Through Object CalisthenicsDorra BARTAGUIZ
After immersing yourself in the blue book and its red counterpart, attending DDD-focused conferences, and applying tactical patterns, you're left with a crucial question: How do I ensure my design is effective? Tactical patterns within Domain-Driven Design (DDD) serve as guiding principles for creating clear and manageable domain models. However, achieving success with these patterns requires additional guidance. Interestingly, we've observed that a set of constraints initially designed for training purposes remarkably aligns with effective pattern implementation, offering a more ‘mechanical’ approach. Let's explore together how Object Calisthenics can elevate the design of your tactical DDD patterns, offering concrete help for those venturing into DDD for the first time!
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
In this insightful webinar, Inflectra explores how artificial intelligence (AI) is transforming software development and testing. Discover how AI-powered tools are revolutionizing every stage of the software development lifecycle (SDLC), from design and prototyping to testing, deployment, and monitoring.
Learn about:
• The Future of Testing: How AI is shifting testing towards verification, analysis, and higher-level skills, while reducing repetitive tasks.
• Test Automation: How AI-powered test case generation, optimization, and self-healing tests are making testing more efficient and effective.
• Visual Testing: Explore the emerging capabilities of AI in visual testing and how it's set to revolutionize UI verification.
• Inflectra's AI Solutions: See demonstrations of Inflectra's cutting-edge AI tools like the ChatGPT plugin and Azure Open AI platform, designed to streamline your testing process.
Whether you're a developer, tester, or QA professional, this webinar will give you valuable insights into how AI is shaping the future of software delivery.
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
💥 Speed, accuracy, and scaling – discover the superpowers of GenAI in action with UiPath Document Understanding and Communications Mining™:
See how to accelerate model training and optimize model performance with active learning
Learn about the latest enhancements to out-of-the-box document processing – with little to no training required
Get an exclusive demo of the new family of UiPath LLMs – GenAI models specialized for processing different types of documents and messages
This is a hands-on session specifically designed for automation developers and AI enthusiasts seeking to enhance their knowledge in leveraging the latest intelligent document processing capabilities offered by UiPath.
Speakers:
👨🏫 Andras Palfi, Senior Product Manager, UiPath
👩🏫 Lenka Dulovicova, Product Program Manager, UiPath
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
1. An Introduction to Groovy for Java
Developers
Kostas Saidis
www.niovity.com
Java Hellenic User Group Meetup
May 17, 2014
2. Outline
Introduction
to Groovy
1. Meet
Groovy
What is Groovy?
Groovy History
Why Groovy
2. Groovy
Basics
Using Groovy
Language
Overview
Closures
Lists and
Ranges
Maps
3. Real-life
Groovy
Open Public
Data Hackathon
Our Web App
JSON and REST
Groovlets
3. About Me
Kostas Saidis
saiko@niovity.com
Software & Data
Architect
Twitter:
@saikos
Linkedin:
http://gr.linkedin.com/in/saiko
Short bio:
Academia
BSc @ cs.unipi.gr (2001)
MSc @ di.uoa.gr (2004)
PhD @ di.uoa.gr (2011)
Industry
Freelance consultant, developer &
instructor since 1999
Founder & Managing Director
Java
Early Java enthusiast (1997)
Diving into Groovy since 2011
5. So, what brings us here?
The Java Platform
1. The language
2. The development kit
3. The virtual machine
The JVM is the key component!
The language and the JDK are aging, striving to catch up with new
developments.
Yet, Java 8 (with Streams and Lambdas) is a huge step forward!
6. What really brings us here!
The fun of programming
And Groovy programming is a whole lotta fun!
8. What is Groovy?
Groovy is
a feature-rich
Java-friendly
dynamic language
for the Java platform
9. Dynamic language?
What is a dynamic language?
A language that allows the types of variables to be
changed at runtime...
...among other things!
In Groovy
We can also change the behavior of objects and classes at runtime (with
Metaprogramming).
10. Example
Introduce a new method in Strings
1 String.metaClass.isUpperCase = {−>
2 delegate.toCharArray().every{ Character.isUpperCase(it) }
3 }
4 assert "GROOVY".isUpperCase() == true
5 assert "java".isUpperCase() == false
11.
12. Keep an open mind
A language that doesn't affect the way
you think about programming, is not
worth knowing.
Alan Perlis (1922 - 1990)
ACM Turing Award, 1966
13. Languages and Typing
Static vs. Dynamic
Statically typed: resolves the types of variables during
compilation. (e.g. Java)
Dynamically typed: resolves the types of variables at runtime.
(Groovy)
Weak vs. Strong
Strongly typed: you can't coerce to a wrong type --the
language guarantees type conformance. (Java & Groovy)
Weakly typed: you can screw everything up in all possible ways.
(e.g. C)
14. Java-friendly?
Groovy is:
A super version of Java
Augments Java with additional features → the GDK extends JDK in
so many helpful ways!
Designed as a companion language for Java
seamless integration with Java → an additional jar at runtime!
syntactically aligned with Java → syntactically correct Java will
work in Groovy (with some gotchas)!
compiles into JVM bytecode and preserves Java semantics → call
Groovy from Java == call Java from Java!
the 2nd language targeting the Java platform (JSR-241) →
Java was the first!
15. Feature-rich?
Groovy features
Fully object-oriented -- e.g. Traits in new version (2.3).
Optional typing --static or dynamic.
Duck typing.
List, map, range, regular expression literals.
Operator overloading.
Closures.
GroovyBeans.
GString and GPath.
Multimethods and metaprogramming.
Easily build custom DSLs (e.g. Gradle, Spock).
17. Groovy History
2003: Started by James Strachan and Bob McWhirter.
2004: Commissioned into JSR 241 but was almost abandoned.
2005: Brought back to life by Guillaume Laforge and Jeremy
Rayner.
2007: Groovy version 1.0.
2012: Groovy version 2.0.
2014: Groovy version 2.3 (official support for JDK 8).
18. Going Mainstream
Awesome Groovy-based tools & frameworks
Grails: Web development framework.
Gradle: Build automation tool. (my next one, if you like!)
Spock: Testing and specification framework.
CodeNarc: Static analysis tool.
easyb: Behavior-driven development framework.
Geb: Browser automation tool.
Griffon: Desktop app framework.
GPars: Multi-paradigm concurrency framework.
Groovy is supported by Pivotal.
19. Why Groovy?
Open Source. → Apache v2.0 License.
Near-zero learning curve. → You' ll become a Groovyist before
you realize it!
Leverage Java investment. → Rock-solid Java foundations.
Focus on your problem/app. → No more boilerplate!
More expressive, powerful and concise code. →
Productivity boost!
22. Groovy Tools
1. groovyc: Compliles groovy sources to JVM class files.
2. groovysh: Executes code interactively.
3. groovyConsole: GUI for interactive code execution
the best place to start .
4. groovy: Executes groovy scripts. Use it like bash, perl, python,
etc. (#!/usr/bin/groovy).
5. groovydoc: Generates documentation (like javadoc).
23. Using the Groovy Console
Use Groovy console to experiment, test and evaluate code.
24. Using the Groovy Interpreter
What date/time is it?
groovy −e "print new Date()"
List files recursively
groovy −e "new File('.').
eachFileRecurse { println it }"
25. Groovy scripts
No mandatory class definitions, no main methods, no
boilerplate.
Groovy creates them for you automagically!
Writing a Groovy script
Fibonacci.groovy
1 def fib(n) { // a method: the return type is not mandatory
2 n<2 ? 1 : fib(n−1)+fib(n−2)
3 }
4 if (args) { // command−line args
5 println fib(args[0] as Integer)
6 }
27. The Groovy Syntax
The majority of Java syntax is part of the Groovy syntax:
packages
imports
control structures
exception handling
classes and methods
object instantiation and method calls
Gotchas: Arrays, additional Groovy keywords, equals checks, etc.
28. Default imports
The following imports are included by default
java.lang.*
java.util.*
java.net.*
groovy.lang.*
groovy.util.*
java.math.BigInteger and java.math.BigDecimal
29. Groovy truth and equals
Null value is false.
Empty collection or map is false.
Empty string is false.
Zero value is false.
Gotcha
The == operator performs value equality (like Java
equals() ).
Use the method is for identity (available in every Groovy
object).
30. Groovy truth
Examples
1 def f = null
2 def t = "string"
3 assert f == false
4 assert t == true
5 list = []
6 map = [a:1]
7 assert list == false
8 assert map == false
9 String s = ""
10 assert s == false
11 i = 1
12 z = 0.0
13 assert i == true
14 assert z == false
31. Optionals
The following are optional:
semicolons: required only when you write multiple statements
in one line.
variable types: you decide what should be static or dynamic.
return statements: the last evaluated expression is the
default return value Gotcha .
parentheses: in method/function invocations Gotcha .
32. Optionals
Examples
1 //a method
2 def fac(n) { n<=1? 1 : n*fac(n−1)}
3 assert fac(3) == 6
4 //a method with default arg value
5 Integer factorial(Integer n=3) { return (n<=1? 1 : n*factorial(n
−1)) }
6 assert factorial(3) == 6
7 //invoke them without parentheses
8 def x = fac 3
9 def y = factorial 3
10 assert x == y
11 x = fac 3 + 1 //will calculate the factorial of 4.
12 assert x == fac(4) //Not always what you want!
13 x = fac(3 + 1) //use parentheses to disambiguate
14 //where parentheses are required
15 x = factorial() //Groovy will look for a property otherwise
16 assert x == fac(3)
33. Everything is an object
In Groovy:
all objects are derived from groovy.lang.GroovyObject, which
extends java.lang.Object.
all integral numbers are java.lang.Integers (or java.lang.Longs
using the proper Java notation).
all real numbers are java.math.BigDecimals.
all booleans are java.lang.Booleans.
34. Example
Everything's an object
1 def x = 1
2 int y = 1
3 assert x.class == Integer.class
4 assert y.class == Integer.class
5 def l = 1L
6 assert l.class == Long.class
7 def z = 0.3
8 assert z.class == BigDecimal.class
9 def flag = false
10 assert flag.class == Boolean.class
35. Strings
Groovy strings support:
Single quotes: ordinary strings.
Double quotes: ordinary strings with variable expansion
(GStrings).
Triple quotes: multi-line strings with variable expansion
(GStrings).
Slashy strings: strings enclosed in slashes; no need to escape
backslashes (useful for regular expressions and file paths).
operator overloading.
36. Examples
Strings
1 def mlStr = """ I am a multi−line
2 string!"""
3 def name = 'Angus';def surname = "Young"
4 //GStrings
5 def fullname = "$name $surname"
6 assert fullname == "Angus Young"
7 //operator overloading
8 def s = name * 3
9 assert s == "AngusAngusAngus"
10 s = fullname − name
11 assert s.trim() == surname
12 //slashy strings: preserve backslashes; no escaping is required
13 s = /nr/
14 assert s.size() == 4
37. Numbers
In Groovy all numbers are objects and BigDecimal arithmetic is used by
default.
Examples
1 def x = 3
2 assert x.plus(4) == x + 4
3 assert x.multiply(4) = x * 4
4 assert x.mod(4) == x % 4
5 //BigDecimal arithmetic
6 assert x/4 == x.div(4)
7 assert x/4 != x.intdiv(4)
8 assert 1/2 == 0.5
9 assert 1/3 == 0.3333333333
38. Java beans for human beings
In Groovy classes/beans:
Methods and classes are public by default.
Members are private by default.
The @PackageScope annotation is used for package scoped
class members.
Enhanced bean property support.
Dynamic constructor arguments.
Accessors (getters and setters) are generated automatically.
You can use the this keyword inside static methods (which
refers to this class).
39. Defining a Groovy class
A Person class
1 class Person {
2 String name
3 String surname
4 @Override
5 String toString() { "$surname, $name" }
6 }
Compile the Person.groovy
groovyc Person.groovy
Result: A ready to use Person.class
40. Use the Person class
Examples
From Groovy
1 p = new Person(name:"Theodoros", surname:"Kolokotronis")
2 assert p.toString() == "Theodoros Kolokotronis"
From Java
1 public class UsingPerson {
2 public static void main(String[] args) {
3 Person p = new Person();
4 p.setSurname("Young");
5 p.setName("Angus");
6 HashMap map = new HashMap();
7 map.put("name", "James");
8 map.put("surname", "Bond");
9 Person p1 = new Person(map);
10 }
11 }
41. Additional Operators
Safe navigation: x?.method()
Elvis: x = y ?: "no y"
Spread: ["java","groovy"]*.size() →
[4,6]
and more... <=> , =~ , ==~ , .@ , .&
42. Groovy powerful switch statement
1 switch(val) {
2 case "String":
3 //a string
4 break
5 case 10..100:
6 //a range
7 break
8 case Date:
9 //a date instance
10 break
11 case ~/gw+/:
12 //a reg−ex
13 break
14 case ['A', 'B']:
15 //a list
16 break
17 case { it instanceOf Number && it > Integer.MAX_VALUE }
18 //a closure
19 break
20 default:
21 //the default, treated as an "else" in Groovy (if
22 //all else fails, run the default). It should always
23 //be at the end of the switch statement.
24 }
43. Dynamic method dispatch
Java dispatches methods according to the type of the
arguments at compile time.
Groovy dispatches methods according to the type of the
arguments at runtime (multimethods).
Example
1 public void foo(String arg) { System.out.println("String"); }
2 public void foo(Object o) { System.out.println("Object"); }
3 Object o = "The type of o at runtime is String";
4 foo(o);
Java output: Object
Groovy output: String
44. Other differences from Java
There is no distinction between checked and unchecked
(runtime) exceptions. All exceptions are runtime exceptions!
Assertions are enabled by default.
Support for default values in method arguments.
use , is and as are keywords. Don't use them as variable
names.
You cannot declare more than one variables in for loops.
Arrays should be initialized with list-like syntax:
int[] a = [1, 2, 3] . Avoid int a[]
notation. Gotcha .
45. What is a closure?
Definition
A closure is a function together with a referencing environment.
Closures are anonymous functions that:
may accept parameters or return a value,
can be assigned to variables,
can be passed as arguments,
capture the variables of their surrounding lexical scope.
46. Groovy closures
Example
1 //a block of code assigned to a variable
2 def num = { int n −> n <=> 0 }
3 //what type is that?
4 assert num instanceof Closure
5 //it: the default closure argument
6 def num2 = { it <=> 0 }
7 assert num(−3) == num2(−3)
8 def x = 3
9 def times = { it * x }
10 assert times(3) == 9
11 x = 4
12 assert times(3) == 12
47. Functional Programming with Groovy
Currying & Higher-order functions
1 def func = { Closure c, int i, int j −>
2 c.call(i, j)
3 }
4 def add = func.curry { int i, int j −> i + j }
5 assert add(1,2) == 3
Composition
1 def add1 = { it + 1}
2 def sq = { it*it }
3 assert sq(add1(2)) == 9 //composition
4 def trans1 = add1 >> sq //left to right
5 assert trans1(2) == sq(add1(2))
6 def trans2 = add1 << sq //right to left
7 assert trans2(2) == add1(sq(2))
48. Closure owner and delegate
Example
1 //All closures have 3 implicit variables:
2 //this: as in Java
3 //owner: the enclosing object (either a closure or this)
4 //delegate: defaults to owner but can be changed
5 def test = {
6 ((this == owner) && (owner == delegate))
7 return { (this != owner) && (owner == delegate) }
8 }
9 assert test()()
10 //changing the delegate
11 def collectWithIndex = { Closure c−>
12 int i = 0
13 delegate.collect { c(it, i++) }
14 }
15 def map = ["name":"Angus", "surname":"Young"]
16 collectWithIndex.delegate = map
17 def list = collectWithIndex { entry, i −> [i, entry.key, entry.
value] }
18 assert list.flatten() == [0, "name", "Angus", 1, "surname", "
Young"]
49. Java 8 Lambda Expressions
Groovy closures ̸= Java lambda expressions.
Lambda expressions
Language facility for implementing functional interfaces
Interfaces with a single abstract method.
Function, Predicate, Supplier, Consumer.
Type inference at compile time.
Free variables must be final or effective final.
Do make your Java life easier.
50. Lists
Groovy offers:
Special syntax for list literals.
Additional common list methods.
Combine with closures for extremely expressive and powerful code!
Examples
1 //a list
2 def list = [1, "2", 3.0]
3 //what type is that?
4 assert list.class == ArrayList.class
5 //list elements
6 assert list.get(1) == "2"
7 assert list[1] == "2"
8 assert list.getAt(1) == "2"
9 //list.getAt(i) equivalent to list[i]
10 //negative indexes − not for the standard list.get(i)
11 assert list[−1] == 3.0
12 assert list.getAt(−2) == "2"
51. More list examples
1 //another list
2 def list3 = [5, 3, 1, ] //trailing comma OK
3 list3[0] = 3
4 list3.putAt(0, 3) //list.putAt(i,val) equivalent to list[i]=val
5 list3.set(0, 3)
6 assert list3 == [3, 3, 1]
7 //the in operator
8 assert '2' in list
9 assert list.contains('2')
10 //operator overloading
11 assert list + [1] == [1, "2", 3.0, 1]
12 assert list − [1] == ["2", 3.0]
13 assert list * 2 == [1, "2", 3.0, 1, "2", 3.0]
14 assert list + list == list * 2
15 //append to list
16 assert list << 1 == [1, "2", 3.0, 1]
17 def otherList = [4, 5.0, "6"]
18 assert list << otherList == [1, "2", 3.0, 1, [4, 5.0, "6"]]
19 //methods
20 assert list.flatten() == [1, "2", 3.0, 1, 4, 5.0, "6"]
21 assert list.flatten().unique() == [1, "2", 3.0, 4, 5.0, "6"]
52. Even more list examples
1 //methods that accept closure arguments
2 otherList = list.flatten().collect { it as Integer }
3 assert otherList == [1, 2, 3, 1, 4, 5, 6]
4 def toInt = { Object o −>
5 try { return o as Integer }
6 catch(e) { return 0 }
7 }
8 assert list.flatten().collect(toInt) == otherList
9 assert [5, "6", "seven"].collect(toInt) == [5, 6, 0]
10 //convert a list to a set
11 def set = otherList as Set
12 assert otherList instanceof List
13 assert set instanceof Set
14 //collect is available to all groovy objects
15 set.collect { it + 1 } == [2, 3, 4, 5, 6, 7]
16 //list to string
17 assert otherList.unique().join(', ') == '1, 2, 3, 4, 5, 6'
53. Enough with these list examples
1 //some more list methods
2 assert otherList.count(1) == 2
3 assert otherList.sum() == 22
4 assert otherList.intersect([1, 3, 4]) == [1, 3, 4]
5 assert otherList.disjoint([0, 10, 20])
6 assert otherList.min() == 1
7 assert otherList.max() == 6
8 assert otherList.reverse().unique().sort() == [1, 2, 3, 4, 5, 6]
9 //some more closures
10 assert otherList.findAll { it%2 == 0} == [2, 4, 6]
11 assert otherList.every { it > 0 } //checks whether the closure
holds for every list element
12 assert !otherList.every { it < 1 }
13 def listWithNulls = [1, null, 2]
14 assert !listWithNulls.every() //checks whether groovy truth
holds for every element
15 //the spread (*.) operator
16 def strings = ['one', 'the other', 'and another']
17 assert strings*.size() == strings.collect { it.size() }
18 //list*.action() calls list.collect { it.action() }
19 assert strings*.toUpperCase() == ['ONE', 'THE OTHER', 'AND
ANOTHER']
56. Maps
Groovy:
offers pecial syntax for map literals.
provides dditional common map methods.
uses maps + closures for duck typing: if it walks and swims like
a duck, it is a duck! → rapid implementation of interfaces
Examples
1 //a map
2 def map = ['id' : 12, 'name' : "John", 'surname' : "Doe"]
3 assert map.size() == 3
4 //keys which are valid Java identifiers need no quotes
5 def now = new Date()
6 def map2 = [
7 id : 1,
8 value : 2.0,
9 "peter's birthday": now
10 ]
57. More maps examples
1 //we can use map.key when key is valid Java identifier
2 assert map2.id == 1
3 //we can quote the key if needed
4 assert map2."peter's birthday" == now
5 //we can also use subscription notation map[key]
6 assert map2["peter's birthday"] == now
7 //and the standard get method
8 assert map2.get('value') == 2
9 assert map.get('foo') == null
10 //default value when key not found
11 assert map.get('foo', 'No such key') == 'No such key'
12 //adds the default value in the map
13 assert map.containsKey('foo')
14 //what type is the map?
15 try {
16 assert map.class == LinkedHashMap.class
17 }
18 catch(Error e) {
19 assert map.class == null //the map is looking for the 'class
' key
20 map.getClass() == LinkedHashMap.class
21 }
58. Even more maps examples
1 //put/update values
2 map.newKey = "new key's value"
3 map2['newKey'] = map.newKey
4 //use parentheses to add the value of a var in a map (and not
its name)
5 def anotherKey = "address"
6 map[(anotherKey)] = "Petraki 28"
7 assert map.address == "Petraki 28"
8 //iterate with each
9 map.each { println "In each: ${it.class}" }
10 //the closure argument is a Map.Entry instance
11 map.each { println "In each again: ${it.key} = ${it.value}" }
12 //all Java Map methods are here
13 assert !map.isEmpty()
14 assert map.containsKey('id')
15 assert map.containsValue(12)
16 //use a HashMap instead of a LinkedHashMap
17 def map3 = new HashMap()
18 assert map3.getClass() == HashMap.class
19 //empty map
20 def map4 = [:]
21 assert !map4//empty map is false
63. Open Public Data Hackathon
Held between 15 - 30 April 2014.
Organized by the Ministry of Administration Reform and E-Governance
(ydmed.gr), in association with:
1. aspete.gr
2. hua.gr
3. ellak.gr
Requirement: deliver an app that utilizes open public data (from
data.gov.gr or elsewhere).
64. We won the 2nd prize!
And Groovy helped us do it!
We shall discuss:
1. How to build a RESTful API with Groovy and Restlet.
2. How to build dynamic web pages with Groovlets.
65. Our Web App
A prototype of a cloud service for
Accessing/retrieving data
Searching/querying data
Visualizing/embedding data
through a powerful RESTful API.
68. The data model
We have
Kept thins as simple as possible.
Data source groups: Sets of
Data sources: Tabular data in excel files arranged
in columns
and rows.
After all, it is a prototype!
75. Groovlets
Groovy scripts on the server side
Compiled on the fly
No boilerplate
With some handy implicit variables provided by default
request,response : Http servler request and
response
params : request parameters
context, application : the ServletContext
object
session : the HttpSession object
out : the writer of the response
sout : the output stream of the response
html: a groovy.xml.MarkupBuilder which writes to out
76. Display a data source in HTML table
source.grovy
1 String groupId = request.getParameter("grp")
2 String srcId = request.getParameter("src")
3 def group = Config.instance.sourceGroups.get(groupId)
4 def sources = group.dataSources()
5 int index = srcId as Integer
6 def source = group.dataSources().get(index)
7 println """
8 ...
9 <table class="table table−bordered table−striped" >
10 <thead>
11 <tr>
12 <th>#</th>
13 ${source.columnNames.collect {"<th>$it</th>"}.join("")}
14 </tr>
15 </thead>
16 <tbody >
17 """
77. HTML table continued
source.grovy
1 source.rows.eachWithIndex {Map row, int i −>
2 println """
3 <tr>
4 <td>${i+1}</td>
5 ${source.columnNames.collect{ "<td>${row.get(it)}</td>"}.join
("")}
6 </tr>
7 """
8 }
9 println """
10 </tbody>
11 </table>
12 ...
13 """
79. Groovy is Java on steroids!
Easy to use: Its integration with the Java platform is insanely
brilliant!
Expressive: Do more with less code!
Effective: Focus on your app and stop wasting your time with
the irrelevant!
Agile: Groovy is agile and rapid prototyping is a few Groovy lines
away!
Leverage Java expertise. Build upon your Java skills.
Powerful: The swiss army knife of the Java hacker!
80. Swiss army knife, indeed
Ain't this groovy or what?
db.groovy
1 @GrabConfig(systemClassLoader=true)
2 @Grab(group='mysql', module='mysql−connector−java', version='
5.1.6')
3 import groovy.sql.Sql
4 def query="select count(*) as c, date(creationDate) as d from
dofields group by d order by c desc limit 10"
5 def url="jdbc:mysql://localhost:3306/test_db?characterEncoding=
utf−8"
6 def (u,p)=["test","test"]
7 try {
8 def sql = Sql.newInstance(url,u,p,"com.mysql.jdbc.Driver")
9 sql.eachRow(query) { println("${it.c}:${it.d}") }
10 }
11 catch(e) { e.printStackTrace() }
81. Output
Run it
groovy db
Output
1 9427:2004−08−20
2 6615:2004−10−29
3 5498:2004−10−08
4 5103:2004−08−31
5 4864:2004−10−14
6 4675:2004−10−31
7 4583:2004−10−05
8 4570:2004−08−21
9 4339:2004−09−30
10 4235:2004−10−30
83. We 've only scratched the surface
Groovy topics not covered
Metaprogramming
Grape
Builders
Working with XML
Working with SQL
Testing
And much, much more...
Perhaps in a 2nd part?
84. What about performance?
Programmers have spent far too much time
worrying about efficiency in the wrong places
at the wrong times; premature optimization is
the root of all evil.
Donald E. Knuth
ACM Turing Award, 1974
85. Put in other terms
The reason to use Groovy should be because it
improves your performance not the computer's.
matthew@stackoverflow
86. About Groovy Performance
Sorry, it hasn't bothered me yet.
Groovy 2.x introduced the @CompileStatic annotation.
Most of Groovy method calls are compiled into direct JVM bytecode
method calls.
People report that Groovy reaches to almost identical performance
with Java.
Start with Groovy and (re)write your performance-critical
classes in Java as you grow.
You can find various benchmarks and performance comparisons
on the web.
Any volunteers for benchmarking, should we do a 2nd part?
87. Resources
1. Programming Groovy 2, V. Subramaniam, The Pragmatic
Bookshelf, 978-1-937785-30-7, 2013
2. Groovy in Action, D. Koenig, A. Glover, P. King, G. Laforge and J.
Skeet, Manning Publications, 1-932394-84-2, 2007
3. Groovy Web Site
http://groovy.codehaus.org
4. Groovy language documentation beta
http://beta.groovy-lang.org/docs/
groovy-2.3.0/html/documentation/