Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Groovy 2 Cookbook

You're reading from   Groovy 2 Cookbook Java and Groovy go together like ham and eggs, and this book is a great opportunity to learn how to exploit Groovy 2 to the full. Packed with recipes, both intermediate and advanced, it's a great way to speed up and modernize your programming.

Arrow left icon
Product type Paperback
Published in Oct 2013
Publisher Packt
ISBN-13 9781849519366
Length 394 pages
Edition 1st Edition
Languages
Arrow right icon
Authors (2):
Arrow left icon
Luciano Fiandesio Luciano Fiandesio
Author Profile Icon Luciano Fiandesio
Luciano Fiandesio
Andrey Adamovich Andrey Adamovich
Author Profile Icon Andrey Adamovich
Andrey Adamovich
Arrow right icon
View More author details
Toc

Table of Contents (17) Chapters Close

Groovy 2 Cookbook
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
1. Getting Started with Groovy 2. Using Groovy Ecosystem FREE CHAPTER 3. Using Groovy Language Features 4. Working with Files in Groovy 5. Working with XML in Groovy 6. Working with JSON in Groovy 7. Working with Databases in Groovy 8. Working with Web Services in Groovy 9. Metaprogramming and DSLs in Groovy 10. Concurrent Programming in Groovy Index

Executing Groovy code from the command line


Groovy, by definition, is a language with scripting features. Many developers approach Groovy by writing short scripts to automate repetitive tasks. The language provides a set of command-line tools that help you create scripts that are usable within your favorite shell.

In this recipe, we will cover the execution of a simple script with the help of the groovy command, which is made available to you after a successful Groovy installation (see the Installing Groovy on Windows recipe and Installing Groovy on Linux and OS X recipe).

How to do it...

Let's start with the most abused example in programming books, printing Hello, World!:

  1. The simplest way to execute Groovy code is by using the -e option and starting to write Groovy code on the same line:

    groovy -e "println 'Hello, World!'"
    
  2. You can also place the println 'Hello, World!' statement in a separate file; for example, hello.groovy, and execute that script with the following simple command:

    groovy hello.groovy
    
  3. In both cases, you'll see the same results:

    Hello, World!
    

How it works...

In step 1, the actual Groovy code resides in the double quotes (") and uses the predefined println method to print a Hello, World! string. But to explain where the println method actually comes from, we need to give a bit more details on Groovy internals.

Every script in Groovy (a command-line parameter or a standalone script file) is compiled on the fly into a class that extends the groovy.lang.Script class (Javadoc for this class can be found at http://groovy.codehaus.org/api/groovy/lang/Script.html).

Naturally, a Script class is eventually inherited from java.lang.Object, which is the base class for all classes in both Java and Groovy. But since Groovy adds its own extension methods to many standard JDK classes (see the Adding a functionality to the existing Java/Groovy classes recipe in Chapter 3, Using Groovy Language Features for Information on Custom Extension Modules), java.lang.Object is enriched with many useful methods including println (the relevant Java documentation can be found at http://groovy.codehaus.org/groovy-jdk/java/lang/Object.html#println(java.lang.Object)).

There's more...

In fact, the groovy command has several other useful command-line options. If you type groovy --help, you can get a full list of them as shown in the following screenshot:

Let's go through some of those options to get a better overview of the possibilities.

First of all, -classpath, --classpath, and -cp options work in a very similar way to the java command. You just specify a list of the *.jar files or list of directories with the *.class files. The only peculiarity is that -classpath must come as the first parameter in the command line; otherwise Groovy will not recognize it.

Another parameter that is common with the java command is -D, which allows to pass the system properties to your script in the following way:

groovy -Dmessage=world-e "println 'Hello, ' + System.getProperty('message')"

One of the strengths of Groovy (as opposed to Java) is its conciseness. This rule is also applied to what Groovy prints out if an exception occurs in your script:

groovy -e "throw new Exception()"
Caught: java.lang.Exception
java.lang.Exception at script_from_command_line.run(script_from_command_line:1)

To print the conventional full Java stack trace, you can use the -d or -debug options (some stack trace lines are omitted for brevity):

groovy -d -e "throw new Exception()"
Caught: java.lang.Exception
java.lang.Exception
    at sun.reflect.Native...
    ...
    at script_from_command_line.run(script_from_command_line:1)
    ...
    at org.codehaus.groovy.tools.GroovyStarter.main(...)

See also

For additional command-line features, please refer to the following recipes:

  • Using Groovy as a command-line text file editor

  • Using Groovy to start a server on the command line

For more information on the Groovy script structure and Groovy additions, go to:

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime