Monday, June 6, 2011

Ten More Groovy One-Liners

The post Ten Groovy One Liners to Impress Your Friends specifically focuses on ten things that Groovy can do in a single line. The particular ten examples are based on the list of ten described in Marcus Kazmierczak's 10 Scala One Liners to Impress Your Friends plus an eleventh example based on the "bonus" FizzBuzz example presented in Ricardo Tomasi's 10 CoffeeScript One Liners to Impress Your Friends. Those ten examples were interesting and insightful, but I use this post to demonstrate another set of Groovy one-liners that can be helpful and insightful.

There are several reasons single line code examples can be useful. First, they can be useful in production software when they provide less code without sacrificing readability. Not all single lines of code can pull this off, but it's highly desirable when they do. Most of my examples in this post are simple to read and understand, but perform the expected function in one (often short) line. A second benefit of single line solutions is that they demonstrate certain features, library calls, and syntax of programming languages. A particular advantage of single-line solutions for Groovy and some other languages is the ability to invoke the single line from the command line. This is done in Groovy with the -e option and I intend to use groovy -e to demonstrate all ten examples in this post.

The ten scripts demonstrated in this post are very simple and largely demonstrate Groovy's rich features. Many of these functions could be implemented with operating system commands or shell scripts, but an advantage to performing these via Groovy is that all of these particular scripts are independent of operating system and should work on any operating system on which a Java Virtual Machine is supported. Where these single lines would most likely be used would be within larger scripts used in the development environment.


1. List JVM Available TimeZone IDs

The TimeZones provided by each JVM are provided with String names. The supported TimeZones for a particular JVM can be easily identified with the following single line of Groovy.

TimeZone.getAvailableIDs().sort().each{ println it }

The next screen snapshot shows execution of this single line of Groovy code via groovy -e.



2. Binary File Copying

Copying a file with a single line of Groovy is nifty. There's more than one way, but the approach shown here works even for binary files.

new File("NewWordDocument.doc").bytes = new File("WordDocument.doc").bytes

The next screen snapshot shows that this works.



3. Acquiring Host Information

Groovy makes it easy to use Java's InetAddress class to determine information about the host. I show two examples of Groovy scripts taking advantage of this class. The code examples are followed by the screen snapshot showing execution of the two commands on the command line. Note that I did some character escaping on the second example as part of its running in the DOS terminal.

println "${InetAddress.localHost}"

println "${InetAddress.localHost}\n${InetAddress.localHost.loopbackAddress}"



4. Current Date/Time in Readable Format

The Groovy GDK's Date class provides a significant convenience in this example.

println new Date().dateTimeString  



5. Display Contents of JAR Manifest File

I covered use of Groovy to see a Manifest file's contents in the blog post Viewing a JAR's Manifest File. The example I showed there is repeated here. In this case, I use a Lucene JAR, but it could any JAR or WAR or EAR file.

new java.util.jar.JarFile('C:/lucene-3.0.2/lucene-core-3.0.2.jar').manifest.mainAttributes.entrySet().each{println "${it.key}: ${it.value}"}



6. Simple HTML Scraping

As I demonstrated in my blog post Minimalistic HTTP Clients with Groovy, Groovy makes it easy to extract text contents of web page. The following example uses http://java.net specifically, but any URL could be used.

println "http://java.net".toURL().text 

I don't show the output here because it includes rather lengthy XML.


7. Determine Machine's Byte Order

I demonstrated how easy it is to get the byte order in ByteOrder: Especially Useful with Groovy Scripts. Here's the one liner.

println java.nio.ByteOrder.nativeOrder() 



8. Joining Elements into Single String

The Collection.join() method makes it easy to generate a single String in Groovy that represents all items in the collection.

println "${['Dustin', 'Inspired', 'Actual', 'Events'].join("_")}"



9. Access Environment Variables

Groovy makes it trivial to list all environment variables in a small, single-line script.

System.getenv().each{println it}



10. Deleting a Directory and Its Contents in One Line

I previously covered the utility of Groovy GDK's File.deleteDir() method in Groovy JDK (GDK): File.deleteDir() and show an example of that again here. This trivial line of Groovy script deletes a directory and its contents. Use it with care!

new File('trashDir').deleteDir()



Conclusion

This post provides a small taste of how Groovy can support significant functionality with concise but expressive syntax. These examples are very simple in large part due to Groovy's convenience methods, especially as provided in the GDK.

4 comments:

alamin said...

There are several reasons single line code examples can be useful.very informative post.this site is also very useful to us.

bootz15 said...

Thanks, very useful except I don't think byte order is particularily useful any more these days, with most Macs running on Intel. It would be great if you covered the ?. and ?: operators. And perhaps ==~ and =~ as well. Just some very random suggestions. :)

Andrey Khikhlovskiy said...

One-liner for file copy:

new File("NewWordDocument.doc").bytes = new File("WordDocument.doc").bytes

would not work for very large files. bytes (which is shorthand for getBytes()) will try to load all content of the file to operating memory.

Andrey Khikhlovskiy said...

The following one-liner can copy very large files without running out of memory:

new File("test").withInputStream { new File("test2") << it }

Just tested it in groovy console - 1 GB file is copied in 5 seconds, memory consumption stays low.
The copy is binary, i.e. it copies bytes, not chars.
One particularity: left-shift operator rather appends than overwrites. If you need to overwrite the file, first need to delete it.