Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 2

[ 27 ]

You can try this script against any running Java application. Just add the following
switches to the Java startup command of the application. This instructs your JVM
to start up with an open JMX connection on the port 3333. For simplicity, we have
abstained from using a secure connection or password authentication:


-Dcom.sun.management.jmxremote.port=3333-Dcom.sun.management.jmxremote.
authenticate=false-Dcom.sun.management.jmxremote.ssl=false


After running the script and connecting to an application, we get instant feedback
about the state of our heap usage:


$groovy monitor.groovy


HEAP USAGE


Memory usage : 1118880


Memory usage after GC: 607128


If you are not familiar with JMX, don't worry. The point to be grasped here is that
Groovy unleashes the power of the JVM and APIs, and puts them at your disposal
through the command-line shell. My starting point for the previous script was an
existing Java program that implemented the JMX API calls I needed. This is a slightly
cleaned up version of the script, which exploits some Groovy syntax that we will
learn about later. In practically no time, it is possible to drop Java API code into a
Groovy script and you have a command-line version to play with. The possibilities
for tool development are endless.


Shebang scripts


If you are running Groovy on UNIX, Linux, Mac OS X, or in the Cygwin shell for
Windows, you can go one step further with this approach. The Groovy script engine
is designed to work as a proper shell scripting language and supports the "shebang"
#! characters. By placing #!/usr/bin/env groovy as the first line of a script,
the shell will pass the remainder of the script for processing by Groovy. These are
commonly referred to as shebang scripts. We can modify our Hello.groovy
as follows:


#!/usr/bin/env groovy
println "Hello, World!"

Now, if we change the permissions of the file to executable, we can call it directly
from the shell:


$mv Hello.groovy Hello
$chmod a+x Hello
$./Hello
Hello, World!

Free download pdf