Shell scripting with groovy
by Dejan Bosanac
java -Djava.util.logging.config.file=app.properties -cp path_to/lib.jar -jar app.jar
So in most cases these applications have shell scripts for starting and stopping the application. In some cases you'll need few more scripts that works with your application.
Common tasks for startup script are:
- Setting local classpath for application
- Testing if required environment variables are set
- Executing java application
Why should you use groovy for this? and how?
First of all, Java developers find Java-like syntax scripting language easier to use, but huge advance is that you have access to all Java libraries that you need. For example you can establish XML-RPC or database connections if you have to.
I have the Java application that have XML-RPC interface and tends to crash from time to time because of unexpected signal 11 (more on this in some future post). I've created a groovy script that calls dummy XML-RPC method of the application and if an exception is thrown (meaning that application is not working properly) application is restarted. I've put this script in cron to be executed every five minutes and in case that application crashes it is restarted in few minutes. It's needless to say that I'm sleeping much better since then :). Of course this could be done in million other ways, but the point here is that this is ten-lines script and ten minutes of work.
We can also go one step further. Most of these standalone application main methods do tasks like:
- Parsing command line arguments
- Reading property files
- Initializing and configuring other classes in order to run application (Loggers, scheduler, server threads, ...)
This tasks could be also moved to startup scripts, leading to more maintainable application.
Command line argument parsing is the ideal job for scripting, because it's all about string comparison.
Some of the basic configuration parameters could be set on the top of the script too. Of course you can't avoid property files in general, because many libraries use them.
And if you have all the arguments and configuration parameters, you are free to initialize your object properly.
To make a shell script with groovy, all you need to do is to put
in the first line of the script, and you are back in Java-land.
Have you find any useful usage of groovy as a language for shell scripting?
Groovy man, but where?
Sounds wonderful ... except where do we find this groovy thing? Is there a URL, or is it like the Rainbow Festival, you have to know someone ;)
Groovy man, but where?
Ah, my bad ... URL is http://groovy.codehaus.org
Sure groovy is new. But I would prefer jython, as there are much more resources available (already accessible scripts). Reenvent the wheel new?