Big Data/Analytics Zone is brought to you in partnership with:

Sam has posted 7 posts at DZone. View Full User Profile

Acquaintance With Groovy

04.10.2013
| 994 views |
  • submit to reddit

For any new language that I wish to learn, first I will try out to code sample application that just output the 'Hello World'

Let's see how it can be done in groovy, it is as simple as typing a text Hello World after the 'print' method.

e.g 
print 'Hello World!!'

You need to download and install anything in your computer just to try out the sample. You can use web console to execute the sample.

Open the web console: http://groovyconsole.appspot.com/

and then type, above example and click execute script, you will the output in output tab of the UI.

To do the same stuff in java, you have to create a class and add the System.out.print("Hello World"); in main method.

After that you have to compile(using javac) and then run using (java). isn't groovy simplified the syntaxt of a java program a lot.

You might have observed that there is no paranthesis and semicolon as they are optional in groovy.

Before exploring further, I would like to mention that groovy is not a replacement of java, it internally use java and make it more dynamic.

You can mix and match java and groovy code. Your final byte code generated through groovyc(similar to javac) is fully compatible to run with 'java' tool, ensure that %GROOVY_HOME%/embeddable/groovy-all-2.1.jar should be in classpath.

Let's go ahead and see some cool samples I tried out.


MarkupBuilder

This is a simple groovy class helps to generate the XML or html markup.
Let's try out an example to generate the xml file contains list of persons with name and gender

import groovy.xml.MarkupBuilder
def strWriterObj = new StringWriter() 
def xmlObj = new MarkupBuilder(strWriterObj) 
xmlObj.persons() {
    person(gender:'male', 'Alex')  
    person(gender:'male', 'Bob')  
    person(gender:'male', 'Cameron')  
}
println strWriterObj.toString()
the above code prints the formatted xml output as,
<persons>
  <person gender='male'>Alex</person>
  <person gender='male'>Bob</person>
  <person gender='male'>Cameron</person>
</persons>

I guess, you might have noticed the declaration in groovy. You can use 'def' instead of explicity type, groovy will take care of that for you.
Also, you can ignore access specifier as groovy automatically use 'private' for fields and 'public' for all methods.

XMLParser

Parsing and accessing elements in xml is pretty simple in groovy, let's parse the above xml generated using MarkupBuilder.

def sampleXml="""
  <persons>
    <person gender='male'>Alex</person>
    <person gender='male'>Bob</person>
    <person gender='male'>Cameron</person>
  </persons>
  """
def personsNode=new XmlParser().parseText(sampleXml)
//to print all person elements:
personsNode.person.each(
    { println "$it" }
)
//to print first person name
println personsNode.person[0].value
Groovy Templating

Groovy Templating works like a JSP kind of expressions, all works starts with $ will be evaluated at run time and substituted with the property value. 

def textWithPlaceholder='Nice to meet you $title. ${firstname} ${lastname} '
def binding=["title":"Mr", 'firstname':"Alex", 'lastname':"Nancy"]
def engine = new groovy.text.SimpleTemplateEngine() 
def result = engine.createTemplate(textWithPlaceholder).make(binding)
println result.toString()
Strings in groovy

There are 3 types of string syntaxes available in groovy, I will explain these with examples mentioned below.

(1)=>Simple Strings:
String s1='this is simple string'

(2)=>GStrings:
String s2="this is a GString..evaluates all expressions ${PATH} "

(3)=>Multiline Strings:
String s3="""this is a multiline
 string in groovy"""
IDE and Build tools support

Goovy plugins are available for all popular java IDEs like eclipse, netbeans, Spring Tool Suite(STS) etc.
if you would like to use maven for building groovy code, here is the dependency and plugin usage:

dependency:
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>2.0.5</version>
</dependency>
plug-in:   
<plugin>
<groupId>org.codehaus.gmaven</groupId>
<artifactId>gmaven-plugin</artifactId>
<version>${groovy.plugin.version}</version>
<executions>
<execution>
<goals>
<goal>compile</goal>
</goals>
<configuration>
<providerSelection>2.0</providerSelection>
<sources>
<fileset>
<directory>${pom.basedir}/src/</directory>
<includes>
<include>**/*.groovy</include>
</includes>
</fileset>
</sources>
</configuration>
</execution>
</executions>
</plugin>

Published at DZone with permission of its author, Sam Kyatham.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)