Saturday 28 June 2014

Why Java developer should learn another programming language called Groovy?

Welcome to my Groovy Learning Made Easy post.

It is always worth to be a polyglot learner and programmer. If you are a java developer, then why not to learn another programming language called Groovy. This post will provide you the getting started directions with sample code snippet for learning Groovy.

Why Java developer should learn another programming language, so called Groovy?
  • Languages other than Java that run on the JVM are called as alternative JVM Languages. For example - Groovy, Scala, Clojure, Jruby, Jython… Among those, Groovy is the most accessible alternative JVM language to Java developers.
  • As per polyglot programming pyramid by Ola Bini, Java can fit in static layer but it isn’t ideal language for solving problems in the dynamic layer. These problems include rapid web development, prototyping, scripting, and more. Groovy is designed to solve exactly such problems, though there are also other programming languages capable to solve such problems like Ruby, Clojure, etc.
  • Groovy is well-suited for writing domain-specific language (DSL). For example - Gradle build tool is written in Java and Groovy, and introduces a Groovy-based DSL instead of the more traditional XML form of declaring the project configuration.
  • The Groovy programming language is supported by Pivotal and the Groovy Community, so we can expect good community support. Also Groovy roadmap has the considerations of supporting new Java releases, for example JDK-8 support is targeted to include in Groovy 3.0 by Q4 2014.
  • Excellent interoperability between Groovy and Java. So the best thing is you can use your existing Java libraries in Groovy code. Basically Groovy extends java.lang.Object and adding some functional behavior. At the end, Groovy source code compiles to JVM bytecode.
  • Inspired by Smalltalk, Ruby, and Python, Groovy has implemented several language features that Java doesn't, such as: Function literals / Closures, First-class support for collections, First-class support for regular expressions, First-class support for XML processing (First-class support = that is built into the language syntax as opposed to requiring library calls)
  • Like Java, there are many Groovy based frameworks available. For example - Grails for web application development, Spock for writing acceptance tests, etc.
  • Groovy enjoys rich IDE support / Eclipse based Groovy/Grails tools suite, so Java developers don't need to learn new development tooling.


About Groovy…

  • is an agile and dynamic language for the Java Virtual Machine
  • builds upon the strengths of Java but has additional power features inspired by languages like Python, Ruby and Smalltalk
  • makes modern programming features available to Java developers with almost-zero learning curve
  • provides the ability to statically type check and statically compile your code for robustness and performance
  • supports Domain-Specific Languages and other compact syntax so your code becomes easy to read and maintain
  • makes writing shell and build scripts easy with its powerful processing primitives, OO abilities and an Ant DSL
  • increases developer productivity by reducing scaffolding code when developing web, GUI, database or console applications
  • simplifies testing by supporting unit testing and mocking out-of-the-box
  • seamlessly integrates with all existing Java classes and libraries
  • compiles straight to Java bytecode so you can use it anywhere you can use Java


Getting Started Guide to Learn Groovy

I recommend to follow steps in below sequence to getting started with Groovy quickly.

Step-1: Groovy environment setup

If you are java developer, then installing Groovy is all about just spending less than 15 minutes after downloading Groovy - http://groovy.codehaus.org/Installing+Groovy

If you already have Eclipse, let's install Groovy plugin in Eclipse. Alternatively you may consider GGST (Groovy/Grails Tool Suite).

Step-2: Groovy project setup

Download and setup my "GroovyQuickStart" project, because that would enable you to learn Groovy quickly using sample code snippet.
  1. Download zip file of / Clone project to your local machine.
  2. Then just import "GroovyQuickStart" project in Eclipse having Groovy plugins already installed.
  3. Fix all build path errors (Project -> Properties -> Java Build Path -> Libraries), such as JRE configuration, Groovy Libraries, etc.
  4. Now run "G00_BasicConcepts.groovy" groovy script files with Groovy Script option (Alt + Shift + X, G) in Eclipse and you should be able to see output in console without any error. That's it.
  5. As directed in next steps, let's start exploring each package containing code of ".groovy" files in given sequence of G00, G01*, G02*...

Step-3: Learning Basic concepts and syntax

Groovy eliminates much of Java's verbosity. It has advanced collection handling, supports functional concepts and brings dynamic typing to the JVM. By default Groovy imports the list of packages and hence those are always implicitly available for access in your Groovy code: groovy.lang.*, groovy.util.*, java.lang.*, java.io.*, java.math.BigDecimal, java.math.BigInteger, java.net.*, java.util.*.

In the downloaded "GroovyQuickStart" project, explore com.tirthal.learning.basic package for learning basic concepts and syntax of Groovy as well as features like Collections, Ranges, Functions, Closures...

Step-4: Working with XML in Groovy

All of Java's native XML processing options are available to access in Groovy, but Groovy brings new options for both low and high level processing of XML. Reading and writing of XML is made easier due to Groovy's dynamicity.

Groovy offers First-class XML processing. In the downloaded "GroovyQuickStart" project, explore com.tirthal.learning.xml package to realize how easy it is to read and write XML in Groovy. Also refer sample xml files in data folder of the project.

Reading XML
  • DomCategory - Low level access to Java's DOM API
  • XmlParser - High level API for DOM process, but entire document is loaded in memory. Eager evaluation. So prohibited for processing larger documents
  • XmlSlurper - Very similar to XmlParser, but using lazy evaluation. This means that only portion loaded into memory just before  they read. Ideal when need to access subset of content in the XML.
Writing XML
  • MarkupBuilder - Simple XML creation API
  • StreamingMarkupBuilder - Advanced XML creation and provides better support for creating large documents

Step-5: Groovy and Java interoperability

In the downloaded "GroovyQuickStart" project, explore com.tirthal.learning.interoperability package to understand how flexible it is to call Java from Groovy and vice-versa.

Calling Java from Groovy
  • Groovy works with existing Java libraries - Including popular libraries such as Google Guava or Apache Commons or your own proprietary libraries
  • If you intend your Groovy code to interoperate with Java, it can pay to use static types where possible, because it simplifies type overloading and dispatch
  • Use Grape for dependency management in Groovy. It is natively supported in Groovy language and build on Ivy.
Calling Groovy from Java
  • Calling Groovy from inside a Java application requires the Groovy JAR and other related JARs to be put into your Java application’s CLASSPATH, as they’re runtime dependencies.
  • Simply put the GROOVY_HOME/embeddable/groovy-all-x.jar file into your CLASSPATH.
  • There are several ways you can call Groovy code from inside a Java application:
    • Using the Bean Scripting Framework (BSF)—a.k.a. JSR 223
    • Using GroovyShell
    • Using GroovyClassLoader
    • Using GroovyScriptEngine
    • Using the embedded Groovy console
  • The most commonly used ways are - Groovy-ClassLoader and GroovyScriptEngine.

Step-6: Working with REST services

In the downloaded "GroovyQuickStart" project, explore com.tirthal.learning.rest package to know that how Groovy is well-suited working with REST services and JSON.
  • RestClient - encapsulates HTTP requests and responses
  • Groovy ConfigSlurper - for reading configuration file

Step-7: Unit testing in Groovy

Unit testing becomes vary important when working with dynamic languages, because the compiler doesn't enforce type-checking. In the downloaded "GroovyQuickStart" project, explore com.tirthal.learning.testing package to experience unit testing support in Groovy.
  • JUnit is built directly into the Groovy runtime
  • Mocking APIs are included in the Groovy platform
  • Advanced testing frameworks are also available

Step-8: Miscellaneous

Based on your interest and need, you can explore it further.
  • Groovy 2.0 introduces static compilation for Groovy - The newly released Groovy 2.0 brings key static features to the language with static type checking and static compilation, adopts JDK 7 related improvements with Project Coin syntax enhancements and the support of the new "invoke dynamic" JVM instruction, and becomes more modular than before.
  • Groovy 2.3 Introduces Traits - A trait is a reusable set of methods and fields that can be added to one or more classes. A class can be composed out of multiple traits without using multiple inheritance (and therefore avoiding the diamond problem).

Groovy performance

Be aware that,
  • Groovy isn’t always the best choice of language if your software has stringent performance requirements. Groovy objects extend from GroovyObject, which contains an invokeMethod(String name, Object args) method. Each time you call a Groovy method, that method isn’t called directly as it would in Java. Instead, it’s executed via the aforementioned invokeMethod(String name, Object args), which itself executes a number of reflection calls and lookups, which of course slows processing. The Groovy language developers have made several optimizations, and more will follow as future versions of Groovy take advantage of the new invokedynamic bytecode in the JVM.
  • A quick performance tip here is to utilize the groovyserv library, which starts up the JVM and Groovy extensions, making your scripts run that much faster.
  • Groovy has powerful XML and JSON parsing capabilities. Please refer Rick's "Groovy/Boon provide the fastest JSON parser for the JVM" post for detail. So Groovy can certainly be considered to do such XML/JSON parsing related piece of work in Java applications for performance and developer productivity benefits.


Also Refer


Finally, I would say "Happy Groovy Learning" to java developers and let’s share your feedback in the comment.

Sunday 8 June 2014

Java power tools series - Steps to setup Hotswap Agent in Eclipse

I hope, you have already read "Preface" of my java power tools series.

HotSwapAgent
  • Hotswap agent provides Java unlimited runtime class and resource redefinition.
  • Hotswap agent supports all major frameworks, it is free, open source and extensible.

What does it mean to you?

The main purpose of such tools is to avoid traditional java development methodology --- change -> restart and wait -> check. So developers can do java code changes and check those immediately without the need of app redeploy or JVM  bouncing process. That means, developers can focus more on writing code. Well, you can read my previous post on Tips to boost Java Developers Productivity for more detail.

You are lucky, if you use JRebel during development. But if your company cannot buy JRebel for you, then don't be sad. Alternatively you can try open source and free Hotswap Agent project which has similar goals, but few key differences are (at the time of writing this post):
  • JRebel is currently highly mature and has many plugins to support broad ecosystem.
  • JRebel provides good reporting like time you saved by using it.
  • JRebel is neither open source nor free.

To summarize, at present Hotswap Agent is in beta release and not mature enough like JRebel, but it is FREE. So just by spending your few minutes to setup Hotswap Agent in your development environment, you will be able to save your hours of efforts from server restarts during development.

Steps to setup Hotswap Agent in IDE

Important note:[ Vladimir(skybber) took initiative and used below mentioned steps with my consensus to write wiki documentation on Github about HotswapAgent setup in Eclipse IDE. Besides this, steps are also available to setup HotswapAgent in Intellij and NetBeans on wiki. Therefore, I recommend you to refer latest GitHub wiki page for HotswapAgent setup in IDE instead of below. ]

Hotswap Agent Quick Start page already has provided simple steps to setup it, and the page also has reference urls for setup guide of IntelliJ Idea and NetBeans IDEs.

As Eclipse and Tomcat are widely used for development, I thought to try Hotswap Agent with those and finally it worked when I disabled “Auto Reload” in Tomcat modules (Note - This is not specified in quick start page of Hotswap Agent site).

I followed to below steps setup Hotswap Agent in Eclipse IDE.

Step-1: Install “jvm.dll” DCEVM patch in JDK

I followed the same steps which are mentioned on HotswapAgent quick start page - Install section to patch Java Hotspot(r) file in JDK 1.7_55 and download HotswapAgent.jar file.

Step-2: In Eclipse - Tomcat Server - Runtime Environment - JRE must be mapped to the same JRE of JDK in which DECVM is patched in step-1

Step-3: Tomcat - Add “-XXaltjvm="dcevm" -javaagent:<PATH>\HotswapAgent.jar” in VM Arguments

Step-4:Disable “Auto Reload” in Tomcat web modules
This is most important step, otherwise you will not see power of Hotswap Agent in step-5.

Step-5: Run Tomcat in Debug mode and Enjoy java coding.
When you start your server in debug mode, you should see messages like below in Eclipse Console.

Now if you do code changes in java as well as configuration files of supported plugins (i.e. logback.xml), those would be ready for unit testing immediately without server restart.

Final Note
Overall Hotswap Agent works excellent, however the supported plugins are limited at present. So it may not work as expected when you do some of framework specific code/configuration changes. For example - when I changed value in one of Spring's annotation @RequestMapping, that didn't reload and reflected for unit testing instantly without server restart.

Updates History
  • 14/Jan/2015 - Added important note to refer HotswapAgent wiki on GitHub.
  • 14/Feb/2015 -  Now changes in @RequestMapping Spring annotation are supported, so I did strikethrough my earlier experience with that in final note section. 
Disclaimer
I am not biased to particular free or commercial tools, rather my objective is about sharing my own experience on set of tools.

Also Refer