December 6, 2017
Anyone who has used Java may have faced some struggles. Not all things in vanilla Java, that is to say, without frameworks, are easy to do or clear to understand. On the other hand, you may have a friend who runs Python, for example, and laughs out loud watching you trying to parse a 10-line XML response.
But never fear! Groovy is here to help. Groovy has class-substitution with Java compatibility, so there is no harm in running it along with your Java classes.
In order to make the most of this tutorial you should have
- basic understanding of OOP,
- core knowledge of enterprise Java, and
- a little experience with web services.
I hope that this article will be helpful for all Java-enthusiasts whose work deals with XMLs. Also, I hope to create a younger generation of Java-developers using Groovy.
In this tutorial, I will use some dummy examples that a senior engineer might consider to be silly. Feel free to stop reading if that is the case, because I will not be showing you anything new here. My goal is to drive someone who has never tried using Groovy to give it a go.
If I were to describe Groovy with one sentence, I would say it is “For developers by developers.” If you are familiar with Java, you will definitely understand Groovy in 9 out of 10 examples, as Java code will be just a valid Groovy code. The idioms and constructions are straightforward, and many complicated features are made as simple as possible. Do not be afraid of that. Simple does not always mean poor quality or lack of maturity.
In this post, I will show you how easily you can execute a GET request to Google Geocoder, and parse XML response with just 8 lines of code. We will also take a look at how to do the same manipulation but with JSON response.
But first of all, we need Groovy. Here are a few facts.
- is an object-oriented programming language for the Java platform;
- is a dynamic language with features similar to those of
- Python (list and map literal notations),
- Ruby (metaprogramming),
- Perl, and
- Smalltalk (collections processing);
- can be used as a scripting language for Java Platform;
- is dynamically (or statically) compiled to Java Virtual Machine (JVM) bytecode, and interoperates with other Java code and libraries;
- was originally developed in 2003;
- was released in version 1.0 on January 2, 2007, and Groovy 2.0 in July, 2012;
- had its last major release, version 2.4, under Pivotal Software’s sponsorship which ended in March 2015;
- is in its latest stable release 2.4.13 under Apache Software Foundation.
- is being actively developed as evidenced by Groovy versions 2.5.0-beta-2 and 2.6.0-alpha-2 exist already;
- has an official web-site at groovy-lang.org.
Groovy also has a cool success story.
First of all, there is Grails Framework, whose authors get inspiration from Ruby-on-Rails. Another cool use for Groovy is Ratpack. If you have never heard of that, I suggest you Google it right after finishing this article.
Groovy is heavily used in enterprise. For example:
- Walmart’s mp3 website,
- LinkedIn uses Groovy for “Glu”,
- Vodafone’s music site,
- M6 (TV broadcasting company) and
If you have heard that Groovy is a dynamically typed language, understand that it is only half-true. Groovy can be both statically and dynamically typed, based on the circumstance. Groovy comes in handy when you need it most.
Best of all, Groovy loves Java. Groovy was built and designed to help ease the pain for those who parse 10,000 line XML files, work with IO, etc., in Java. The advent of Java8 introduced a large number of Groovy features implemented within it. That made life easier for Java users, but Groovy still has some aces up its sleeve to impress you.
So, how do you get fancy and shiny Groovy on your machine? Easy as pie. Just go to http://groovy-lang.org/download.html and download the Groovy version that you like. I would suggest not starting with alpha or beta versions, but with stable one.
If you use macOS or some Linux distributive, you can use SDKMAN! at http://sdkman.io/usage.html.
It will download Groovy and create all needed PATH variables. After download and installation are complete, you will be able to check your Groovy version.
That’s it. Now you have Groovy. If you have never used SDKMAN!, I encourage you to do so. There you will find plenty of sdk’s and tools, including scala, grails, maven, gradle and many-many others.
Once you have Groovy up and running, try out some things that come with sdk itself.
“Groovysh” stands for Groovy Shell, which is quite similar to the Java 9 jshell. This type of command-line tool is called an REPL and comes in handy when you need to evaluate some expression quickly.
Other cool stuff you get “for free” is groovyConsole, a GUI that allows you to write your code with autocompletion, syntax highlighting, and execution environment. It is similar to a shell, but way better and more powerful. For the educational purpose of this post, I will write all code in groovyConsole.
Talk is cheap, show me the code.
‘Nuff said! Let’s do a little bit of practice in Google Geocoder. I choose this service for two reasons: it is free of charge (for some requests you do not need an API key) and it can return both JSON and XML responses.
We will start with XML, but how should those parameters should look?
Okay, so there is a path variable in UTF-8 url-encoded format. Quite clear. Let’s code it. We will try to obtain the latitude and longitude of CoreValue HQ – 18 Overlook Ave, Suite 9, Rochelle Park, NJ.
Groovy naturally does not have that URLEncoder class. It comes from Java, but in Groovy it is totally okay to use it.
There is our response done with 9 lines of code, which might have been less if I had not made those empty lines separations. Let’s review what we have.
First of all, we use def’ instead of real type. That is a type variable already present, in Kotling or JS, for instance, it will also be included in Java 10. From my experience, it is worth it to actually appoint the real type you expect. If you name the type, say, String base instead of def base, both your teammates and you yourself will appreciate it in some 2 or 3 weeks. In case the type does not matter to you, using def is totally ok
To get the encoded address, I put all parts of it into list. With Groovy, you can create an ArrayList just with .
Then I encoded it by using URLEncoder from Java inside the clojure. Think of clojure as an anonymous method, something that Java8’s lambdas could look like, but do not.
After that I joined all of my encoded elements into one String separated by “,”.
Groovy supports String interpolation, so concatenating Strings has never been easier in Java. And here the quite exciting thing is “$base$queryParams”.toURL().text. We transform String into URL with just one method — toURL() and get response from it with .text command. Just like that.
Now let’s find latitude and longitude in that response. The response is big, but here we are:
Time to parse!
Could it be any easier? And as a reminder, it is all stuff out of the box.
Image parsing that XML in Java, JS, or .Net. In Groovy, we simply traverse the XML node tree to query the nodes as properties. This is what Groovy is all about – making complicated things simple.
Let’s do the same thing with JSON to show that indeed it is also simple.
There is one extra line of code, because we needed to import groovy.json to accomplish our task.
Instead of conclusions.
Groovy is extremely powerful but simple at the same time. But when using it, remember one thing – with great power comes great responsibility. Use your tools wisely.
** Special thanks to:
- Baruch Sadogursky
- Evegenii Borisov
- Ken Kousen
All of them inspired me, and I used their presentations or keynotes to make my own.